JSON-RPC API Reference

Overview

OPN Chain provides a complete Ethereum-compatible JSON-RPC API, allowing seamless integration with existing Ethereum tools and libraries. This API follows the Ethereum JSON-RPC specification exactly, ensuring maximum compatibility.

Quick Reference

Endpoint URLs

Network
HTTP Endpoint
WebSocket Endpoint

Testnet

https://testnet-rpc.iopn.tech

wss://testnet-ws.iopn.tech

Mainnet

https://rpc.iopn.tech

wss://ws.iopn.tech

Supported Namespaces

  • web3_* - Web3 specific methods

  • net_* - Network information

  • eth_* - Ethereum compatible methods

  • debug_* - Debug and trace methods

  • txpool_* - Transaction pool information

Making Requests

HTTP Requests

curl -X POST https://testnet-rpc.iopn.tech \
  -H "Content-Type: application/json" \
  --data '{
    "jsonrpc": "2.0",
    "method": "eth_blockNumber",
    "params": [],
    "id": 1
  }'

WebSocket Connections

const WebSocket = require('ws');
const ws = new WebSocket('wss://testnet-ws.iopn.tech');

ws.on('open', function open() {
  ws.send(JSON.stringify({
    jsonrpc: '2.0',
    method: 'eth_subscribe',
    params: ['newHeads'],
    id: 1
  }));
});

ws.on('message', function message(data) {
  console.log('received:', JSON.parse(data));
});

Method Categories

1. Web3 Methods

Basic client and utility methods:

  • web3_clientVersion - Get client version

  • web3_sha3 - Keccak-256 hash function

2. Network Methods

Network status and information:

  • net_version - Network ID

  • net_listening - Listening status

  • net_peerCount - Connected peer count

3. Ethereum Methods

Core blockchain functionality:

  • Reading: eth_getBalance, eth_getCode, eth_getStorageAt

  • Transactions: eth_sendRawTransaction, eth_getTransactionReceipt

  • Blocks: eth_getBlockByNumber, eth_getBlockByHash

  • Filters: eth_newFilter, eth_getFilterChanges

  • Gas: eth_gasPrice, eth_estimateGas

4. Debug Methods

Advanced debugging capabilities:

  • debug_traceTransaction - Detailed transaction traces

  • debug_traceBlockByNumber - Block execution traces

Request Format

All requests must follow the JSON-RPC 2.0 specification:

{
  "jsonrpc": "2.0",
  "method": "method_name",
  "params": [...],
  "id": 1
}

Request Fields

Field
Type
Description

jsonrpc

string

Always "2.0"

method

string

The method name

params

array

Method parameters

id

number/string

Request identifier

Response Format

Success Response

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": "0x..."
}

Error Response

{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32601,
    "message": "Method not found"
  }
}

Error Codes

Code
Message
Description

-32700

Parse error

Invalid JSON

-32600

Invalid request

Invalid request format

-32601

Method not found

Method does not exist

-32602

Invalid params

Invalid method parameters

-32603

Internal error

Internal JSON-RPC error

-32000

Server error

Generic server error

Rate Limits

Default Limits

Endpoint Type
Rate Limit
Window

Public HTTP

100 req/sec

Per IP

Public WebSocket

100 msg/sec

Per connection

Authenticated

1000 req/sec

Per API key

Rate Limit Headers

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1640995200

Best Practices

1. Connection Management

class RPCClient {
  constructor(url) {
    this.url = url;
    this.id = 0;
  }
  
  async call(method, params = []) {
    const response = await fetch(this.url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        method,
        params,
        id: ++this.id
      })
    });
    
    const data = await response.json();
    
    if (data.error) {
      throw new Error(data.error.message);
    }
    
    return data.result;
  }
}

2. Error Handling

try {
  const balance = await client.call('eth_getBalance', [address, 'latest']);
  console.log('Balance:', balance);
} catch (error) {
  if (error.message.includes('rate limit')) {
    // Handle rate limiting
    await sleep(1000);
    return retry();
  }
  throw error;
}

3. Batch Requests

const batchRequest = [
  { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 },
  { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 },
  { jsonrpc: '2.0', method: 'net_version', params: [], id: 3 }
];

const response = await fetch('https://testnet-rpc.iopn.tech', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(batchRequest)
});

const results = await response.json();

Common Use Cases

Get Current Block Number

const blockNumber = await client.call('eth_blockNumber');
console.log('Current block:', parseInt(blockNumber, 16));

Check Account Balance

const balance = await client.call('eth_getBalance', [
  '0x742d35Cc6634C0532925a3b844Bc9e7595f2bD40',
  'latest'
]);
console.log('Balance:', web3.utils.fromWei(balance, 'ether'), 'OPN');

Send Transaction

const signedTx = await web3.eth.accounts.signTransaction({
  to: recipient,
  value: web3.utils.toWei('1', 'ether'),
  gas: 21000,
  gasPrice: '7000000000'
}, privateKey);

const txHash = await client.call('eth_sendRawTransaction', [
  signedTx.rawTransaction
]);

Subscribe to New Blocks

// WebSocket subscription
ws.send(JSON.stringify({
  jsonrpc: '2.0',
  method: 'eth_subscribe',
  params: ['newHeads'],
  id: 1
}));

ws.on('message', (data) => {
  const message = JSON.parse(data);
  if (message.params) {
    console.log('New block:', message.params.result);
  }
});

Testing Your Integration

Health Check Script

async function healthCheck() {
  const tests = [
    { name: 'Client Version', method: 'web3_clientVersion' },
    { name: 'Network ID', method: 'net_version' },
    { name: 'Chain ID', method: 'eth_chainId' },
    { name: 'Block Number', method: 'eth_blockNumber' },
    { name: 'Gas Price', method: 'eth_gasPrice' }
  ];
  
  for (const test of tests) {
    try {
      const result = await client.call(test.method);
      console.log(`✓ ${test.name}:`, result);
    } catch (error) {
      console.log(`✗ ${test.name}: ${error.message}`);
    }
  }
}

Migration from Ethereum

Migrating from Ethereum RPC requires minimal changes:

// Ethereum
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_KEY');

// OPN Chain - Just change the URL!
const web3 = new Web3('https://testnet-rpc.iopn.tech');

Troubleshooting

Connection Refused

  • Check if you're using the correct endpoint URL

  • Verify your firewall settings

  • Try using a different network

Invalid Response

  • Ensure you're sending valid JSON

  • Check method names are correct

  • Verify parameters match expected types

Rate Limiting

  • Implement exponential backoff

  • Use batch requests when possible

  • Consider upgrading to authenticated access


Last updated