# Dwellir API Documentation > Enterprise-grade blockchain RPC infrastructure documentation. API references for 150+ networks including Ethereum, Base, Arbitrum, Polkadot, and Sui. API keys are included directly in endpoint URLs — no Authorization headers needed. # Dwellir API Documentation — Full Content Complete offline reference for Dwellir's blockchain infrastructure platform. - 150+ supported networks - 99.99% uptime SLA - JSON-RPC compatible API endpoints - API key embedded in URL (no Authorization headers) Quick Start: Create an API key at https://dashboard.dwellir.com/register Site index: https://www.dwellir.com/llms.txt ## author_pendingExtrinsics - Acala RPC Method # author_pendingExtrinsics Returns all pending extrinsics in the transaction pool on Acala. ## Use Cases - **Mempool monitoring** - Track pending transactions - **Transaction status** - Check if your transaction is pending for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Pool analysis** - Monitor network activity ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "author_pendingExtrinsics", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_pendingExtrinsics", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const pending = await api.rpc.author.pendingExtrinsics(); console.log('Pending extrinsics:', pending.length); pending.forEach((ext, idx) => { console.log(`${idx}: ${ext.method.section}.${ext.method.method}`); }); await api.disconnect(); ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction --- ## author_rotateKeys - Acala RPC Method # author_rotateKeys Generate a new set of session keys on Acala. This method creates fresh cryptographic keys for validator operations and stores them in the node's keystore. The returned keys must be registered on-chain via `session.setKeys`. ## Use Cases - **Validator setup** - Generate initial session keys for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Key rotation** - Periodically rotate keys for security best practices - **Recovery** - Generate new keys after potential key compromise ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | `Bytes` | Concatenated SCALE-encoded public keys for all session key types | ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_rotateKeys", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Generate new session keys const keys = await api.rpc.author.rotateKeys(); console.log('New session keys:', keys.toHex()); // These keys need to be registered on-chain: // api.tx.session.setKeys(keys, proof) await api.disconnect(); ``` ```python url = 'https://api-acala.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'author_rotateKeys', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json() if 'result' in result: session_keys = result['result'] print(f'New session keys: {session_keys}') print('Register these keys using session.setKeys extrinsic') else: print(f"Error: {result.get('error')}") ``` ## Validator Setup Workflow 1. **Generate keys** - Call `author_rotateKeys` on your validator node 2. **Register on-chain** - Submit `session.setKeys(keys, proof)` extrinsic 3. **Wait for session** - Keys become active in the next session 4. **Verify** - Check `session.nextKeys` storage ## Security Considerations - Only call this method on your own validator node - Session keys are stored in the node's keystore - Rotate keys periodically and after any security incident - Never expose this RPC method publicly ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit setKeys transaction - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - View pending transactions --- ## author_submitAndWatchExtrinsic - Acala RPC Method # author_submitAndWatchExtrinsic Submit a signed extrinsic to and subscribe to status updates. This WebSocket method provides real-time feedback on transaction progress from submission through finalization. ## Use Cases - **Transaction tracking** - Monitor extrinsic lifecycle for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **UI feedback** - Show users real-time transaction status - **Confirmation workflows** - Wait for specific finality level before proceeding ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `Bytes` | Yes | SCALE-encoded signed extrinsic | ## Returns Returns a subscription that emits `ExtrinsicStatus` updates: | Status | Description | |--------|-------------| | `future` | In future queue (nonce too high) | | `ready` | In ready queue, waiting for block | | `broadcast` | Broadcast to peers | | `inBlock` | Included in block (hash provided) | | `retracted` | Block retracted (reorg) | | `finalityTimeout` | Finality timeout | | `finalized` | Finalized in block (hash provided) | | `usurped` | Replaced by another extrinsic | | `dropped` | Dropped from pool | | `invalid` | Invalid extrinsic | ## Code Examples ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const keyring = new Keyring({ type: 'sr25519' }); // Create and sign a transfer const sender = keyring.addFromUri('//Alice'); const transfer = api.tx.balances.transferKeepAlive( '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 1000000000000n ); // Submit and watch const unsub = await transfer.signAndSend(sender, ({ status, events }) => { console.log(`Status: ${status.type}`); if (status.isInBlock) { console.log(`Included in block: ${status.asInBlock.toHex()}`); } if (status.isFinalized) { console.log(`Finalized in block: ${status.asFinalized.toHex()}`); unsub(); } }); ``` ```python async def submit_and_watch(signed_extrinsic_hex): uri = 'wss://api-acala.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: # Submit and subscribe await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'author_submitAndWatchExtrinsic', 'params': [signed_extrinsic_hex], 'id': 1 })) # Get subscription ID response = json.loads(await ws.recv()) if 'error' in response: print(f"Error: {response['error']}") return sub_id = response['result'] print(f'Watching with subscription: {sub_id}') # Listen for status updates while True: message = json.loads(await ws.recv()) if 'params' in message: status = message['params']['result'] print(f"Status: {status}") # Check for finalization if isinstance(status, dict) and 'finalized' in status: print(f"Finalized in: {status['finalized']}") break # asyncio.run(submit_and_watch('0x...')) ``` ## Status Flow ``` ready → broadcast → inBlock → finalized ↘ retracted (if reorg) ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit without watching (fire-and-forget) - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - View transaction pool - [`payment_queryInfo`](./payment_queryInfo) - Estimate fees before submission --- ## author_submitExtrinsic - Acala RPC Method # author_submitExtrinsic Submit a signed extrinsic to Acala for inclusion in a block. ## Use Cases - **Transaction submission** - Broadcast signed transactions - **dApp interactions** - Execute on-chain operations for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Automated systems** - Submit programmatic transactions ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `String` | Yes | Hex-encoded signed extrinsic | ## Request ```json { "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": ["0x..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Transaction hash | ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": ["0x..."], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const keyring = new Keyring({ type: 'sr25519' }); const sender = keyring.addFromUri('//Alice'); // Build and sign transaction const transfer = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000); const hash = await transfer.signAndSend(sender); console.log('Transaction hash:', hash.toHex()); await api.disconnect(); ``` ## Related Methods - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - Get pending transactions - [`payment_queryInfo`](./payment_queryInfo) - Estimate fees --- ## beefy_getFinalizedHead - Acala RPC Method # beefy_getFinalizedHead Returns the block hash of the latest BEEFY-finalized block on Acala. BEEFY (Bridge Efficiency Enabling Finality Yielder) provides additional finality proofs optimized for light clients and bridges. ## Use Cases - **Cross-chain bridges** - Verify finality proofs for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Light clients** - Efficient finality verification without full GRANDPA proofs - **Trustless bridges** - Generate compact finality proofs for external chains ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | `Hash` | Block hash of the latest BEEFY-finalized block | ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "beefy_getFinalizedHead", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get BEEFY finalized head const beefyHead = await api.rpc.beefy.getFinalizedHead(); console.log('BEEFY finalized:', beefyHead.toHex()); // Compare with GRANDPA finalized const grandpaHead = await api.rpc.chain.getFinalizedHead(); console.log('GRANDPA finalized:', grandpaHead.toHex()); await api.disconnect(); ``` ```python url = 'https://api-acala.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'beefy_getFinalizedHead', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json() if 'result' in result: print(f"BEEFY finalized: {result['result']}") else: print(f"Error: {result.get('error')}") ``` ## BEEFY vs GRANDPA Finality | Aspect | GRANDPA | BEEFY | |--------|---------|-------| | **Purpose** | Primary finality | Bridge-optimized finality | | **Proof size** | Larger (full validator set) | Compact (aggregated signatures) | | **Latency** | Immediate | Slightly delayed | | **Use case** | On-chain finality | Cross-chain bridges | ## Availability BEEFY is enabled on relay chains and some parachains. If BEEFY is not enabled, this method will return an error. ## Related Methods - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - GRANDPA finalized head - [`grandpa_roundState`](./grandpa_roundState) - GRANDPA consensus state - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks --- ## chain_getBlock - Acala RPC Method # chain_getBlock Retrieves complete block information from Acala, including the block header, extrinsics, and justifications. > **Why Acala?** Build on Polkadot's DeFi and liquidity hub with aUSD stablecoin and liquid staking (LDOT) with $250M aUSD ecosystem fund, 150%+ LDOT TVL growth, micro gas fees payable in any token, and Coinbase Cloud partnership. ## Use Cases The `chain_getBlock` method is essential for: - **Block explorers** - Display complete block information - **Chain analysis** - Analyze block production patterns - **Transaction verification** - Confirm extrinsic inclusion for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Data indexing** - Build historical blockchain databases ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Hex-encoded block hash. If omitted, returns latest block | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getBlock", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `block` | `Object` | Complete block data | | `block.header` | `Object` | Block header information | | `block.header.parentHash` | `String` | Hash of the parent block | | `block.header.number` | `String` | Block number (hex-encoded) | | `block.header.stateRoot` | `String` | Root of the state trie | | `block.header.extrinsicsRoot` | `String` | Root of the extrinsics trie | | `block.extrinsics` | `Array` | Array of extrinsics in the block | | `justifications` | `Array` | Block justifications (if available) | ## Code Examples ```bash # Get latest block curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": [], "id": 1 }' # Get specific block curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get latest block const latestHash = await api.rpc.chain.getBlockHash(); const latestBlock = await api.rpc.chain.getBlock(latestHash); console.log('Latest block:', { number: latestBlock.block.header.number.toNumber(), hash: latestHash.toHex(), extrinsicsCount: latestBlock.block.extrinsics.length }); // Get specific block const blockHash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'; const block = await api.rpc.chain.getBlock(blockHash); console.log('Block extrinsics:', block.block.extrinsics.length); await api.disconnect(); ``` ```python def get_block(block_hash=None): url = 'https://api-acala.n.dwellir.com/YOUR_API_KEY' params = [block_hash] if block_hash else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getBlock', 'params': params, 'id': 1 } response = requests.post(url, json=payload) data = response.json() if 'error' in data: raise Exception(f"RPC Error: {data['error']}") return data['result'] # Get latest block latest_block = get_block() block_number = int(latest_block['block']['header']['number'], 16) print(f'Latest block number: {block_number}') # Get specific block specific_block = get_block('0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3') print(f"Extrinsics count: {len(specific_block['block']['extrinsics'])}") ``` ## Related Methods - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number - [`chain_getHeader`](./chain_getHeader) - Get block header only - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get finalized block hash --- ## chain_getBlockHash - Acala RPC Method # chain_getBlockHash Returns the block hash for a given block number on Acala. ## Use Cases - **Historical queries** - Convert block numbers to hashes - **Block navigation** - Navigate blockchain history for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Data indexing** - Build block number to hash mappings ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `Number` | No | Block number. If omitted, returns latest block hash | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getBlockHash", "params": [1000000], "id": 1 } ``` ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlockHash", "params": [1000000], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get hash for specific block number const blockNumber = 1000000; const blockHash = await api.rpc.chain.getBlockHash(blockNumber); console.log(`Block ${blockNumber} hash:`, blockHash.toHex()); await api.disconnect(); ``` ```python def get_block_hash(block_number=None): url = 'https://api-acala.n.dwellir.com/YOUR_API_KEY' params = [block_number] if block_number is not None else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getBlockHash', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] block_hash = get_block_hash(1000000) print(f'Block hash: {block_hash}') ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get block by hash - [`chain_getHeader`](./chain_getHeader) - Get block header --- ## chain_getFinalizedHead - Acala RPC Method # chain_getFinalizedHead Returns the hash of the last finalized block on Acala. ## Use Cases - **Confirmed state** - Query state that cannot be reverted - **Transaction confirmation** - Verify transaction finality for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Safe checkpoints** - Use finalized blocks for critical operations ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const finalizedHash = await api.rpc.chain.getFinalizedHead(); console.log('Finalized block hash:', finalizedHash.toHex()); // Get finalized block details const block = await api.rpc.chain.getBlock(finalizedHash); console.log('Finalized block number:', block.block.header.number.toNumber()); await api.disconnect(); ``` ```python def get_finalized_head(): url = 'https://api-acala.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'chain_getFinalizedHead', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] finalized_hash = get_finalized_head() print(f'Finalized block hash: {finalized_hash}') ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get block by hash - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number --- ## chain_getHeader - Acala RPC Method # chain_getHeader Returns the block header for a given hash on Acala. ## Use Cases - **Lightweight queries** - Get header without full block data - **Chain synchronization** - Track block production for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Parent chain navigation** - Follow parentHash links ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash. If omitted, returns latest header | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getHeader", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 } ``` ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getHeader", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get latest header const header = await api.rpc.chain.getHeader(); console.log('Block number:', header.number.toNumber()); console.log('Parent hash:', header.parentHash.toHex()); await api.disconnect(); ``` ```python def get_header(block_hash=None): url = 'https://api-acala.n.dwellir.com/YOUR_API_KEY' params = [block_hash] if block_hash else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getHeader', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] header = get_header() print(f"Block number: {int(header['number'], 16)}") ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get full block with extrinsics - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number --- ## chain_subscribeFinalizedHeads - Acala RPC Method # chain_subscribeFinalizedHeads Subscribe to receive notifications when blocks are finalized on Acala. Finalized blocks are guaranteed to never be reverted, making this essential for applications requiring strong consistency. ## Use Cases - **Exchange deposits** - Only credit funds after finalization for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Bridge operations** - Wait for finality before cross-chain transfers - **Critical state changes** - Ensure irreversibility for important transactions ## Parameters This method takes no parameters. ## Returns Returns a subscription ID. The subscription emits `Header` objects for each finalized block: | Field | Type | Description | |-------|------|-------------| | `parentHash` | `Hash` | Parent block hash | | `number` | `BlockNumber` | Block number | | `stateRoot` | `Hash` | State trie root hash | | `extrinsicsRoot` | `Hash` | Extrinsics trie root hash | | `digest` | `Digest` | Block digest with consensus logs | ## Code Examples ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Subscribe to finalized heads const unsubscribe = await api.rpc.chain.subscribeFinalizedHeads((header) => { console.log(`Finalized block #${header.number}`); console.log(` Hash: ${header.hash.toHex()}`); // Safe to consider this block permanent processConfirmedBlock(header); }); // Later: unsubscribe() ``` ```python async def subscribe_finalized(): uri = 'wss://api-acala.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'chain_subscribeFinalizedHeads', 'params': [], 'id': 1 })) response = json.loads(await ws.recv()) sub_id = response['result'] print(f'Subscribed to finalized heads: {sub_id}') while True: message = json.loads(await ws.recv()) if 'params' in message: header = message['params']['result'] block_num = int(header['number'], 16) print(f"Finalized: #{block_num}") asyncio.run(subscribe_finalized()) ``` ## Finality Lag Finalized blocks typically lag behind the best block by a few blocks due to GRANDPA consensus requirements. This is normal and ensures Byzantine fault tolerance. ## Related Methods - [`chain_subscribeNewHeads`](./chain_subscribeNewHeads) - Subscribe to all new blocks (not just finalized) - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get current finalized block hash - [`grandpa_roundState`](./grandpa_roundState) - Monitor GRANDPA consensus progress --- ## chain_subscribeNewHeads - Acala RPC Method # chain_subscribeNewHeads Subscribe to receive notifications when new block headers are produced on Acala. This WebSocket subscription provides real-time updates for each new block. ## Use Cases - **Block monitoring** - Track new blocks in real-time for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Event indexing** - Trigger processing when new blocks arrive - **Chain synchronization** - Keep external systems in sync with the chain ## Parameters This method takes no parameters. ## Returns Returns a subscription ID. The subscription emits `Header` objects for each new block: | Field | Type | Description | |-------|------|-------------| | `parentHash` | `Hash` | Parent block hash | | `number` | `BlockNumber` | Block number | | `stateRoot` | `Hash` | State trie root hash | | `extrinsicsRoot` | `Hash` | Extrinsics trie root hash | | `digest` | `Digest` | Block digest with consensus logs | ## Code Examples ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Subscribe to new heads const unsubscribe = await api.rpc.chain.subscribeNewHeads((header) => { console.log(`New block #${header.number}`); console.log(` Hash: ${header.hash.toHex()}`); console.log(` Parent: ${header.parentHash.toHex()}`); console.log(` State root: ${header.stateRoot.toHex()}`); }); // Later: unsubscribe() ``` ```python async def subscribe_new_heads(): uri = 'wss://api-acala.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: # Subscribe to new heads await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'chain_subscribeNewHeads', 'params': [], 'id': 1 })) # Get subscription ID response = json.loads(await ws.recv()) sub_id = response['result'] print(f'Subscribed with ID: {sub_id}') # Listen for new headers while True: message = json.loads(await ws.recv()) if 'params' in message: header = message['params']['result'] print(f"Block #{int(header['number'], 16)}") print(f" Hash: {header['parentHash']}") asyncio.run(subscribe_new_heads()) ``` ## Subscription vs Polling | Approach | Latency | Resource Usage | Use Case | |----------|---------|----------------|----------| | `subscribeNewHeads` | Immediate | Low (push-based) | Real-time monitoring | | Polling `getHeader` | Block time + poll interval | Higher (repeated requests) | Simple integrations | ## Related Methods - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks only - [`chain_getHeader`](./chain_getHeader) - Get a specific block header - [`chain_getBlock`](./chain_getBlock) - Get full block with extrinsics --- ## grandpa_roundState - Acala RPC Method # grandpa_roundState Returns the state of the current GRANDPA finality round on Acala. GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) is the finality gadget used by Substrate chains. ## Use Cases - **Finality monitoring** - Track consensus progress for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Validator analysis** - Monitor prevote/precommit participation - **Chain health checks** - Detect finality delays or stalls ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `setId` | `u64` | Current authority set ID | | `best` | `RoundState` | Best round state | | `background` | `Vec` | Background rounds | ### RoundState Structure | Field | Type | Description | |-------|------|-------------| | `round` | `u64` | Round number | | `totalWeight` | `u64` | Total validator weight | | `thresholdWeight` | `u64` | Weight needed for supermajority | | `prevotes` | `Prevotes` | Prevote information | | `precommits` | `Precommits` | Precommit information | ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "grandpa_roundState", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const roundState = await api.rpc.grandpa.roundState(); console.log('Set ID:', roundState.setId.toString()); console.log('Best round:', roundState.best.round.toString()); console.log('Total weight:', roundState.best.totalWeight.toString()); console.log('Threshold:', roundState.best.thresholdWeight.toString()); await api.disconnect(); ``` ```python url = 'https://api-acala.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'grandpa_roundState', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json()['result'] print(f"Set ID: {result['setId']}") print(f"Round: {result['best']['round']}") print(f"Total weight: {result['best']['totalWeight']}") ``` ## Understanding GRANDPA Rounds 1. **Prevote phase** - Validators vote on best block they've seen 2. **Precommit phase** - Validators commit to finalize if supermajority prevoted 3. **Finalization** - Block is finalized when 2/3+ weight precommits ## Related Methods - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get current finalized hash - [`beefy_getFinalizedHead`](./beefy_getFinalizedHead) - BEEFY finality (if enabled) --- ## Acala RPC with Dwellir # Acala – DeFi Hub Parachain on Polkadot ## Why Build on Acala? Acala is a DeFi-focused parachain on the Polkadot relay chain that provides a stablecoin (aUSD), liquid staking (LDOT), and EVM+Substrate interoperability. Built on Substrate, Acala exposes the standard JSON‑RPC namespaces developers rely on for production‑grade integrations. ### 🚀 DeFi Primitives Out of the Box - aUSD stablecoin, LDOT liquid staking, DEX and more, available through standard pallets and EVM. - Seamless cross‑chain asset routing via XCM to and from Polkadot ecosystems. ### 🧰 Familiar Tooling - Works with polkadot.js, Subxt (Rust), and py‑substrate‑interface (Python). - Dwellir provides globally anycasted endpoints with low‑latency routing and high availability. ### 🔒 Security Inherited from Polkadot - As parachain `2000` on Polkadot, Acala benefits from shared security and fast finality. ## Quick Start Connect to Acala’s production endpoints. ### Installation & Setup ```ts async function main() { const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const [chain, version] = await Promise.all([ api.rpc.system.chain(), api.rpc.system.version(), ]); console.log(`Connected to ${chain.toString()} v${version.toString()}`); // Subscribe to new blocks const unsub = await api.rpc.chain.subscribeNewHeads((header) => { console.log(`New block #${header.number} ${header.hash.toHex()}`); }); // Stop after 3 blocks setTimeout(async () => { await unsub(); await api.disconnect(); }, 18000); } main().catch(console.error); ``` ```bash curl -s https://api-acala.n.dwellir.com/YOUR_API_KEY \ -H 'Content-Type: application/json' \ -d '{ "jsonrpc": "2.0", "method": "chain_getHeader", "params": [], "id": 1 }' ``` ```rust use subxt::{OnlineClient, PolkadotConfig}; #[tokio::main] async fn main() -> Result<(), Box> { let api = OnlineClient::::from_url( "wss://api-acala.n.dwellir.com/YOUR_API_KEY" ).await?; let header = api.rpc().block_header(None).await?.expect("latest header"); println!("Latest block: #{:?} (hash {:?})", header.number, header.hash()); Ok(()) } ``` ```python from substrateinterface import SubstrateInterface substrate = SubstrateInterface( url="wss://api-acala.n.dwellir.com/YOUR_API_KEY", type_registry_preset="substrate-node-template" # use custom types if needed ) chain = substrate.rpc_request("system_chain", []) print(f"Connected to {chain['result']}") head = substrate.rpc_request("chain_getFinalizedHead", []) print(f"Finalized head: {head['result']}") ``` ## Network Information Genesis Hash 0xfc41b9bd…ba64c Verified via chain_getBlockHash(0) Native Token ACA 12 decimals SS58 Prefix 10 Address format Runtime Spec Version 2300 state_getRuntimeVersion (Oct 9, 2025) Transaction Version 3 state_getRuntimeVersion Explorer Subscan acala.subscan.io Acala runs as Polkadot parachain `2000`. Token properties and address prefix were verified using `system_properties`; genesis hash via `chain_getBlockHash(0)`; runtime versions via `state_getRuntimeVersion` on October 9, 2025. ## Substrate JSON‑RPC API Reference Acala exposes the core Substrate RPC namespaces for node telemetry, block production, storage access, and transaction submission. Use the menu below to open the method guides. ## Common Integration Patterns ### Subscribe to Finality and New Heads ```ts const unsubFinal = await api.rpc.chain.subscribeFinalizedHeads((h) => console.log(`Finalized #${h.number} ${h.hash.toHex()}`) ); const unsubNew = await api.rpc.chain.subscribeNewHeads((h) => console.log(`New #${h.number}`) ); ``` ### Paginate Large Storage Scans ```ts const keys = await api.rpc.state.getKeysPaged( // System.Account prefix '0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9', 100, '0x', null ); console.log('Fetched', keys.length, 'keys'); ``` ### Estimate Fees Before Broadcasting ```ts const ext = api.tx.balances.transferAllowDeath('ADDRESS', 1_000_000_000_000); const info = await api.rpc.payment.queryInfo(ext.toHex()); console.log(`PartialFee: ${info.partialFee.toHuman()}`); ``` ## Performance Best Practices - Prefer WebSocket connections for subscriptions and multi‑round queries. - Cache runtime metadata and type bundles; reuse ApiPromise across requests. - Use `state_getKeysPaged` for large map scans; avoid full‑chain scans. - Implement reconnection/backoff and share a connection pool across services. ## Troubleshooting - Connection refused: ensure your API key is appended and outbound TCP/443 is allowed. - Invalid SS58: addresses must use prefix `10` for Acala. - Type errors: refresh metadata after runtime upgrades (`api.runtimeVersion`). - Extrinsic failed: decode dispatch error via `api.registry.findMetaError`. ## Smoke Tests Run these minimal checks against production endpoints (captured Oct 9, 2025): ```bash # Node health (peers ≈ 15, isSyncing false) curl -s https://api-acala.n.dwellir.com/YOUR_API_KEY \ -H 'Content-Type: application/json' \ -d '{"jsonrpc":"2.0","id":1,"method":"system_health","params":[]}' # Latest block header (e.g. number ~ 9617916) curl -s https://api-acala.n.dwellir.com/YOUR_API_KEY \ -H 'Content-Type: application/json' \ -d '{"jsonrpc":"2.0","id":1,"method":"chain_getHeader","params":[]}' # Finalized head hash (e.g. 0xdcdcc29c…f13e7) curl -s https://api-acala.n.dwellir.com/YOUR_API_KEY \ -H 'Content-Type: application/json' \ -d '{"jsonrpc":"2.0","id":1,"method":"chain_getFinalizedHead","params":[]}' # Runtime versions (specVersion 2300, transactionVersion 3) curl -s https://api-acala.n.dwellir.com/YOUR_API_KEY \ -H 'Content-Type: application/json' \ -d '{"jsonrpc":"2.0","id":1,"method":"state_getRuntimeVersion","params":[]}' ``` ## Migration Guide (from Polkadot/Kusama) - Endpoints: replace with `https://api-acala.n.dwellir.com/YOUR_API_KEY` or `wss://api-acala.n.dwellir.com/YOUR_API_KEY`. - Addresses: re‑encode SS58 addresses with prefix `10`. - Types: include Acala custom types where applicable; refresh metadata after upgrades. - Fees: re‑calibrate using `payment_queryInfo`; fee multipliers differ across chains. ## Resources & Tools - Acala Portal: https://acala.network - Explorer: https://acala.subscan.io - Substrate Developer Hub: https://docs.substrate.io/ - Dwellir Dashboard – Get your API key: https://dashboard.dwellir.com/register --- ## payment_queryFeeDetails - Acala RPC Method # payment_queryFeeDetails Returns a detailed breakdown of fees for a given extrinsic on Acala. Unlike `payment_queryInfo` which returns the total fee, this method separates the fee into its component parts. ## Use Cases - **Fee analysis** - Understand fee composition for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Optimization** - Identify which fee component dominates costs - **Debugging** - Diagnose unexpected fee amounts ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `Bytes` | Yes | SCALE-encoded extrinsic (signed or unsigned) | | `blockHash` | `Hash` | No | Block hash for fee calculation context | ## Returns | Field | Type | Description | |-------|------|-------------| | `inclusionFee` | `Option` | Fee details (null for unsigned extrinsics) | ### InclusionFee Structure | Field | Type | Description | |-------|------|-------------| | `baseFee` | `Balance` | Fixed base fee per extrinsic | | `lenFee` | `Balance` | Fee based on encoded extrinsic length | | `adjustedWeightFee` | `Balance` | Fee based on execution weight | ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "payment_queryFeeDetails", "params": ["0x...encodedExtrinsic"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Create a sample transfer const tx = api.tx.balances.transferKeepAlive( '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 1000000000000n ); // Get fee details const feeDetails = await api.rpc.payment.queryFeeDetails(tx.toHex()); if (feeDetails.inclusionFee.isSome) { const fee = feeDetails.inclusionFee.unwrap(); console.log('Base fee:', fee.baseFee.toString()); console.log('Length fee:', fee.lenFee.toString()); console.log('Weight fee:', fee.adjustedWeightFee.toString()); } await api.disconnect(); ``` ```python url = 'https://api-acala.n.dwellir.com/YOUR_API_KEY' # Replace with actual encoded extrinsic encoded_extrinsic = '0x...' payload = { 'jsonrpc': '2.0', 'method': 'payment_queryFeeDetails', 'params': [encoded_extrinsic], 'id': 1 } response = requests.post(url, json=payload) result = response.json()['result'] if result['inclusionFee']: fee = result['inclusionFee'] print(f"Base fee: {fee['baseFee']}") print(f"Length fee: {fee['lenFee']}") print(f"Weight fee: {fee['adjustedWeightFee']}") ``` ## Fee Components Explained | Component | Calculation | Optimization | |-----------|-------------|--------------| | **Base fee** | Fixed per extrinsic | Batch calls to share base fee | | **Length fee** | `length * lengthToFee` | Minimize call data size | | **Weight fee** | `weight * weightToFee` | Choose efficient operations | ## Related Methods - [`payment_queryInfo`](./payment_queryInfo) - Get total fee estimate - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction - [`state_call`](./state_call) - Call TransactionPaymentApi directly --- ## payment_queryInfo - Acala RPC Method # payment_queryInfo Estimates the fee for an extrinsic on Acala. ## Use Cases - **Fee estimation** - Calculate transaction costs before sending - **UI display** - Show fees to users for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Transaction planning** - Ensure sufficient funds ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `String` | Yes | Hex-encoded unsigned extrinsic | | `blockHash` | `String` | No | Block hash for fee calculation | ## Request ```json { "jsonrpc": "2.0", "method": "payment_queryInfo", "params": ["0x..."], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `weight` | `Object` | Transaction weight | | `class` | `String` | Dispatch class | | `partialFee` | `String` | Estimated fee | ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "payment_queryInfo", "params": ["0x..."], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Create transfer (unsigned for estimation) const transfer = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000); const info = await transfer.paymentInfo('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'); console.log('Partial fee:', info.partialFee.toHuman()); await api.disconnect(); ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction --- ## rpc_methods - Acala RPC Method # rpc_methods Returns a list of all RPC methods available on Acala. ## Use Cases - **API discovery** - List all available methods - **Compatibility checking** - Verify method availability for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Documentation** - Auto-generate method lists ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const methods = await api.rpc.rpc.methods(); console.log('Available methods:', methods.methods.length); await api.disconnect(); ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## state_call - Acala RPC Method # state_call Calls a runtime API method on Acala. ## Use Cases - **Runtime computations** - Execute runtime logic without transactions - **Account queries** - Use AccountNonceApi for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Fee estimation** - Use TransactionPaymentApi ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `method` | `String` | Yes | Runtime API method name | | `data` | `String` | Yes | SCALE-encoded call data | | `blockHash` | `String` | No | Block hash for historical call | ## Request ```json { "jsonrpc": "2.0", "method": "state_call", "params": ["AccountNonceApi_account_nonce", "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"], "id": 1 } ``` ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_call", "params": ["AccountNonceApi_account_nonce", "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get account nonce via runtime API const account = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const result = await api.call.accountNonceApi.accountNonce(account); console.log('Account nonce:', result.toNumber()); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Query storage - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## state_getKeysPaged - Acala RPC Method # state_getKeysPaged Returns storage keys with pagination on Acala. ## Use Cases - **Storage iteration** - Enumerate storage map entries - **Data export** - Bulk export chain data for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Account enumeration** - List all accounts ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `prefix` | `String` | Yes | Storage key prefix | | `count` | `Number` | Yes | Maximum keys to return | | `startKey` | `String` | No | Key to start after | | `blockHash` | `String` | No | Block hash for historical query | ## Request ```json { "jsonrpc": "2.0", "method": "state_getKeysPaged", "params": ["0x...", 100], "id": 1 } ``` ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getKeysPaged", "params": ["0x26aa394eea5630e07c48ae0c9558cef7", 100], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get all accounts (paginated) const keys = await api.rpc.state.getKeysPaged( api.query.system.account.keyPrefix(), 100 ); console.log('Found accounts:', keys.length); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Get storage value - [`state_queryStorageAt`](./state_queryStorageAt) - Batch storage query --- ## state_getMetadata - Acala RPC Method # state_getMetadata Returns the runtime metadata on Acala. ## Use Cases - **Runtime introspection** - Discover available pallets and calls - **Extrinsic building** - Get call and type information for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Storage key generation** - Build storage keys from metadata - **Client generation** - Auto-generate typed APIs ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash for historical metadata | ## Request ```json { "jsonrpc": "2.0", "method": "state_getMetadata", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getMetadata", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get runtime metadata const metadata = await api.rpc.state.getMetadata(); // List available pallets const pallets = metadata.asLatest.pallets.map(p => p.name.toString()); console.log('Available pallets:', pallets); // Get specific pallet info const systemPallet = metadata.asLatest.pallets.find(p => p.name.toString() === 'System'); console.log('System pallet calls:', systemPallet.calls.isSome ? 'Available' : 'None'); await api.disconnect(); ``` ```python def get_metadata(): url = 'https://api-acala.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'state_getMetadata', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] metadata_hex = get_metadata() print(f'Metadata length: {len(metadata_hex)} bytes') ``` ## Related Methods - [`state_getRuntimeVersion`](./state_getRuntimeVersion) - Get runtime version - [`state_getStorage`](./state_getStorage) - Query storage --- ## state_getRuntimeVersion - Acala RPC Method # state_getRuntimeVersion Returns the runtime version on Acala. ## Use Cases - **Version checking** - Verify runtime compatibility - **Upgrade detection** - Monitor for runtime upgrades on decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Client compatibility** - Ensure API compatibility ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash for historical version | ## Request ```json { "jsonrpc": "2.0", "method": "state_getRuntimeVersion", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getRuntimeVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const version = await api.rpc.state.getRuntimeVersion(); console.log('Spec name:', version.specName.toString()); console.log('Spec version:', version.specVersion.toNumber()); console.log('Impl version:', version.implVersion.toNumber()); await api.disconnect(); ``` ```python def get_runtime_version(): url = 'https://api-acala.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'state_getRuntimeVersion', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] version = get_runtime_version() print(f"Spec: {version['specName']} v{version['specVersion']}") ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata - [`system_version`](./system_version) - Get node version --- ## state_getStorage - Acala RPC Method # state_getStorage Returns a storage entry at a specific key on Acala. > **Why Acala?** Build on Polkadot's DeFi and liquidity hub with aUSD stablecoin and liquid staking (LDOT) with $250M aUSD ecosystem fund, 150%+ LDOT TVL growth, micro gas fees payable in any token, and Coinbase Cloud partnership. ## Use Cases - **State queries** - Read on-chain storage values - **Account balances** - Query account data for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Pallet storage** - Access runtime storage items - **Historical state** - Query state at specific blocks ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `key` | `String` | Yes | Storage key (hex-encoded) | | `blockHash` | `String` | No | Block hash for historical query | ## Request ```json { "jsonrpc": "2.0", "method": "state_getStorage", "params": [""], "id": 1 } ``` ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getStorage", "params": [""], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query account balance const account = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const accountInfo = await api.query.system.account(account); console.log('Free balance:', accountInfo.data.free.toString()); // Query at specific block const blockHash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'; const historicalBalance = await api.query.system.account.at(blockHash, account); console.log('Historical balance:', historicalBalance.data.free.toString()); await api.disconnect(); ``` ```python def get_storage(key, block_hash=None): url = 'https://api-acala.n.dwellir.com/YOUR_API_KEY' params = [key] if block_hash is None else [key, block_hash] payload = { 'jsonrpc': '2.0', 'method': 'state_getStorage', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] # Query :code storage (runtime wasm) storage_key = '' value = get_storage(storage_key) print(f'Storage value: {value[:66]}...' if value else 'None') ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata - [`state_getKeysPaged`](./state_getKeysPaged) - Enumerate storage keys --- ## state_queryStorageAt - Acala RPC Method # state_queryStorageAt Query multiple storage keys at a specific block on Acala. ## Use Cases - **Batch queries** - Efficiently query multiple storage items - **Snapshot state** - Get consistent multi-key state for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Data analysis** - Compare storage across blocks ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `keys` | `Array` | Yes | Array of storage keys | | `blockHash` | `String` | No | Block hash for query | ## Request ```json { "jsonrpc": "2.0", "method": "state_queryStorageAt", "params": [[""]], "id": 1 } ``` ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_queryStorageAt", "params": [[""]], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query multiple accounts at once const accounts = ['5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY']; const entries = await api.query.system.account.multi(accounts); entries.forEach((info, idx) => { console.log(`Account ${idx}: ${info.data.free.toString()}`); }); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Single storage query - [`state_getKeysPaged`](./state_getKeysPaged) - Enumerate keys --- ## system_chain - Acala RPC Method # system_chain Returns the chain name on Acala. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const chain = await api.rpc.system.chain(); console.log('Chain:', chain.toString()); await api.disconnect(); ``` ## Related Methods - [`system_name`](./system_name) - Get node implementation name - [`system_version`](./system_version) - Get node version --- ## system_health - Acala RPC Method # system_health Returns the health status of the Acala node. ## Use Cases - **Health checks** - Monitor node availability - **Load balancing** - Route traffic based on health for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **Sync status** - Verify node is synced ## Parameters This method accepts no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `peers` | `Number` | Connected peer count | | `isSyncing` | `Boolean` | Whether node is syncing | | `shouldHavePeers` | `Boolean` | Whether node should have peers | ## Request ```json { "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const health = await api.rpc.system.health(); console.log('Peers:', health.peers.toNumber()); console.log('Is syncing:', health.isSyncing.isTrue); await api.disconnect(); ``` ```python def get_health(): url = 'https://api-acala.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'system_health', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] health = get_health() print(f"Peers: {health['peers']}") print(f"Syncing: {health['isSyncing']}") ``` ## Related Methods - [`system_version`](./system_version) - Get node version - [`system_chain`](./system_chain) - Get chain name --- ## system_name - Acala RPC Method # system_name Returns the node implementation name on Acala. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_name", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_name", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const name = await api.rpc.system.name(); console.log('Node name:', name.toString()); await api.disconnect(); ``` ## Related Methods - [`system_version`](./system_version) - Get node version - [`system_chain`](./system_chain) - Get chain name --- ## system_properties - Acala RPC Method # system_properties Returns chain properties including token symbol and decimals on Acala. ## Use Cases - **Token formatting** - Get decimals and symbol for decentralized stablecoin (aUSD), liquid DOT staking (LDOT), and cross-chain AMM DEX - **UI configuration** - Configure wallets and dApps - **Address formatting** - Get SS58 prefix ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_properties", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_properties", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const props = await api.rpc.system.properties(); console.log('Token symbol:', props.tokenSymbol.toString()); console.log('Token decimals:', props.tokenDecimals.toString()); console.log('SS58 prefix:', props.ss58Format.toString()); await api.disconnect(); ``` ## Related Methods - [`system_chain`](./system_chain) - Get chain name - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## system_version - Acala RPC Method # system_version Returns the node implementation version on Acala. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_version", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-acala.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_version", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-acala.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const version = await api.rpc.system.version(); console.log('Version:', version.toString()); await api.disconnect(); ``` ## Related Methods - [`system_chain`](./system_chain) - Get chain name - [`state_getRuntimeVersion`](./state_getRuntimeVersion) - Get runtime version --- ## Agent Tooling Dwellir builds tools and infrastructure that AI coding agents can use directly. This page covers the CLI, agent skills, migration automation, and the documentation endpoints that make Dwellir's docs consumable by agents without HTML parsing. ## Dwellir CLI The [Dwellir CLI](/cli) gives agents full access to the Dwellir platform from the command line. Every command supports `--json` output wrapped in a standard `{ok, data, meta}` envelope, and the CLI auto-selects JSON when stdout is not a terminal. Key capabilities for agents: - **Endpoint discovery**: `dwellir endpoints list --json` returns the full catalog of 150+ blockchain endpoints with connection URLs, node types, and ecosystems. - **API key management**: Create, rotate, and delete API keys programmatically with `dwellir keys create --name "agent-key" --json`. - **Usage analytics**: Query request counts, RPS, costs, and error logs with structured JSON output. - **Built-in docs**: `dwellir docs list` and `dwellir docs get ` fetch Dwellir documentation as markdown directly in the terminal. Install the CLI: ```bash curl -fsSL https://raw.githubusercontent.com/dwellir-public/cli/main/scripts/install.sh | sh ``` See the full [CLI documentation](/cli) for all commands and flags. ## Hyperliquid Agent Skill The [Hyperliquid agent skill](https://github.com/dwellir-public/hyperliquid-skills) gives AI coding agents procedural knowledge for building on Hyperliquid through Dwellir's infrastructure. It follows the open [Agent Skills standard](https://skills.sh), making it portable across 40+ AI coding agents including Claude Code, Cursor, and Windsurf. ### What the skill provides Once installed, the skill automatically activates when an agent encounters Hyperliquid-related tasks. It equips the agent with knowledge of: - **HyperEVM JSON-RPC**: Query EVM state, deploy Solidity contracts (Chain ID: 999, gas token: HYPE) - **Info API**: Access market data, prices, order books, candles, funding rates, user positions and balances - **gRPC streaming**: Stream real-time L1 block data, fill executions, and order book snapshots - **Order book WebSocket**: Real-time L2 and L4 depth data from edge servers in Singapore and Tokyo - **Native API routing**: The skill teaches agents to route read operations through Dwellir endpoints and write operations (orders, transfers) through Hyperliquid's native API with EIP-712 signatures ### Install ```bash npx skills add dwellir-public/hyperliquid-skills ``` This installs the skill into your project's `.claude/skills/` directory. No manual invocation is needed. - [View on Skills.sh](https://skills.sh/dwellir-public/hyperliquid-skills/hyperliquid) - [GitHub repository](https://github.com/dwellir-public/hyperliquid-skills) - [Hyperliquid API documentation](/hyperliquid) ## RPC Migration Prompt The migration prompt automates switching a project's blockchain RPC endpoints from other providers to Dwellir. Copy it into your AI agent's context or use it as a system prompt. It walks agents through a structured 5-phase process: environment discovery, codebase scanning, compatibility matching, migration, and summary reporting.
View and copy the migration prompt ````text Migrate this project's blockchain RPC endpoints to Dwellir. Follow the phases below in order. Use subagents and background processes to parallelize work wherever your tooling supports it. ## Phase 1 — Environment & Endpoint Discovery 1. Check whether the Dwellir CLI is installed by running `dwellir --version`. If the command is not found, suggest the user install it: curl -fsSL https://raw.githubusercontent.com/dwellir-public/cli/main/scripts/install.sh | sh 2. Obtain the full list of Dwellir-supported chains, networks, and node types (full vs archive). Try one of these approaches in order until one succeeds: a. **CLI** (preferred): Run `dwellir endpoints list` to get the complete endpoint catalog. b. **Documentation**: If the CLI is unavailable or the user declines to install it, fetch https://www.dwellir.com/docs.md or https://www.dwellir.com/networks.md for the supported endpoint list. c. **Dashboard export**: As a last resort, ask the user to go to dashboard.dwellir.com/endpoints and press the Export button (top-left) to export all endpoints as CSV, Markdown, or JSON, then share the file with you. 3. Check whether the project uses separate configurations per environment (production, staging, development, etc.). If it does, ask the user to provide a Dwellir API key for each environment. If there is only one environment, ask for a single key. ## Phase 2 — Codebase Discovery Scan the entire codebase in parallel where possible: 1. Find every RPC endpoint URL (look for domains like infura.io, alchemy.com, quicknode.com, chainstack.com, ankr.com, blast.io, drpc.org, and any other known RPC providers, as well as raw IP/port patterns and chain-specific gateway URLs). 2. Identify each endpoint's chain, network, and authentication method (API key in URL path, header, query param, or none). 3. Determine whether the code requires an archive node or a full node for each endpoint (look for calls to historical state such as eth_getBalance at old block heights, debug_*/trace_* namespaces, or large block-range log filters). 4. Check if the codebase interacts with Hyperliquid. If it does, suggest that the user install Dwellir's Hyperliquid Skills: npx skills add https://github.com/dwellir-public/hyperliquid-skills ## Phase 3 — Compatibility Matching For each discovered endpoint: 1. Compare the chain + network against the Dwellir endpoints list from Phase 1. Note that some providers (especially for EVM chains) use chain ID-based naming in their URLs rather than chain + network names — resolve any ambiguity by calling the endpoint's RPC method for chain ID (e.g., eth_chainId) and comparing the result against the chain ID returned by the corresponding Dwellir endpoint to confirm they serve the same network. 2. If the code requires an archive node and Dwellir only offers a full node for that chain, mark the endpoint as unsupported and do NOT migrate it. 3. For EVM chains, check whether the codebase depends on client-specific response shapes (e.g., Geth/Erigon trace formats vs Reth, differences in debug_traceTransaction output, or Parity-style trace_* responses). Use web search if needed to understand current client-level differences. Flag any potential incompatibilities. ## Phase 4 — Migration 1. Create a new branch (e.g., chore/migrate-to-dwellir) — NEVER commit directly to main. 2. For each supported endpoint, replace the provider URL with the equivalent Dwellir endpoint URL and update the authentication to use the correct Dwellir API key for each environment. Preserve the existing configuration pattern (env var, config file, etc.). 3. If any endpoints, chains, or networks in the codebase are NOT supported by Dwellir, do not touch them. ## Phase 5 — Summary Present a clear summary with: - Migrated: list of endpoints successfully switched to Dwellir (chain, network, full/archive). - Flagged: any EVM client compatibility concerns the user should verify. - Not supported: list of endpoints/chains/networks Dwellir does not currently support, along with whether each requires a full or archive node and the estimated monthly request volume if determinable from the code. Ask the user to reach out to support@dwellir.com or the team on https://t.me/dwellir with this list so Dwellir can evaluate adding support. If there are any questions about supported RPC methods or Dwellir services, consult https://www.dwellir.com/docs/llms.txt and https://www.dwellir.com/docs.md for authoritative reference. Commit the changes and ask the user whether you should push the branch to origin and open a pull request. ````
## Documentation for Agents Dwellir's documentation is built with AI agent ergonomics in mind. Every page is available as clean markdown, and multiple discovery mechanisms help agents find the right content without HTML parsing. ### llms.txt The site follows the [llmstxt.org](https://llmstxt.org) specification. Agents can fetch a structured index of all available content: | Endpoint | Description | |----------|-------------| | [`/llms.txt`](https://www.dwellir.com/llms.txt) | Site-wide index with links to all networks, blog posts, and documentation | | [`/docs/llms.txt`](https://www.dwellir.com/docs/llms.txt) | Curated documentation index with network guides and key docs | | [`/docs/llms-full.txt`](https://www.dwellir.com/docs/llms-full.txt) | Complete documentation concatenated into a single file for large-context agents | ### Markdown endpoints Append `.md` to any documentation URL to get the content as plain markdown with `Content-Type: text/markdown` headers: ``` https://www.dwellir.com/docs/ethereum.md https://www.dwellir.com/networks/ethereum.md https://www.dwellir.com/blog/hyperliquid-rpc-providers-2025.md ``` These endpoints strip all JSX/MDX components, rewrite internal links to absolute URLs, and include YAML frontmatter with title and description metadata. ### Smart 404 responses When a documentation page is not found, the API returns fuzzy-matched suggestions instead of a generic error. Agents receive: - A list of similar pages ranked by confidence score - Direct links to the matching markdown URLs - Fallback links to `/docs/llms.txt` and `/llms.txt` for broader discovery Single exact matches (confidence 1.0) trigger an automatic redirect. This means minor typos or case mismatches resolve automatically. ### Content negotiation All markdown endpoints set response headers that agents can use for content negotiation: - `Content-Type: text/markdown; charset=utf-8` - `Link` header with `rel="canonical"` (HTML version) and `rel="alternate"` (markdown version) - `X-Robots-Tag: noindex, follow` to prevent search engine indexing of markdown versions ### Index endpoints Two index endpoints provide structured lists of all available content: - [`/docs.md`](https://www.dwellir.com/docs.md) - All documentation pages with titles, descriptions, and markdown links - [`/networks.md`](https://www.dwellir.com/networks.md) - All supported networks with availability, regions, and pricing summaries ## Next steps - [Install the CLI](/cli/installation) and authenticate with `dwellir auth login` - [Install the Hyperliquid skill](https://github.com/dwellir-public/hyperliquid-skills) for AI-assisted Hyperliquid development - Fetch [`/llms.txt`](https://www.dwellir.com/llms.txt) to discover all available documentation - [Contact the Dwellir team](mailto:support@dwellir.com) for dedicated node access or custom integrations --- ## aggregator_v2 # Aggregator V2 Aggregator V2 is a specialized data structure in Aptos designed for high-performance concurrent counters that enable parallel transaction execution without conflicts. It leverages Aptos's Block-STM parallel execution engine to allow multiple transactions to increment or decrement the same counter simultaneously, dramatically improving throughput for applications with shared state. ## Overview Traditional blockchain counters create transaction conflicts when multiple operations try to modify the same value concurrently. Aggregator V2 solves this by using commutative merge semantics, where operations can be applied in any order and combined at the end of block execution. This enables true parallelism for operations like tracking token supply, counting users, or maintaining statistics. ## Technical Implementation Aggregator V2 uses a mathematical property called commutativity: addition and subtraction operations produce the same result regardless of execution order. The Block-STM engine tracks delta values during parallel execution and merges them atomically at commit time. ```move module 0x1::token_counter { use aptos_framework::aggregator_v2::{Self, Aggregator}; struct TokenStats has key { total_minted: Aggregator, total_burned: Aggregator, active_holders: Aggregator } public fun initialize(account: &signer) { move_to(account, TokenStats { total_minted: aggregator_v2::create_aggregator(0), total_burned: aggregator_v2::create_aggregator(0), active_holders: aggregator_v2::create_aggregator(0) }); } public entry fun mint_tokens(amount: u64) acquires TokenStats { let stats = borrow_global_mut(@0x1); aggregator_v2::add(&mut stats.total_minted, amount); } public entry fun burn_tokens(amount: u64) acquires TokenStats { let stats = borrow_global_mut(@0x1); aggregator_v2::add(&mut stats.total_burned, amount); } public entry fun on_new_holder() acquires TokenStats { let stats = borrow_global_mut(@0x1); aggregator_v2::add(&mut stats.active_holders, 1); } #[view] public fun get_total_minted(): u64 acquires TokenStats { let stats = borrow_global(@0x1); aggregator_v2::read(&stats.total_minted) } #[view] public fun circulating_supply(): u64 acquires TokenStats { let stats = borrow_global(@0x1); aggregator_v2::read(&stats.total_minted) - aggregator_v2::read(&stats.total_burned) } } ``` ## API Functions ```move // Create new aggregator with initial value aggregator_v2::create_aggregator(initial_value: T): Aggregator // Add value (works for any numeric type) aggregator_v2::add(aggregator: &mut Aggregator, value: T) // Subtract value aggregator_v2::sub(aggregator: &mut Aggregator, value: T) // Read current value aggregator_v2::read(aggregator: &Aggregator): T // Try to subtract with bounds checking aggregator_v2::try_sub(aggregator: &mut Aggregator, value: T): bool ``` ## Real-World Use Cases 1. **Token Supply Tracking**: Track total minted and burned tokens across thousands of concurrent mint/burn transactions without creating bottlenecks or conflicts. 2. **User Statistics**: Maintain real-time counts of active users, daily transactions, or engagement metrics in high-traffic applications without serialization. 3. **DEX Volume Counters**: Aggregate trading volumes, swap counts, and liquidity metrics across parallel trading operations on decentralized exchanges. 4. **NFT Collection Stats**: Track total minted NFTs, active listings, and collection metrics as multiple users mint and trade simultaneously. 5. **Gaming Leaderboards**: Update player scores, achievement counts, and global statistics with high concurrency during peak gaming periods. 6. **Protocol Analytics**: Maintain real-time protocol metrics like total value locked, transaction counts, and fee accumulation without performance degradation. ## Performance Benefits Without Aggregator V2, concurrent counter updates would create conflicts requiring sequential execution: ```move // Traditional counter - causes conflicts struct OldCounter has key { value: u64 // Every update conflicts with others } public fun increment() acquires OldCounter { let counter = borrow_global_mut(@0x1); counter.value = counter.value + 1; // Conflict! } ``` With Aggregator V2, the same operations execute in parallel: ```move // Parallel counter - no conflicts struct NewCounter has key { value: Aggregator // Parallel updates merge } public fun increment() acquires NewCounter { let counter = borrow_global_mut(@0x1); aggregator_v2::add(&mut counter.value, 1); // Parallelizes! } ``` Benchmark results show 10-100x throughput improvements for counter-heavy workloads. ## Best Practices **Use for Shared State**: Apply Aggregator V2 to any counter or accumulator that multiple transactions will modify concurrently. **Combine with Regular Fields**: Mix aggregators with normal fields in the same struct for optimal performance: ```move struct MixedStats has key { total_count: Aggregator, // Parallel updates last_updated: u64, // Sequential field admin: address // Sequential field } ``` **Read Sparingly in Transactions**: Reading aggregator values during transaction execution may reduce parallelism. Prefer reads in view functions. **Batch Operations**: When possible, batch multiple small updates into larger operations to reduce overhead. **Consider Overflow**: While aggregators support large numbers, implement checks for meaningful limits based on your application logic. **Monitor Performance**: Use Aptos performance metrics to verify that aggregators are providing expected parallelism benefits. ## Limitations and Considerations - Aggregators only support commutative operations (addition, subtraction) - Cannot use aggregators for operations requiring specific ordering - Reading aggregator values in transaction execution may impact parallelism - Not suitable for operations requiring immediate consistency checks - Best suited for statistics and metrics rather than critical balance tracking ## Migration from V1 If you're using the older Aggregator V1 API, migrate to V2 for improved performance: ```move // V1 (deprecated) use aptos_framework::aggregator; let agg = aggregator::create(100); // With max limit // V2 (recommended) use aptos_framework::aggregator_v2; let agg = aggregator_v2::create_aggregator(0); // No max limit needed ``` ## Related Concepts - [Block-STM](https://medium.com/aptoslabs/block-stm-how-we-execute-over-160k-transactions-per-second-on-the-aptos-blockchain-3b003657e4ba) - Parallel execution engine - [Resource Management](/aptos/resource_management) - Managing shared state - [Testing](/aptos/testing) - Test parallel execution scenarios - [View Functions](/aptos/view_functions) - Read aggregator values efficiently --- ## key_rotation # Key Rotation Key rotation on Aptos allows users to change their account's authentication key while preserving the account address, enabling recovery from compromised keys, upgrading security schemes, and transitioning to different authentication methods without losing assets or on-chain identity. ## Overview Unlike traditional blockchains where accounts are permanently tied to a single private key, Aptos separates account addresses from authentication keys. This architecture enables users to rotate their keys for security purposes while maintaining the same address. Key rotation supports both proven rotations (where you have the old key) and unproven rotations (using social recovery or multi-sig authorization). ## How Key Rotation Works Every Aptos account has two components: the permanent address derived from the initial public key, and a mutable authentication key that controls access. When you rotate keys, only the authentication key changes while the address remains constant. ```move // Using Aptos CLI for key rotation aptos account rotate-key \ --new-private-key-file ~/.aptos/new_key.key \ --profile mainnet // Programmatic key rotation module 0x1::key_manager { use std::signer; use aptos_framework::account; public entry fun rotate_authentication_key( account: &signer, new_auth_key: vector ) { account::rotate_authentication_key(account, new_auth_key); } } ``` ## Proven Rotation Proven rotation requires the current private key to authorize the key change: ```typescript const aptos = new Aptos(); // Current account (old key) const oldPrivateKey = new Ed25519PrivateKey("0x..."); const account = Account.fromPrivateKey({ privateKey: oldPrivateKey }); // Generate new key const newPrivateKey = Ed25519PrivateKey.generate(); const newAuthKey = newPrivateKey.publicKey().authKey(); // Rotate to new key const transaction = await aptos.rotateAuthKey({ sender: account, newAuthKey: newAuthKey }); console.log(`Key rotated: ${transaction.hash}`); ``` ## Unproven Rotation Unproven rotation allows key changes through alternative authorization mechanisms like multi-sig or social recovery when the original key is lost: ```move module 0x1::recovery { use std::signer; use aptos_framework::account; struct RecoveryConfig has key { guardians: vector
, threshold: u64 } public entry fun setup_recovery( account: &signer, guardians: vector
, threshold: u64 ) { move_to(account, RecoveryConfig { guardians, threshold }); } public entry fun recover_account( recovered_addr: address, new_auth_key: vector, guardian_signatures: vector> ) acquires RecoveryConfig { let config = borrow_global(recovered_addr); // Verify threshold of guardian signatures // Then rotate to new key // account::rotate_authentication_key_call(recovered_addr, new_auth_key); } } ``` ## Real-World Use Cases 1. **Security Incidents**: Immediately rotate keys when you suspect a private key has been compromised, protecting assets before an attacker can act. 2. **Hardware Wallet Migration**: Transition from a software wallet to a hardware wallet for enhanced security without changing your on-chain address. 3. **Social Recovery**: Implement social recovery systems where trusted friends or family can help recover accounts if keys are lost. 4. **Corporate Key Management**: Rotate employee access keys when staff changes while maintaining consistent corporate account addresses. 5. **Multi-Sig Evolution**: Upgrade from single-key control to multi-sig authorization as account value or importance grows. 6. **Custody Transitions**: Transfer custody of accounts between different custodians or security providers without asset transfers. ## Best Practices **Verify New Keys**: Always verify you can sign with new keys before finalizing rotation. Test on testnet first for critical accounts. **Secure Key Generation**: Generate new keys using cryptographically secure random number generators in isolated environments. **Backup Immediately**: Back up new private keys in multiple secure locations before completing rotation. **Document Rotation**: Maintain records of key rotations including dates, reasons, and new key fingerprints for audit purposes. **Test Recovery Procedures**: Regularly test your recovery mechanisms to ensure they work before an emergency. **Use Time Locks**: Consider implementing time-delayed rotations for high-value accounts to allow cancellation if unauthorized. **Monitor After Rotation**: Watch account activity closely after rotation to detect any unauthorized access attempts. ## Key Rotation with Multi-Sig Combine key rotation with multi-sig for enhanced security: ```move module 0x1::multisig_rotation { use aptos_framework::account; use aptos_framework::multisig_account; public entry fun propose_key_rotation( proposer: &signer, multisig_address: address, new_auth_key: vector ) { // Create proposal to rotate multisig account key // Requires threshold approval from signers } public entry fun approve_key_rotation( approver: &signer, multisig_address: address, proposal_id: u64 ) { // Approve the key rotation proposal } } ``` ## Security Considerations **Old Key Compromise**: After rotation, the old private key can no longer control the account, but it could still be used to attempt social engineering attacks. **Rotation Timing**: Complete rotations quickly once initiated to minimize the window where multiple keys could theoretically control the account. **Authentication vs Address**: Remember that rotating the authentication key doesn't change the account address, so on-chain references remain valid. **Transaction Replay**: Signed but unsubmitted transactions from before rotation will fail after the key changes. **Emergency Contacts**: Maintain emergency contact information with trusted parties who can assist with recovery if needed. ## CLI Commands ```bash # Generate new key pair aptos key generate --output-file ~/.aptos/new_key.key # Rotate to new key aptos account rotate-key \ --new-private-key-file ~/.aptos/new_key.key \ --profile mainnet # Verify rotation aptos account lookup-address \ --profile mainnet # Test signing with new key aptos move run \ --function-id 0x1::aptos_account::test_transaction \ --profile mainnet ``` ## Related Concepts - [Multi-Agent Transactions](/aptos/multi_agent) - Coordinate multiple signers - [Resource Accounts](/aptos/resource_accounts) - Accounts without private keys - [Authentication](/aptos/authentication) - Authentication methods - [Sponsored Transactions](/aptos/sponsored_transactions) - Gasless key rotation --- ## multi_agent # Multi-Agent Transactions Multi-agent transactions enable multiple independent signers to authorize a single transaction on Aptos, allowing complex operations that require coordination between different accounts. This feature is essential for marketplaces, atomic swaps, escrow services, and any scenario where multiple parties must agree to a state change. ## Overview Traditional blockchain transactions have a single sender who pays gas and authorizes all operations. Multi-agent transactions extend this model by allowing additional signers (secondary signers) to authorize operations on their own resources within the same atomic transaction. All signers must provide signatures before the transaction can execute, ensuring all parties consent to the operation. ## Technical Implementation Multi-agent transactions use a special transaction payload that includes addresses of all required signers. Each signer must sign the same transaction hash, and the transaction only executes if all signatures are valid. ```move module 0x1::marketplace { use std::signer; use aptos_framework::coin; use aptos_framework::aptos_coin::AptosCoin; struct Listing has key { price: u64, owner: address } struct NFT has key, store { id: u64, metadata: vector } // Requires both buyer and seller signatures public entry fun purchase_nft( buyer: &signer, seller: &signer, nft_id: u64 ) acquires NFT, Listing { let seller_addr = signer::address_of(seller); let buyer_addr = signer::address_of(buyer); // Get listing from seller let listing = borrow_global(seller_addr); let price = listing.price; // Transfer payment from buyer to seller coin::transfer(buyer, seller_addr, price); // Transfer NFT from seller to buyer let nft = move_from(seller_addr); move_to(buyer, nft); // Clean up listing let Listing { price: _, owner: _ } = move_from(seller_addr); } } ``` ## Creating Multi-Agent Transactions ### TypeScript SDK ```typescript const aptos = new Aptos(); // Create accounts const buyer = Account.generate(); const seller = Account.generate(); // Build multi-agent transaction const transaction = await aptos.transaction.build.multiAgent({ sender: buyer.accountAddress, secondarySignerAddresses: [seller.accountAddress], data: { function: "0x1::marketplace::purchase_nft", functionArguments: [seller.accountAddress, 123] } }); // Both parties sign const buyerAuth = aptos.transaction.sign({ signer: buyer, transaction }); const sellerAuth = aptos.transaction.sign({ signer: seller, transaction }); // Submit with all signatures const committedTxn = await aptos.transaction.submit.multiAgent({ transaction, senderAuthenticator: buyerAuth, additionalSignersAuthenticators: [sellerAuth] }); await aptos.waitForTransaction({ transactionHash: committedTxn.hash }); ``` ### Python SDK ```python from aptos_sdk.client import RestClient from aptos_sdk.account import Account from aptos_sdk.transactions import EntryFunction, TransactionPayload client = RestClient("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1") buyer = Account.generate() seller = Account.generate() # Build multi-agent transaction payload = EntryFunction.natural( "0x1::marketplace", "purchase_nft", [], [seller.address(), 123] ) # Create and sign with both accounts signed_txn = client.create_multi_agent_bcs_transaction( buyer, [seller], payload ) tx_hash = client.submit_bcs_transaction(signed_txn) client.wait_for_transaction(tx_hash) ``` ## Real-World Use Cases 1. **NFT Marketplaces**: Execute atomic NFT sales where the buyer transfers payment and seller transfers the NFT in a single transaction, eliminating front-running or partial execution risks. 2. **Atomic Swaps**: Enable trustless peer-to-peer token swaps where both parties exchange assets simultaneously without requiring an intermediary or escrow. 3. **Joint Account Operations**: Implement shared accounts or vaults that require multiple parties to approve withdrawals or significant operations. 4. **Escrow Releases**: Coordinate between buyer, seller, and escrow agent to release funds and assets when conditions are met. 5. **Multi-Party Gaming**: Execute game moves or state transitions that require agreement from multiple players in competitive or cooperative games. 6. **Cross-Protocol Operations**: Coordinate actions across different protocols where multiple protocol administrators must authorize complex operations. ## Advanced Patterns ### Three-Way Transactions ```move public entry fun escrow_complete( buyer: &signer, seller: &signer, escrow_agent: &signer, item_id: u64 ) acquires EscrowedItem, Payment { // All three parties must sign // Agent verifies conditions // Buyer gets item // Seller gets payment // Agent gets fee } ``` ### Conditional Multi-Agent ```move public entry fun conditional_transfer( sender: &signer, receiver: &signer, amount: u64, condition_met: bool ) { assert!(condition_met, ECONDITION_NOT_MET); // Both parties acknowledge the condition is met // Execute transfer } ``` ## Best Practices **Verify All Signers**: Always validate that all required signers have provided valid signatures before executing critical operations. **Atomic Operations**: Structure multi-agent transactions to be truly atomic - either all operations succeed or all fail together. **Clear Responsibilities**: Document which signer pays gas (primary signer) and what each secondary signer authorizes. **Timeout Mechanisms**: Implement expiration times for multi-agent transaction proposals to prevent indefinite pending states. **Off-Chain Coordination**: Use off-chain communication channels to coordinate signature collection before submitting the final transaction. **Gas Estimation**: The primary signer pays all gas fees, so ensure they have sufficient funds for the entire transaction. **Order Independence**: Design functions so that the order of secondary signers doesn't matter when possible to simplify coordination. ## Signature Collection Flow 1. **Transaction Construction**: Primary signer builds the transaction with all secondary signer addresses 2. **Hash Distribution**: Share the transaction hash with all secondary signers 3. **Signature Collection**: Each party signs the transaction hash independently 4. **Aggregation**: Primary signer collects all signatures 5. **Submission**: Submit the fully-signed transaction to the network 6. **Atomic Execution**: All operations execute or fail together ## Security Considerations **Signature Verification**: Never submit a multi-agent transaction without verifying all signatures are authentic and match expected signers. **Transaction Inspection**: All signers should inspect the transaction details before signing to ensure they agree with the operations. **Replay Protection**: Multi-agent transactions include sequence numbers to prevent replay attacks. **Partial Signing Attacks**: Protect against scenarios where some signers might try to modify the transaction after others have signed. **Resource Ownership**: Verify that all signers actually own or control the resources the transaction will modify. ## Comparison with Multi-Sig Multi-agent transactions differ from multi-sig accounts: - **Multi-Agent**: Multiple independent accounts coordinate on a single transaction - **Multi-Sig**: Single account controlled by multiple keys with threshold approval Multi-agent is better for: - Peer-to-peer interactions between distinct parties - Operations involving resources from multiple accounts - One-time coordinated actions Multi-sig is better for: - Shared account management - Corporate treasury controls - Ongoing governance of a single account ## Related Concepts - [Sponsored Transactions](/aptos/sponsored_transactions) - Separate signer and fee payer - [Resource Accounts](/aptos/resource_accounts) - Autonomous contract accounts - [Key Rotation](/aptos/key_rotation) - Change account keys - [Object Model](/aptos/object_model) - Alternative ownership patterns --- ## object_model # Object Model The Aptos object model introduces a powerful abstraction for managing complex digital assets with rich composition, flexible ownership, and extensible functionality. Objects provide globally addressable, heterogeneous resources that support ownership hierarchies, reference relationships, and safe composition patterns not easily achievable with traditional Move resources. ## Overview Objects in Aptos are special on-chain entities identified by unique addresses, combining the benefits of resource safety with flexible ownership and composition capabilities. Unlike traditional resources stored directly under user accounts, objects have their own addresses and can own other objects, creating hierarchical ownership structures ideal for NFTs, composable game items, and complex DeFi positions. ## Core Concepts ### Object Creation Objects are created with unique addresses and can store multiple heterogeneous resources: ```move module 0x1::nft_collection { use std::string::String; use aptos_framework::object::{Self, Object, ConstructorRef}; use aptos_token_objects::token; use aptos_token_objects::collection; struct CollectionMetadata has key { creator: address, description: String, max_supply: u64, minted: u64 } struct TokenMetadata has key { name: String, description: String, uri: String, rarity: u8 } // Create a collection object public entry fun create_collection( creator: &signer, name: String, description: String, max_supply: u64, uri: String ) { let constructor_ref = collection::create_unlimited_collection( creator, description, name, option::none(), uri ); let object_signer = object::generate_signer(&constructor_ref); move_to(&object_signer, CollectionMetadata { creator: signer::address_of(creator), description, max_supply, minted: 0 }); } // Create an NFT object within the collection public entry fun mint_nft( creator: &signer, collection: String, name: String, description: String, uri: String, rarity: u8 ) { let constructor_ref = token::create_named_token( creator, collection, description, name, option::none(), uri ); let object_signer = object::generate_signer(&constructor_ref); move_to(&object_signer, TokenMetadata { name, description, uri, rarity }); } } ``` ## Key Features ### Object References Objects can reference other objects safely without ownership transfer: ```move struct GameCharacter has key { name: String, level: u64, equipped_weapon: Object, // Reference to weapon object inventory: vector> // References to item objects } public fun equip_weapon( character_obj: Object, weapon_obj: Object ) acquires GameCharacter { let character = borrow_global_mut(object::object_address(&character_obj)); character.equipped_weapon = weapon_obj; } ``` ### Ownership Transfer Objects support flexible ownership patterns: ```move use aptos_framework::object; public entry fun transfer_nft( owner: &signer, nft: Object, recipient: address ) { // Transfer object ownership object::transfer(owner, nft, recipient); } public entry fun make_soulbound(creator: &signer, nft: Object) { // Disable transfers permanently let transfer_ref = object::generate_transfer_ref(creator, nft); object::disable_ungated_transfer(&transfer_ref); } ``` ### Object Composition Objects can own other objects, creating hierarchies: ```move struct Bundle has key { items: vector>, total_value: u64 } public fun create_bundle( creator: &signer, item_objects: vector> ) { let constructor_ref = object::create_object(signer::address_of(creator)); let object_signer = object::generate_signer(&constructor_ref); // Transfer items to the bundle object let i = 0; while (i < vector::length(&item_objects)) { let item = *vector::borrow(&item_objects, i); object::transfer(creator, item, signer::address_of(&object_signer)); i = i + 1; }; move_to(&object_signer, Bundle { items: item_objects, total_value: 0 // Calculate from items }); } ``` ## Real-World Use Cases 1. **Composable NFTs**: Create NFTs that can own other NFTs, like a character owning equipment, a house containing furniture, or a card deck containing individual cards. 2. **DeFi Positions**: Represent complex financial positions as objects that aggregate multiple assets, track performance, and enable atomic position transfers. 3. **Gaming Assets**: Build rich game systems where items, characters, and locations are objects with properties, inventories, and relationships. 4. **Fractional Ownership**: Create objects representing shared ownership of assets where multiple parties hold stakes in a single valuable item. 5. **Licensing and Royalties**: Implement objects that track usage rights, royalty obligations, and derivative relationships between creative works. 6. **Supply Chain Tracking**: Model physical goods as objects that move through a supply chain, accumulating provenance and certification data. ## Best Practices **Use Objects for Complex Assets**: Prefer objects over simple resources when assets need ownership transfer, composition, or references to other assets. **Leverage Object Addresses**: Objects have stable addresses independent of owner, enabling reliable references and off-chain indexing. **Implement Access Control**: Use object extensions and permissions to control who can modify object properties or transfer ownership. **Consider Gas Costs**: Object operations involve additional overhead compared to simple resources; balance flexibility with efficiency. **Plan Ownership Hierarchies**: Design clear ownership structures to prevent circular references and simplify asset management. **Utilize Events**: Emit events for object creation, transfer, and modification to enable off-chain tracking and indexing. **Test Composition Patterns**: Thoroughly test complex object hierarchies to ensure proper cleanup and prevent orphaned resources. ## Object Capabilities Objects support various capabilities through refs: ```move // Transfer control let transfer_ref = object::generate_transfer_ref(&constructor_ref); object::disable_ungated_transfer(&transfer_ref); // Deletion control let delete_ref = object::generate_delete_ref(&constructor_ref); object::delete(delete_ref); // Extension control let extend_ref = object::generate_extend_ref(&constructor_ref); let object_signer = object::generate_signer_for_extending(&extend_ref); ``` ## Querying Objects ```move #[view] public fun get_owner(obj: Object): address { object::owner(obj) } #[view] public fun is_owner(obj: Object, potential_owner: address): bool { object::is_owner(obj, potential_owner) } #[view] public fun can_transfer(obj: Object): bool { object::ungated_transfer_allowed(obj) } ``` ## Object vs Traditional Resources **Use Objects When:** - Assets need to be transferred between users - Complex composition or hierarchies are required - Stable addresses independent of owner are beneficial - References between assets are needed **Use Traditional Resources When:** - Simple account-scoped data storage - No transfer or ownership changes needed - Minimizing gas costs is critical - Simple key-value storage suffices ## Related Concepts - [Resource Management](/aptos/resource_management) - Traditional resource patterns - [Multi-Agent Transactions](/aptos/multi_agent) - Transfer objects atomically - [View Functions](/aptos/view_functions) - Query object properties - [Testing](/aptos/testing) - Test object composition --- ## orderless_transactions # Orderless Transactions Orderless transactions on Aptos reduce head-of-line blocking by allowing flexible transaction ordering using explicit nonces instead of strict sequence numbers. This feature enables parallel transaction submission and improves throughput for accounts issuing multiple independent operations simultaneously. ## Overview Traditional blockchain accounts process transactions in strict sequential order based on sequence numbers, where transaction N+1 cannot execute until transaction N completes. Orderless transactions relax this constraint by using nonces that allow transactions to execute in any order when dependencies permit, significantly improving performance for high-frequency accounts like exchanges, bots, and payment processors. ## How It Works Instead of requiring sequential processing, orderless transactions use nonces to indicate independence: ```move // Traditional: Must execute in order 0, 1, 2, 3... Transaction { sequence_number: 0 } Transaction { sequence_number: 1 } // Blocks on 0 Transaction { sequence_number: 2 } // Blocks on 1 // Orderless: Can execute in any order Transaction { nonce: 1 } // Independent Transaction { nonce: 2 } // Independent Transaction { nonce: 3 } // Independent ``` ## Implementation ```typescript const aptos = new Aptos(); const account = Account.generate(); // Submit multiple transactions with different nonces const nonce1 = 100; const nonce2 = 101; const nonce3 = 102; // All can execute in parallel const tx1 = await aptos.transaction.build.simple({ sender: account.accountAddress, data: { function: "0x1::coin::transfer", functionArguments: [recipient1, 1000] }, options: { nonce: nonce1 } }); const tx2 = await aptos.transaction.build.simple({ sender: account.accountAddress, data: { function: "0x1::coin::transfer", functionArguments: [recipient2, 2000] }, options: { nonce: nonce2 } }); // Submit both immediately await aptos.transaction.submit.simple({ transaction: tx1, senderAuthenticator: auth1 }); await aptos.transaction.submit.simple({ transaction: tx2, senderAuthenticator: auth2 }); ``` ## Real-World Use Cases 1. **Exchange Operations**: Crypto exchanges can submit thousands of withdrawal transactions simultaneously without waiting for sequential processing, dramatically increasing throughput. 2. **Payment Processors**: Payment platforms can process multiple customer payments in parallel rather than queuing them sequentially. 3. **Bot Operations**: Trading bots and automated market makers can submit multiple independent transactions without head-of-line blocking from slower operations. 4. **Batch Processing**: Applications can submit large batches of independent transactions that execute as capacity permits rather than in strict order. 5. **Multi-User Services**: Services managing operations for multiple users can interleave transactions without artificial ordering constraints. 6. **Retry Logic**: Failed transactions can be retried with new nonces while other transactions continue processing without blocking. ## Best Practices **Use Unique Nonces**: Ensure each transaction from an account uses a unique nonce to prevent conflicts and rejections. **Track Nonce Usage**: Maintain a nonce counter or registry to avoid accidentally reusing nonces across concurrent operations. **Handle Race Conditions**: Implement proper error handling for nonce conflicts that may occur in distributed systems. **Monitor Nonce Gaps**: Track which nonces have been used to identify failed or pending transactions. **Set Reasonable Limits**: Don't create excessive nonce gaps as validators may have limits on nonce range acceptance. **Combine with Sequence Numbers**: Use orderless transactions for truly independent operations while using sequence numbers for dependent chains. ## Limitations - Nonces must be managed carefully to avoid conflicts - Not all transaction types support orderless execution - May require changes to existing transaction submission infrastructure - Validators may impose limits on maximum nonce values or gaps - Ordering guarantees between transactions are reduced ## Comparison with Sequential Transactions **Sequential (Traditional)** - Guaranteed execution order - Simpler to reason about dependencies - Natural retry semantics - Lower throughput under load **Orderless (Nonce-based)** - Higher throughput potential - Parallel execution capability - More complex nonce management - Better for independent operations ## Monitoring and Debugging ```typescript // Track nonce usage const usedNonces = new Set(); function getNextNonce(): number { let nonce = Math.floor(Math.random() * 1000000); while (usedNonces.has(nonce)) { nonce = Math.floor(Math.random() * 1000000); } usedNonces.add(nonce); return nonce; } // Check transaction status by nonce async function checkNonceStatus(account: address, nonce: number) { // Query blockchain for transaction with specific nonce } ``` ## Related Concepts - [Aggregator V2](/aptos/aggregator_v2) - Parallel state updates - [Sponsored Transactions](/aptos/sponsored_transactions) - Flexible fee payment - [Multi-Agent Transactions](/aptos/multi_agent) - Multi-party coordination --- ## resource_accounts # Resource Accounts Resource accounts are special autonomous accounts on Aptos that have no private key and can only be controlled by smart contracts. They enable developers to create stable, deterministic addresses for protocols while maintaining programmatic control over account operations, making them essential for DeFi protocols, DAOs, and autonomous systems. ## Overview Resource accounts solve the problem of protocol-controlled accounts that need stable addresses but shouldn't have private keys that could be lost or compromised. They are created with deterministic addresses derived from a source account and seed, allowing protocols to own assets, publish modules, and execute operations entirely through smart contract logic. ## Creating Resource Accounts ```move module 0x1::protocol { use std::signer; use aptos_framework::resource_account; use aptos_framework::account; struct ResourceAccountCap has key { cap: account::SignerCapability } // Create a resource account during protocol initialization public entry fun initialize(deployer: &signer, seed: vector) { // Create resource account with deterministic address let (resource_signer, signer_cap) = account::create_resource_account( deployer, seed ); // Store capability to use resource account later move_to(deployer, ResourceAccountCap { cap: signer_cap }); // Resource account can now hold assets, publish modules // Address is deterministic: derived from deployer + seed } // Use resource account for protocol operations public entry fun protocol_transfer( amount: u64, recipient: address ) acquires ResourceAccountCap { let cap = borrow_global(@deployer); let resource_signer = account::create_signer_with_capability(&cap.cap); // Resource account executes transfer coin::transfer(&resource_signer, recipient, amount); } } ``` ## Deterministic Addresses Resource account addresses are deterministically computed: ```move // Address formula: hash(source_address, seed, 0xFF) let resource_addr = account::create_resource_address(&source_address, seed); ``` This enables: - Predictable protocol addresses before deployment - Consistent addresses across different networks - Easy verification of protocol authenticity ## Real-World Use Cases 1. **DeFi Protocols**: Create liquidity pools, vaults, and treasury accounts that are controlled by protocol logic rather than private keys, eliminating single points of failure. 2. **DAO Treasuries**: Establish autonomous treasuries where funds can only be moved through governance proposals and smart contract execution. 3. **Escrow Services**: Build trustless escrow systems where locked assets are held by resource accounts with programmatic release conditions. 4. **Protocol Upgrades**: Deploy protocol modules to resource accounts, enabling controlled upgrade paths through governance rather than admin keys. 5. **Cross-Chain Bridges**: Operate bridge accounts that custody locked assets with release controlled by multi-sig validation logic. 6. **Automated Market Makers**: Run AMM contracts where liquidity provider funds are held in resource accounts managed by protocol mathematics. ## Best Practices **Secure Signer Capabilities**: Store `SignerCapability` in a protected resource with appropriate access controls. Never expose it directly. **Use Meaningful Seeds**: Choose descriptive seeds that indicate the resource account's purpose (e.g., b"liquidity_pool_v2"). **Implement Access Control**: Add authorization logic to functions that use resource account capabilities. **Test Address Generation**: Verify resource account addresses are computed correctly before mainnet deployment. **Document Ownership**: Clearly document which modules control which resource accounts for auditing and verification. **Capability Rotation**: Consider patterns for safely transferring or revoking resource account control if needed. **Avoid Seed Collisions**: Use unique seeds to prevent accidentally creating multiple resource accounts at the same address. ## Advanced Patterns ### Multi-Tier Resource Accounts ```move // Create hierarchy of resource accounts public fun create_protocol_structure(creator: &signer) { let (treasury_signer, treasury_cap) = account::create_resource_account( creator, b"treasury" ); let (rewards_signer, rewards_cap) = account::create_resource_account( creator, b"rewards" ); let (insurance_signer, insurance_cap) = account::create_resource_account( creator, b"insurance" ); // Store capabilities for different protocol functions } ``` ### Controlled Capability Distribution ```move struct GovernanceCap has key { treasury_cap: account::SignerCapability, withdraw_limit: u64, last_withdraw: u64 } public fun governed_withdraw( amount: u64, recipient: address ) acquires GovernanceCap { let gov = borrow_global_mut(@governance); // Enforce time-locks and limits assert!(amount <= gov.withdraw_limit, EEXCEEDS_LIMIT); let resource_signer = account::create_signer_with_capability(&gov.treasury_cap); coin::transfer(&resource_signer, recipient, amount); gov.last_withdraw = timestamp::now_seconds(); } ``` ## Security Considerations **Capability Storage**: The `SignerCapability` is extremely powerful - treat it like a master private key and protect it appropriately. **Access Control**: Implement robust access control for any function that uses resource account capabilities. **Upgrade Safety**: If resource accounts publish modules, carefully manage upgrade policies to prevent malicious changes. **Resource Exhaustion**: Resource accounts need gas for operations, so ensure they maintain sufficient APT balances. **Deterministic Generation**: Understand that anyone can compute your resource account address from the source and seed. ## Querying Resource Accounts ```move #[view] public fun get_resource_account_address(source: address, seed: vector): address { account::create_resource_address(&source, seed) } #[view] public fun get_protocol_treasury(): address { account::create_resource_address(&@deployer, b"treasury") } ``` ## Comparison with Regular Accounts **Resource Accounts:** - No private key - Controlled by smart contracts - Deterministic addresses - Perfect for protocols **Regular Accounts:** - Have private keys - User-controlled - Random addresses - For individual users ## Related Concepts - [Multi-Agent Transactions](/aptos/multi_agent) - Coordinate with resource accounts - [Sponsored Transactions](/aptos/sponsored_transactions) - Pay gas for resource accounts - [Module Structure](/aptos/module_structure) - Deploy modules to resource accounts - [Key Rotation](/aptos/key_rotation) - Not applicable to resource accounts --- ## sponsored_transactions # Sponsored Transactions Sponsored transactions enable gas fee delegation on Aptos, allowing one account (the sponsor) to pay transaction fees for another account (the user). This feature is crucial for onboarding new users, providing gasless experiences, and building accessible dApps that don't require users to hold native tokens before interacting with applications. ## Overview Traditional blockchain interactions require users to hold native tokens (APT on Aptos) to pay gas fees, creating a significant onboarding barrier. Sponsored transactions separate the transaction sender from the fee payer, enabling applications, DAOs, or services to subsidize user transactions while maintaining proper authentication and authorization. ## How Sponsored Transactions Work A sponsored transaction involves three parties: 1. **User (Sender)**: Signs the transaction to authorize their operations 2. **Sponsor (Fee Payer)**: Pays gas fees and signs to authorize payment 3. **Network**: Validates both signatures and executes the transaction ```typescript const aptos = new Aptos(); // User who wants to perform an operation but has no APT const user = Account.generate(); // Sponsor who will pay the gas fees const sponsor = Account.generate(); // Must have APT // Build sponsored transaction const transaction = await aptos.transaction.build.simple({ sender: user.accountAddress, data: { function: "0x1::aptos_account::transfer", functionArguments: [recipientAddress, 1000] }, withFeePayer: true }); // User signs their part const userAuth = aptos.transaction.sign({ signer: user, transaction }); // Sponsor signs to pay fees const sponsorAuth = aptos.transaction.signAsFeePayer({ signer: sponsor, transaction }); // Submit with both signatures const committedTxn = await aptos.transaction.submit.simple({ transaction, senderAuthenticator: userAuth, feePayerAuthenticator: sponsorAuth }); await aptos.waitForTransaction({ transactionHash: committedTxn.hash }); ``` ## Move Implementation ```move module 0x1::sponsored_service { use std::signer; use aptos_framework::coin; use aptos_framework::aptos_coin::AptosCoin; struct SponsorshipConfig has key { enabled: bool, daily_limit: u64, per_user_limit: u64 } struct UserQuota has key { used_today: u64, last_reset: u64 } // User function that can be sponsored public entry fun perform_action(user: &signer, data: vector) { // User's actual operation // Gas will be paid by sponsor, not user } // Sponsor checks if they should sponsor this user public entry fun check_sponsorship_eligibility( user: address, estimated_gas: u64 ): bool acquires UserQuota, SponsorshipConfig { let config = borrow_global(@sponsor); if (!config.enabled) return false; if (!exists(user)) return true; let quota = borrow_global(user); quota.used_today + estimated_gas <= config.per_user_limit } } ``` ## Real-World Use Cases 1. **User Onboarding**: Let new users interact with your dApp immediately without requiring them to acquire APT first, dramatically reducing onboarding friction. 2. **Gaming Applications**: Sponsor in-game transactions so players can play without worrying about gas fees, creating a seamless gaming experience. 3. **Social Media dApps**: Enable users to post, like, and interact on blockchain social platforms without paying gas for each action. 4. **Enterprise Applications**: Corporations can sponsor transactions for their employees or customers, internalizing blockchain interaction costs. 5. **Loyalty Programs**: Reward loyal users by sponsoring their transactions as a benefit, similar to traditional fee waivers. 6. **Micropayments**: Enable micro-transaction use cases where gas fees would otherwise be prohibitively expensive relative to transaction value. ## Best Practices **Implement Rate Limiting**: Protect sponsors from abuse by implementing per-user quotas, daily limits, and velocity checks. **Verify User Intent**: Ensure the sponsored transaction represents genuine user intent and hasn't been manipulated. **Gas Estimation**: Accurately estimate gas costs before sponsoring to prevent unexpected costs and set appropriate budgets. **Conditional Sponsorship**: Only sponsor transactions that meet specific criteria (new users, specific functions, within limits). **Monitor Costs**: Track total sponsorship costs and set alerts for unusual patterns or excessive spending. **Graceful Degradation**: Have fallback options if sponsorship limits are reached so users can still complete transactions. **Transparent Terms**: Clearly communicate sponsorship terms, limits, and conditions to users. ## Advanced Sponsorship Patterns ### Conditional Sponsorship ```typescript async function conditionalSponsor( user: Account, transaction: any, sponsor: Account ): Promise { // Check if user qualifies for sponsorship const userTxCount = await getUserTransactionCount(user.accountAddress); const isNewUser = userTxCount < 10; if (isNewUser) { // Sponsor new users return true; } // Check if user has loyalty points const loyaltyPoints = await getLoyaltyPoints(user.accountAddress); if (loyaltyPoints > 100) { // Sponsor loyal users return true; } return false; // User must pay own fees } ``` ### Tiered Sponsorship ```move struct TieredSponsorship has key { bronze_limit: u64, // Sponsor up to X gas silver_limit: u64, // Sponsor up to Y gas gold_limit: u64, // Sponsor up to Z gas } public fun get_user_tier(user: address): u8 { // Determine user tier based on activity, holdings, etc. 1 // Bronze } ``` ### Pooled Sponsorship ```move struct SponsorshipPool has key { contributors: vector
, total_funds: u64, used_funds: u64, } public fun contribute_to_pool(contributor: &signer, amount: u64) { // Add funds to sponsorship pool // Multiple parties share sponsorship costs } ``` ## Cost Management ```typescript // Track sponsorship costs interface SponsorshipMetrics { totalSponsored: number; transactionsSponsored: number; averageCostPerTx: number; dailyBudget: number; remainingBudget: number; } async function checkBudget(sponsor: Account): Promise { const metrics = await getSponsorshipMetrics(sponsor.accountAddress); return metrics.remainingBudget > metrics.averageCostPerTx; } ``` ## Security Considerations **Sybil Resistance**: Implement mechanisms to prevent users from creating multiple accounts to exploit sponsorship limits. **Validation Before Signing**: Sponsors must validate transaction contents before signing to prevent sponsoring malicious operations. **Budget Controls**: Set strict budget limits and alerts to prevent sponsorship pool depletion. **Abuse Prevention**: Monitor for unusual patterns that might indicate coordinated abuse of sponsorship systems. **Emergency Shutdown**: Implement ability to quickly disable sponsorship if abuse is detected. ## Monitoring and Analytics ```typescript // Track sponsorship metrics async function trackSponsorship(txHash: string, sponsor: address, user: address, gasPaid: number) { await database.insert({ timestamp: Date.now(), txHash, sponsor, user, gasPaid, type: 'sponsored_transaction' }); await updateDailyMetrics(sponsor); await checkAbusePatterns(user); } ``` ## Related Concepts - [Multi-Agent Transactions](/aptos/multi_agent) - Multiple signers in transactions - [Resource Accounts](/aptos/resource_accounts) - Programmatic transaction execution - [Key Rotation](/aptos/key_rotation) - Sponsor key management - [Orderless Transactions](/aptos/orderless_transactions) - High-throughput sponsorship --- ## aggregations > Coming soon: Need support for this? Email support@dwellir.com and we will enable it for you. # GraphQL Aggregations GraphQL aggregations enable powerful analytical queries on Aptos blockchain data, allowing you to compute statistics, counts, sums, and other aggregate functions across large datasets. These queries are essential for building analytics dashboards, generating reports, and understanding on-chain activity patterns without processing individual records. ## Overview The Aptos GraphQL indexer provides aggregate functions that operate on filtered datasets, enabling you to answer questions like "How many transactions occurred today?", "What's the total trading volume?", or "Who are the top gas consumers?" These aggregations run efficiently on indexed data, providing fast results even for complex queries spanning millions of records. ## Common Aggregate Functions The GraphQL API supports standard aggregate operations: **count**: Total number of records matching criteria **sum**: Sum of numeric field values **avg**: Average of numeric values **max**: Maximum value in dataset **min**: Minimum value in dataset **stddev**: Standard deviation of values **variance**: Variance of values ## Example Queries ### Transaction Volume Analysis ```graphql query TransactionMetrics($startTime: timestamp!, $endTime: timestamp!) { user_transactions_aggregate( where: { timestamp: { _gte: $startTime, _lte: $endTime } } ) { aggregate { count sum { gas_used } avg { gas_used } max { gas_used } min { gas_used } } } } ``` ### Top Gas Consumers ```graphql query TopGasUsers($limit: Int!) { user_transactions_aggregate { aggregate { count } } user_transactions( order_by: { gas_used: desc }, limit: $limit ) { sender gas_used version timestamp } } ``` ### Daily Active Users ```graphql query DailyActiveUsers($date: date!) { user_transactions_aggregate( distinct_on: sender, where: { timestamp: { _gte: $date, _lt: "${date + 1 day}" } } ) { aggregate { count(distinct: true, columns: sender) } } } ``` ### Token Transfer Statistics ```graphql query TokenTransferStats($token_type: String!) { coin_activities_aggregate( where: { coin_type: { _eq: $token_type }, activity_type: { _eq: "0x1::coin::WithdrawEvent" } } ) { aggregate { count sum { amount } avg { amount } } } } ``` ### NFT Collection Analytics ```graphql query CollectionMetrics($collection_id: String!) { current_token_ownerships_v2_aggregate( where: { current_token_data: { collection_id: { _eq: $collection_id } } } ) { aggregate { count } } token_activities_v2_aggregate( where: { token_data_id: { _like: "${collection_id}%" }, type: { _eq: "0x3::token::MintTokenEvent" } } ) { aggregate { count } } } ``` ## Real-World Use Cases 1. **Protocol Analytics**: Track total value locked, transaction volumes, user growth, and other key metrics for DeFi protocols and dApps. 2. **User Behavior Analysis**: Understand user engagement patterns, identify power users, and analyze transaction frequency distributions. 3. **Gas Optimization Research**: Analyze gas consumption patterns to identify optimization opportunities and compare efficiency across different contract designs. 4. **Market Intelligence**: Aggregate trading volumes, price movements, and liquidity metrics for tokens and NFT collections. 5. **Network Health Monitoring**: Track transaction success rates, average confirmation times, and network utilization over time. 6. **Revenue Reporting**: Calculate total fees collected, transaction counts by type, and other financial metrics for business reporting. ## Best Practices **Use Appropriate Filters**: Apply WHERE clauses to reduce dataset size before aggregation for better performance. **Leverage Indexed Fields**: Aggregations on indexed fields (addresses, timestamps, types) perform significantly faster. **Batch Time-Series Queries**: For dashboards displaying multiple time periods, batch queries together to reduce API calls. **Cache Results**: Aggregate statistics change slowly - implement appropriate caching strategies to reduce load. **Pagination for Details**: When showing aggregate summaries plus details, paginate the detail results appropriately. **Use Variables**: Parameterize queries with GraphQL variables for reusable, type-safe queries. ## Performance Considerations - Aggregations on large unfiltered tables can be slow - always use WHERE clauses - Distinct counts are more expensive than simple counts - Complex nested aggregations should be avoided or split into multiple queries - Consider using materialized views for frequently accessed aggregations - Time-range queries on timestamp fields are well-optimized ## Combining Aggregates with Details ```graphql query DashboardMetrics($limit: Int!) { # Overall statistics metrics: user_transactions_aggregate { aggregate { count avg { gas_used } sum { gas_used } } } # Top performers top_users: user_transactions( order_by: { gas_used: desc }, limit: $limit, distinct_on: sender ) { sender gas_used } # Recent activity recent: user_transactions( order_by: { timestamp: desc }, limit: $limit ) { hash sender timestamp success } } ``` ## TypeScript Integration ```typescript const client = new ApolloClient({ uri: "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/graphql" }); const TRANSACTION_STATS = gql` query TransactionStats { user_transactions_aggregate { aggregate { count avg { gas_used } } } } `; const { data } = await client.query({ query: TRANSACTION_STATS }); console.log(`Total transactions: ${data.user_transactions_aggregate.aggregate.count}`); console.log(`Average gas: ${data.user_transactions_aggregate.aggregate.avg.gas_used}`); ``` ## Related Concepts - [GraphQL Overview](/aptos/graphql_overview) - Introduction to GraphQL indexer - [User Transactions](/aptos/user_transactions) - Query transaction data - [Token Activities](/aptos/token_activities) - Aggregate token transfers - [ANS Queries](/aptos/ans_queries) - Query naming service data --- ## ans_queries > Coming soon: Need support for this? Email support@dwellir.com and we will enable it for you. # ANS Queries Aptos Name Service (ANS) provides human-readable names for Aptos addresses, similar to DNS for the internet. The GraphQL API enables efficient querying of ANS registrations, allowing applications to resolve names to addresses, lookup reverse mappings, check expiration dates, and manage domain portfolios programmatically. ## Overview ANS transforms complex hexadecimal addresses like `0x1a2b3c...` into memorable names like `alice.apt`, significantly improving user experience. The GraphQL indexer provides indexed access to ANS data, enabling fast lookups for wallet displays, payment systems, social features, and any application needing human-readable identifiers. ## Core Query Patterns ### Resolve Name to Address ```graphql query ResolveName($name: String!) { ans_lookup(where: { name: { _eq: $name } }) { name address expiration_timestamp registered_at owner } } ``` ### Reverse Lookup (Address to Names) ```graphql query AddressToNames($address: String!) { ans_lookup( where: { address: { _eq: $address } }, order_by: { registered_at: desc } ) { name expiration_timestamp is_primary } } ``` ### Check Name Availability ```graphql query CheckAvailability($name: String!) { ans_lookup( where: { name: { _eq: $name }, expiration_timestamp: { _gt: "now()" } } ) { name owner } } ``` ### Get Primary Name ```graphql query GetPrimaryName($address: String!) { ans_lookup( where: { address: { _eq: $address }, is_primary: { _eq: true } }, limit: 1 ) { name expiration_timestamp } } ``` ### Search Names by Pattern ```graphql query SearchNames($pattern: String!, $limit: Int!) { ans_lookup( where: { name: { _like: $pattern } }, order_by: { registered_at: desc }, limit: $limit ) { name address owner registered_at } } ``` ### Expiring Names ```graphql query ExpiringNames($days: Int!) { ans_lookup( where: { expiration_timestamp: { _gte: "now()", _lte: "now() + ${days} days" } }, order_by: { expiration_timestamp: asc } ) { name address expiration_timestamp } } ``` ## Real-World Use Cases 1. **Wallet Applications**: Display user-friendly names instead of addresses in transaction histories, contact lists, and payment interfaces for improved UX. 2. **Payment Systems**: Allow users to send payments to names like "alice.apt" instead of copying long addresses, reducing errors and improving accessibility. 3. **Social Platforms**: Enable username-based social features where users can follow, message, or interact with others using memorable names. 4. **Domain Marketplaces**: Build platforms for buying, selling, and trading ANS domains with search, filtering, and expiration monitoring. 5. **Portfolio Management**: Track domain portfolios, monitor expiration dates, and manage renewal workflows for users with multiple names. 6. **Identity Verification**: Use ANS as a lightweight identity system where verified names provide reputation and trust signals. ## Best Practices **Cache Resolved Names**: ANS data changes infrequently - implement caching with appropriate TTLs to reduce API calls. **Handle Non-Existent Names**: Always check for null/empty results when resolving names and provide clear user feedback. **Validate Name Format**: Implement client-side name validation (format, length, allowed characters) before querying. **Check Expiration**: Always verify expiration_timestamp to ensure names are still active before relying on them. **Support Both Directions**: Implement both name-to-address and address-to-name lookups for complete functionality. **Prioritize Primary Names**: When an address owns multiple names, prefer displaying the primary name for consistency. **Batch Lookups**: When resolving multiple names, batch them into single GraphQL queries for efficiency. ## TypeScript Integration ```typescript const client = new ApolloClient({ uri: "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/graphql" }); async function resolveName(name: string): Promise { const { data } = await client.query({ query: gql` query ResolveName($name: String!) { ans_lookup(where: { name: { _eq: $name } }) { address expiration_timestamp } } `, variables: { name } }); const result = data.ans_lookup[0]; if (!result) return null; const now = Date.now(); const expiration = new Date(result.expiration_timestamp).getTime(); return expiration > now ? result.address : null; } async function getPrimaryName(address: string): Promise { const { data } = await client.query({ query: gql` query GetPrimaryName($address: String!) { ans_lookup( where: { address: { _eq: $address }, is_primary: { _eq: true } }, limit: 1 ) { name expiration_timestamp } } `, variables: { address } }); const result = data.ans_lookup[0]; if (!result) return null; const now = Date.now(); const expiration = new Date(result.expiration_timestamp).getTime(); return expiration > now ? result.name : null; } ``` ## Advanced Queries ### Domain Portfolio Analysis ```graphql query PortfolioStats($owner: String!) { active: ans_lookup_aggregate( where: { owner: { _eq: $owner }, expiration_timestamp: { _gt: "now()" } } ) { aggregate { count } } expiring_soon: ans_lookup_aggregate( where: { owner: { _eq: $owner }, expiration_timestamp: { _gt: "now()", _lte: "now() + 30 days" } } ) { aggregate { count } } domains: ans_lookup( where: { owner: { _eq: $owner } }, order_by: { expiration_timestamp: asc } ) { name address expiration_timestamp registered_at } } ``` ### Marketplace Trending Names ```graphql query TrendingNames($hours: Int!) { ans_lookup( where: { registered_at: { _gte: "now() - ${hours} hours" } }, order_by: { registered_at: desc }, limit: 50 ) { name address owner registered_at } } ``` ## Common Patterns ```typescript // Display name with fallback to address function displayName(address: string, ansName?: string | null): string { if (ansName) return ansName; return `${address.substring(0, 6)}...${address.substring(address.length - 4)}`; } // Validate name format function isValidANSName(name: string): boolean { return /^[a-z0-9-]{1,63}\.apt$/.test(name); } // Check if name is expired function isExpired(expirationTimestamp: string): boolean { return new Date(expirationTimestamp).getTime() < Date.now(); } ``` ## Related Concepts - [GraphQL Overview](/aptos/graphql_overview) - GraphQL indexer introduction - [Aggregations](/aptos/aggregations) - Aggregate ANS statistics - [User Transactions](/aptos/user_transactions) - Track ANS registrations - [Subscriptions](/aptos/subscriptions) - Real-time ANS updates --- ## fungible_assets > Coming soon: Need support for this? Email support@dwellir.com and we will enable it for you. # Fungible Assets Fungible Assets (FA) represent the next generation token standard on Aptos, providing enhanced functionality compared to the legacy Coin standard. The GraphQL API enables comprehensive querying of FA balances, metadata, transfer histories, and analytics, essential for wallets, DEXes, portfolio trackers, and any application working with tokens. ## Overview The Fungible Asset standard improves upon Coins by supporting programmable behaviors, better metadata management, and composability with the Object model. GraphQL queries provide indexed access to all FA data including current balances, historical activities, supply metrics, and token metadata across all fungible assets on Aptos. ## Core Queries ### Account Balances ```graphql query FaBalances($owner: String!) { current_fungible_asset_balances( where: { owner_address: { _eq: $owner } } ) { owner_address asset_type amount last_transaction_version metadata { name symbol decimals icon_uri project_uri } } } ``` ### Token Metadata ```graphql query TokenInfo($asset_type: String!) { fungible_asset_metadata( where: { asset_type: { _eq: $asset_type } } ) { asset_type creator_address name symbol decimals icon_uri project_uri supply_aggregator_table_handle supply_aggregator_table_key } } ``` ### Transfer History ```graphql query TransferHistory($owner: String!, $limit: Int!) { fungible_asset_activities( where: { _or: [ { owner_address: { _eq: $owner } }, { to_address: { _eq: $owner } } ] }, order_by: { transaction_version: desc }, limit: $limit ) { transaction_version owner_address to_address amount type asset_type transaction_timestamp } } ``` ### Supply Metrics ```graphql query SupplyMetrics($asset_type: String!) { fungible_asset_supply( where: { asset_type: { _eq: $asset_type } } ) { asset_type current_supply max_supply total_minted total_burned } } ``` ### Top Holders ```graphql query TopHolders($asset_type: String!, $limit: Int!) { current_fungible_asset_balances( where: { asset_type: { _eq: $asset_type }, amount: { _gt: "0" } }, order_by: { amount: desc }, limit: $limit ) { owner_address amount last_transaction_version } } ``` ## Real-World Use Cases 1. **Wallet Applications**: Display comprehensive token portfolios with balances, prices, and metadata for all FAs held by users across the Aptos ecosystem. 2. **DEX Interfaces**: Query token metadata, verify decimals, fetch logos, and track liquidity for trading pairs on decentralized exchanges. 3. **Portfolio Trackers**: Aggregate holdings across multiple wallets, calculate total values, and track historical balance changes over time. 4. **Token Analytics**: Analyze holder distribution, supply metrics, transfer volumes, and other statistics for tokens and liquidity pools. 5. **Payment Systems**: Verify balances before transactions, fetch current exchange rates, and track payment histories for accounting purposes. 6. **DeFi Dashboards**: Monitor staking positions, lending collateral, farming rewards, and other DeFi activities involving fungible assets. ## Best Practices **Cache Metadata**: Token metadata (name, symbol, decimals, logo) changes rarely - cache it with long TTLs to reduce API calls. **Handle Decimals**: Always account for token decimals when displaying amounts - a balance of 1000000 with 6 decimals is actually 1.0 tokens. **Batch Balance Queries**: Fetch all balances for an address in a single query rather than separate requests per token. **Track Versions**: Use transaction_version to detect balance changes and avoid displaying stale data. **Filter Zero Balances**: Exclude zero-balance entries to avoid cluttering portfolio displays with tokens users no longer hold. **Use Aggregations**: For analytics, use aggregate queries to compute statistics efficiently rather than fetching all records. **Pagination**: Implement proper pagination for transfer histories and holder lists to handle large datasets. ## TypeScript Integration ```typescript const client = new ApolloClient({ uri: "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/graphql" }); interface TokenBalance { asset_type: string; amount: string; decimals: number; symbol: string; name: string; } async function getPortfolio(address: string): Promise { const { data } = await client.query({ query: gql` query Portfolio($address: String!) { current_fungible_asset_balances( where: { owner_address: { _eq: $address }, amount: { _gt: "0" } } ) { asset_type amount metadata { name symbol decimals } } } `, variables: { address } }); return data.current_fungible_asset_balances.map((balance: any) => ({ asset_type: balance.asset_type, amount: balance.amount, decimals: balance.metadata.decimals, symbol: balance.metadata.symbol, name: balance.metadata.name })); } function formatTokenAmount(amount: string, decimals: number): string { const value = parseInt(amount) / Math.pow(10, decimals); return value.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: decimals }); } ``` ## Advanced Queries ### Portfolio Value Tracking ```graphql query PortfolioWithPrices($owner: String!) { balances: current_fungible_asset_balances( where: { owner_address: { _eq: $owner }, amount: { _gt: "0" } } ) { asset_type amount metadata { name symbol decimals icon_uri } } } ``` ### Token Distribution Analysis ```graphql query HolderDistribution($asset_type: String!) { total_holders: current_fungible_asset_balances_aggregate( where: { asset_type: { _eq: $asset_type }, amount: { _gt: "0" } } ) { aggregate { count } } large_holders: current_fungible_asset_balances_aggregate( where: { asset_type: { _eq: $asset_type }, amount: { _gt: "1000000000" } } ) { aggregate { count } } total_supply: fungible_asset_supply( where: { asset_type: { _eq: $asset_type } } ) { current_supply } } ``` ### Activity Feed ```graphql query RecentActivities($owner: String!, $limit: Int!) { fungible_asset_activities( where: { _or: [ { owner_address: { _eq: $owner } }, { to_address: { _eq: $owner } } ] }, order_by: { transaction_version: desc }, limit: $limit ) { transaction_version owner_address to_address amount type asset_type transaction_timestamp metadata { symbol decimals } } } ``` ## Fungible Assets vs Coins The Fungible Asset standard offers several improvements over the legacy Coin standard: - **Object Integration**: FAs integrate with the Object model for better composability - **Metadata Standards**: Built-in metadata support with URLs for icons and project info - **Programmable Transfers**: Support for custom transfer logic and restrictions - **Better Events**: More comprehensive event emissions for indexing - **Future-Proof**: Designed for long-term extensibility ## Related Concepts - [GraphQL Overview](/aptos/graphql_overview) - GraphQL indexer introduction - [Token Activities](/aptos/token_activities) - NFT and token transfers - [Aggregations](/aptos/aggregations) - Statistical queries - [Object Model](/aptos/object_model) - Object-based asset design --- ## GraphQL API Overview > Coming soon: Need support for this? Email support@dwellir.com and we will enable it for you. # GraphQL API Overview The Aptos indexer GraphQL API provides powerful query capabilities for transactions, token activities, and analytics. Use `https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/graphql` for mainnet access once enabled on your account. ## Example ``` query LedgerInfo { ledger_infos(limit: 1, order_by: {version: desc}) { chain_id version }} ``` --- ## subscriptions > Coming soon: Need support for this? Email support@dwellir.com and we will enable it for you. # GraphQL Subscriptions GraphQL subscriptions enable real-time data streaming from the Aptos blockchain, allowing applications to receive instant notifications when on-chain events occur. This feature is essential for responsive user interfaces, live dashboards, trading bots, and any application requiring immediate updates without polling. ## Overview Unlike traditional queries that fetch data once, subscriptions establish persistent connections that stream updates as blockchain state changes. When a new block is added, transactions are processed, or specific events occur, subscribed clients receive notifications immediately, enabling truly reactive blockchain applications. ## Core Subscription Patterns ### New Transactions ```graphql subscription NewTransactions($address: String!) { user_transactions( where: { _or: [ { sender: { _eq: $address } }, { receiver: { _eq: $address } } ] }, order_by: { version: desc }, limit: 1 ) { hash sender version success gas_used timestamp } } ``` ### Balance Changes ```graphql subscription BalanceUpdates($owner: String!, $asset_type: String!) { current_fungible_asset_balances( where: { owner_address: { _eq: $owner }, asset_type: { _eq: $asset_type } } ) { amount last_transaction_version last_transaction_timestamp } } ``` ### NFT Transfers ```graphql subscription NftActivity($collection: String!) { token_activities_v2( where: { token_data: { collection_id: { _eq: $collection } } }, order_by: { transaction_version: desc }, limit: 1 ) { transaction_version from_address to_address token_data_id type transaction_timestamp } } ``` ### New Blocks ```graphql subscription NewBlocks { ledger_infos( order_by: { version: desc }, limit: 1 ) { chain_id version block_height epoch block_timestamp } } ``` ### Event Monitoring ```graphql subscription EventStream($address: String!, $event_type: String!) { events( where: { account_address: { _eq: $address }, type: { _eq: $event_type } }, order_by: { transaction_version: desc }, limit: 1 ) { sequence_number type data transaction_version transaction_timestamp } } ``` ## Real-World Use Cases 1. **Live Wallets**: Update balances, transaction histories, and token holdings in real-time as blockchain state changes without manual refreshing. 2. **Trading Interfaces**: Stream price updates, order fills, and liquidity changes instantly for responsive trading experiences on DEXes. 3. **Notification Systems**: Alert users immediately when they receive payments, NFT transfers, or other important on-chain events. 4. **Live Dashboards**: Display real-time protocol metrics, transaction volumes, active users, and other statistics with instant updates. 5. **Gaming Applications**: Stream game state changes, item transfers, and player actions in real-time for interactive blockchain games. 6. **Monitoring Tools**: Track smart contract interactions, detect anomalies, and monitor system health with instant event notifications. ## Best Practices **Handle Reconnections**: Implement automatic reconnection logic with exponential backoff when subscription connections drop. **Manage Connection Limits**: Be aware of concurrent subscription limits and reuse connections where possible. **Filter Aggressively**: Use precise WHERE clauses to receive only relevant updates and reduce bandwidth usage. **Implement Debouncing**: For rapid updates, debounce UI updates to prevent overwhelming the interface with changes. **Fallback to Polling**: Have polling-based fallbacks for environments where WebSocket connections aren't available. **Validate Events**: Always validate subscription payloads before processing to handle schema changes gracefully. **Monitor Performance**: Track subscription latency and message rates to ensure responsive user experiences. ## TypeScript Implementation ```typescript // Create WebSocket client const wsClient = new SubscriptionClient( "wss://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/graphql", { reconnect: true, connectionParams: { headers: { "X-API-Key": "YOUR_API_KEY" } } }, ws ); const link = new WebSocketLink(wsClient); const client = new ApolloClient({ link, cache: new InMemoryCache() }); // Subscribe to transactions function subscribeToTransactions(address: string, callback: (tx: any) => void) { const subscription = client.subscribe({ query: gql` subscription NewTransactions($address: String!) { user_transactions( where: { _or: [ { sender: { _eq: $address } }, { receiver: { _eq: $address } } ] }, order_by: { version: desc }, limit: 1 ) { hash sender success timestamp } } `, variables: { address } }); return subscription.subscribe({ next: (result) => callback(result.data.user_transactions[0]), error: (error) => console.error("Subscription error:", error) }); } // Usage const unsubscribe = subscribeToTransactions("0x123...", (transaction) => { console.log("New transaction:", transaction); // Update UI with new transaction }); // Clean up // unsubscribe(); ``` ## Advanced Patterns ### Combined Updates ```typescript // Subscribe to multiple data streams function subscribeToWallet(address: string) { // Transactions const txSub = client.subscribe({ query: TRANSACTION_SUBSCRIPTION, variables: { address } }); // Balance changes const balanceSub = client.subscribe({ query: BALANCE_SUBSCRIPTION, variables: { address } }); // NFT transfers const nftSub = client.subscribe({ query: NFT_SUBSCRIPTION, variables: { address } }); return { unsubscribe: () => { txSub.unsubscribe(); balanceSub.unsubscribe(); nftSub.unsubscribe(); } }; } ``` ### Conditional Subscriptions ```typescript // Only subscribe when needed let subscription: any = null; function startMonitoring(address: string) { if (subscription) return; subscription = subscribeToTransactions(address, (tx) => { if (tx.success) { notifyUser(`Transaction ${tx.hash} confirmed`); } }); } function stopMonitoring() { if (subscription) { subscription.unsubscribe(); subscription = null; } } ``` ### Debounced Updates ```typescript const updateUI = debounce((data: any) => { // Update UI with latest data render(data); }, 100); subscribeToBalances(address, (balance) => { updateUI(balance); }); ``` ## WebSocket Connection Management ```typescript // Robust connection handling class SubscriptionManager { private client: SubscriptionClient; private subscriptions: Map = new Map(); constructor(url: string) { this.client = new SubscriptionClient(url, { reconnect: true, reconnectionAttempts: 5, connectionParams: { headers: { "X-API-Key": process.env.API_KEY } } }); this.client.onReconnected(() => { console.log("Reconnected - resubscribing..."); this.resubscribeAll(); }); } subscribe(id: string, query: any, variables: any, callback: Function) { const sub = this.client.request({ query, variables }).subscribe({ next: (data) => callback(data), error: (error) => console.error(`Subscription ${id} error:`, error) }); this.subscriptions.set(id, { sub, query, variables, callback }); return () => this.unsubscribe(id); } unsubscribe(id: string) { const subscription = this.subscriptions.get(id); if (subscription) { subscription.sub.unsubscribe(); this.subscriptions.delete(id); } } private resubscribeAll() { this.subscriptions.forEach((sub, id) => { this.unsubscribe(id); this.subscribe(id, sub.query, sub.variables, sub.callback); }); } } ``` ## Related Concepts - [GraphQL Overview](/aptos/graphql_overview) - GraphQL API introduction - [Streaming API](/aptos/streaming_overview) - Alternative real-time approach - [Aggregations](/aptos/aggregations) - Statistical queries - [Token Activities](/aptos/token_activities) - Transaction and transfer monitoring --- ## token_activities > Coming soon: Need support for this? Email support@dwellir.com and we will enable it for you. # Token Activities Token activities tracking provides comprehensive visibility into NFT and token operations on Aptos, including mints, transfers, burns, and marketplace interactions. The GraphQL API enables querying of activity histories, ownership changes, and collection analytics essential for NFT marketplaces, portfolio trackers, and blockchain explorers. ## Overview Every NFT interaction on Aptos generates events that are indexed and made queryable through GraphQL. Token activities encompass all operations affecting digital assets - from initial minting through transfers, sales, and eventual burning. This data enables applications to display transaction histories, track provenance, analyze trading patterns, and provide real-time notifications for NFT-related events. ## Core Query Patterns ### User Activity History ```graphql query TokenTransfers($owner: String!, $limit: Int!) { token_activities_v2( where: { owner_address: { _eq: $owner } }, limit: $limit, order_by: { transaction_version: desc } ) { transaction_version event_account_address token_standard from_address to_address token_data_id amount type transaction_timestamp token_data { token_name collection_id current_collection { collection_name creator_address } } } } ``` ### Collection Activity Feed ```graphql query CollectionActivities($collection_id: String!, $limit: Int!) { token_activities_v2( where: { token_data: { collection_id: { _eq: $collection_id } } }, order_by: { transaction_version: desc }, limit: $limit ) { type from_address to_address token_data_id transaction_timestamp transaction_version } } ``` ### Recent Mints ```graphql query RecentMints($collection_id: String!) { token_activities_v2( where: { type: { _eq: "0x4::token::MintEvent" }, token_data: { collection_id: { _eq: $collection_id } } }, order_by: { transaction_version: desc }, limit: 50 ) { to_address token_data_id transaction_timestamp transaction_version } } ``` ### Sales and Transfers ```graphql query TokenSales($token_data_id: String!) { token_activities_v2( where: { token_data_id: { _eq: $token_data_id }, type: { _in: ["0x4::token::TransferEvent", "marketplace_sale"] } }, order_by: { transaction_version: desc } ) { type from_address to_address transaction_version transaction_timestamp event_account_address } } ``` ### Burn Events ```graphql query BurnedTokens($collection_id: String!) { token_activities_v2( where: { type: { _eq: "0x4::token::BurnEvent" }, token_data: { collection_id: { _eq: $collection_id } } }, order_by: { transaction_version: desc } ) { token_data_id from_address transaction_timestamp } } ``` ## Real-World Use Cases 1. **NFT Marketplaces**: Display comprehensive activity feeds showing mints, listings, sales, and transfers for collections and individual NFTs with real-time updates. 2. **Portfolio Trackers**: Show users their complete NFT transaction history including acquisitions, sales, transfers, and current holdings across all collections. 3. **Collection Analytics**: Analyze trading volumes, mint rates, holder behavior, and price trends for NFT collections to provide market intelligence. 4. **Provenance Tracking**: Build complete ownership histories showing every transfer from mint to current owner for authenticity verification. 5. **Notification Systems**: Alert users instantly when their NFTs are transferred, listed, sold, or when new items mint in collections they follow. 6. **Marketplace Aggregators**: Combine activity data from multiple marketplaces to provide comprehensive views of NFT trading across the ecosystem. ## Best Practices **Filter by Activity Type**: Use the type field to distinguish between mints, transfers, burns, and marketplace events for appropriate handling. **Paginate Results**: Implement cursor-based pagination for activity feeds to efficiently handle collections with high volumes of transactions. **Join with Token Data**: Always join activities with token_data to fetch metadata (names, images, attributes) for display. **Cache Collection Metadata**: Collection-level data changes rarely - cache it aggressively to reduce duplicate queries. **Handle Missing Data**: Not all activities have complete metadata - implement fallbacks for missing names, images, or attributes. **Time-Based Filtering**: Use transaction_timestamp for date range queries when analyzing historical trends or generating reports. **Aggregate for Statistics**: Use aggregate queries to compute volumes, counts, and other metrics rather than client-side processing. ## TypeScript Integration ```typescript const client = new ApolloClient({ uri: "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/graphql" }); interface TokenActivity { type: string; fromAddress: string; toAddress: string; tokenDataId: string; timestamp: string; tokenName: string; collectionName: string; } async function getActivityFeed(address: string, limit: number = 50): Promise { const { data } = await client.query({ query: gql` query ActivityFeed($address: String!, $limit: Int!) { token_activities_v2( where: { _or: [ { from_address: { _eq: $address } }, { to_address: { _eq: $address } } ] }, order_by: { transaction_version: desc }, limit: $limit ) { type from_address to_address token_data_id transaction_timestamp token_data { token_name current_collection { collection_name } } } } `, variables: { address, limit } }); return data.token_activities_v2.map((activity: any) => ({ type: activity.type, fromAddress: activity.from_address, toAddress: activity.to_address, tokenDataId: activity.token_data_id, timestamp: activity.transaction_timestamp, tokenName: activity.token_data?.token_name || "Unknown", collectionName: activity.token_data?.current_collection?.collection_name || "Unknown" })); } // Format activity for display function formatActivity(activity: TokenActivity): string { if (activity.type.includes("Mint")) { return `Minted ${activity.tokenName}`; } else if (activity.type.includes("Transfer")) { return `Transferred ${activity.tokenName} from ${activity.fromAddress.substring(0, 6)}... to ${activity.toAddress.substring(0, 6)}...`; } else if (activity.type.includes("Burn")) { return `Burned ${activity.tokenName}`; } return `${activity.type} - ${activity.tokenName}`; } ``` ## Advanced Queries ### Collection Trading Volume ```graphql query TradingVolume($collection_id: String!, $since: timestamp!) { token_activities_v2_aggregate( where: { token_data: { collection_id: { _eq: $collection_id } }, type: { _in: ["marketplace_sale", "0x4::token::TransferEvent"] }, transaction_timestamp: { _gte: $since } } ) { aggregate { count } } activities: token_activities_v2( where: { token_data: { collection_id: { _eq: $collection_id } }, type: { _in: ["marketplace_sale"] }, transaction_timestamp: { _gte: $since } }, order_by: { transaction_timestamp: desc } ) { transaction_timestamp from_address to_address token_data_id } } ``` ### Most Active Traders ```graphql query ActiveTraders($collection_id: String!, $days: Int!) { token_activities_v2( where: { token_data: { collection_id: { _eq: $collection_id } }, transaction_timestamp: { _gte: "now() - ${days} days" } }, distinct_on: from_address ) { from_address } } ``` ### Token Provenance Chain ```graphql query TokenHistory($token_data_id: String!) { token_activities_v2( where: { token_data_id: { _eq: $token_data_id } }, order_by: { transaction_version: asc } ) { type from_address to_address transaction_version transaction_timestamp event_account_address } } ``` ## Activity Type Classification Common activity types and their meanings: - `0x4::token::MintEvent`: NFT was minted - `0x4::token::TransferEvent`: NFT was transferred - `0x4::token::BurnEvent`: NFT was burned/destroyed - `marketplace_listing`: NFT was listed for sale - `marketplace_sale`: NFT was sold - `marketplace_delist`: Listing was cancelled ## Pagination Pattern ```typescript async function getPaginatedActivities( address: string, limit: number, offset: number ): Promise { const { data } = await client.query({ query: gql` query PaginatedActivities($address: String!, $limit: Int!, $offset: Int!) { token_activities_v2( where: { owner_address: { _eq: $address } }, order_by: { transaction_version: desc }, limit: $limit, offset: $offset ) { # fields... } } `, variables: { address, limit, offset } }); return data.token_activities_v2; } ``` ## Related Concepts - [Fungible Assets](/aptos/fungible_assets) - Token balance queries - [Aggregations](/aptos/aggregations) - Activity statistics - [Subscriptions](/aptos/subscriptions) - Real-time activity streams - [Object Model](/aptos/object_model) - NFT architecture --- ## user_transactions > Coming soon: Need support for this? Email support@dwellir.com and we will enable it for you. # user_transactions ## Overview Query transactions submitted by a specific address. ## Query Structure ```graphql query GetUserTransactions($address: String!, $limit: Int) { user_transactions( where: { sender: { _eq: $address } } limit: $limit order_by: { version: desc } ) { version hash success vm_status gas_used } } ``` ## Variables | Name | Type | Required | Description | | -- | -- | -- | -- | | address | String | Yes | Account address | | limit | Int | No | Result limit | ## Code Examples ``` query = """query GetUserTransactions($address: String!, $limit: Int) { user_transactions(where: { sender: { _eq: $address } }, limit: $limit, order_by: { version: desc }) { version hash success vm_status gas_used } }""" variables = {"address": "0x1", "limit": 10} requests.post("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/graphql", json={"query": query, "variables": variables}) ``` ``` const query = `query GetUserTransactions($address: String!, $limit: Int) { user_transactions(where: { sender: { _eq: $address } }, limit: $limit, order_by: { version: desc }) { version hash success vm_status gas_used } }`; const variables = { address: "0x1", limit: 10 }; await fetch("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/graphql", { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query, variables }) }); ``` --- ## Aptos Network Documentation ## Why Build on Aptos - 160K+ TPS via Block-STM parallel execution - Sub-second finality (~250 ms blocks) with AptosBFT v4 - Resource-oriented Move language with formal verification - Native sponsored and multi-agent transactions - Object model for powerful composition - Evolving token standards (Fungible Asset and Digital Asset) ## Quick Start ```bash curl -X GET https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1 \ -H "Accept: application/json" ``` ```ts const config = new AptosConfig({ network: Network.MAINNET, fullnode: "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1", }); const aptos = new Aptos(config); const info = await aptos.getLedgerInfo(); console.log(info.chain_id, info.ledger_version); ``` ```python from aptos_sdk.client import RestClient client = RestClient("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1") info = client.get_ledger_info() print(info["chain_id"], info["ledger_version"]) # 1 APT = 100,000,000 Octas ``` ```rust use aptos_sdk::rest_client::Client; let client = Client::new("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1".parse()?); let info = client.get_ledger_information().await?; println!("{} {}", info.inner().chain_id, info.inner().ledger_version); ``` ## Network Information Chain ID 1 Mainnet Native Token APT 1 APT = 100,000,000 Octas Consensus AptosBFT v4 ~250 ms blocks Execution Block-STM Parallel transactions ## REST API Reference - Base path: `/v1` - Auth: Add your key in the URL path: `https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1` - JSON responses, snake_case fields, bcs-encoded payloads for transactions ## GraphQL API Reference - Indexer GraphQL endpoint: `https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/graphql` - Advanced queries for transactions, tokens, ANS, aggregations - Real-time subscription support (see Streaming for gRPC) See the GraphQL section for examples and schema notes. ## Transaction Stream Service - gRPC-based real-time transaction stream - Historical replay from genesis, checkpointing, custom processors - Early access available — email `support@dwellir.com` ## Move Development - Entry functions (transactions) vs view functions (read-only) - Modules, resources, and abilities (key, store, drop, copy) - Testing with Move unit tests and Move Prover ## Object Model - Globally addressable objects enable safe composition - Reference types: `ConstructorRef`, `MutatorRef`, `DeleteRef` - Ownership hierarchies and type-safe conversions ## Token Standards - Legacy: `0x1::coin`, `0x3::token` - Current: Fungible Asset (FA) and Digital Asset (DA) - Migration patterns and compatibility tips ## Unique Aptos Features - Sponsored transactions (fee payer) - Multi-agent transactions (multiple signers) - Key rotation (proven/unproven) - Aggregator V2 counters - Orderless transactions ## Code Examples Find end-to-end examples for transfers, NFTs, module publish, and token ops in the respective sections. ## Performance Optimization - Parallel-friendly design patterns (minimize write conflicts) - Gas optimization via simulation and views - Aggregators for scalable counters - Batching reads and writes when appropriate ## Troubleshooting - Common REST errors, transaction failures, module verification - Gas estimation pitfalls and how to resolve them ## Resources & Tools - Official SDKs (TS, Python, Rust) - Explorers, faucets, testing tools, community links --- ## entry_functions ## Overview Entry functions are the primary mechanism for executing Move code via transactions on Aptos. These special functions serve as transaction entry points, allowing external accounts to trigger on-chain logic execution. ## Technical Details Entry functions are declared with the `public entry` visibility modifier in Move modules: ```move public entry fun transfer(from: &signer, to: address, amount: u64) { // Function implementation } ``` **Key Characteristics**: - Must be marked with both `public` and `entry` keywords - Can be called directly from transactions - Cannot return values (void return type) - Can modify blockchain state - Execute with the transaction sender's authority - Support generic type parameters ## How Entry Functions Work When a transaction calls an entry function: 1. The Move VM loads the module containing the function 2. Arguments are BCS-deserialized from transaction payload 3. The function executes with sender's signer capability 4. State changes are committed if execution succeeds 5. Events are emitted to the blockchain 6. Gas is consumed based on computational cost Entry functions form the external API of Move modules, bridging off-chain applications with on-chain logic. ## Practical Examples **Simple Transfer:** ```move public entry fun simple_transfer(sender: &signer, recipient: address, amount: u64) { coin::transfer(sender, recipient, amount); } ``` **With Type Parameters:** ```move public entry fun swap( sender: &signer, amount_in: u64, min_amount_out: u64 ) { // DEX swap implementation } ``` **Multiple Operations:** ```move public entry fun batch_mint(admin: &signer, recipients: vector
, amounts: vector) { let len = vector::length(&recipients); let i = 0; while (i < len) { let recipient = *vector::borrow(&recipients, i); let amount = *vector::borrow(&amounts, i); mint_to(admin, recipient, amount); i = i + 1; }; } ``` ## Use Cases Entry functions power diverse blockchain applications: 1. **Token Operations**: Transfers, minting, burning, and approvals for fungible and non-fungible tokens. 2. **DeFi Protocols**: Swaps, liquidity provision, staking, and yield farming operations. 3. **NFT Marketplaces**: Listing, purchasing, bidding, and collection management. 4. **Gaming**: Character creation, item crafting, battle execution, and reward distribution. 5. **Governance**: Proposal submission, voting, and execution of governance decisions. 6. **Identity**: Account creation, key rotation, and permission management. ## Best Practices **Input Validation**: Always validate inputs within entry functions to prevent invalid state transitions. Check address validity, amount ranges, and permission requirements explicitly. **Avoid Write Conflicts**: Under Block-STM parallel execution, minimize conflicts by: - Reading shared resources early in execution - Writing to unique per-account resources when possible - Using fine-grained resource structures instead of global state - Leveraging Aggregator V2 for concurrent counters **Gas Efficiency**: Keep entry functions focused and delegate complex logic to internal helper functions. This improves code organization and allows better gas optimization. **Error Handling**: Use descriptive abort codes and messages to help developers debug failed transactions: ```move const EINSUFFICIENT_BALANCE: u64 = 1; const EINVALID_RECIPIENT: u64 = 2; public entry fun safe_transfer(sender: &signer, to: address, amount: u64) { assert!(to != @0x0, EINVALID_RECIPIENT); assert!(coin::balance(signer::address_of(sender)) >= amount, EINSUFFICIENT_BALANCE); coin::transfer(sender, to, amount); } ``` **Signer Requirement**: Only include `&signer` parameters for accounts that must authorize the transaction. Extra signer parameters complicate multi-signature scenarios unnecessarily. **Event Emission**: Emit events for significant state changes to enable off-chain indexing and monitoring: ```move event::emit(TransferEvent { from: signer::address_of(sender), to: recipient, amount }); ``` ## Common Patterns **Admin Functions**: Restrict privileged operations with capability checks: ```move public entry fun admin_mint(admin: &signer, to: address, amount: u64) acquires AdminCap { let admin_addr = signer::address_of(admin); assert!(exists(admin_addr), ENOT_ADMIN); // Mint logic } ``` **Batch Operations**: Process multiple operations in one transaction for efficiency: ```move public entry fun batch_transfer(sender: &signer, recipients: vector
, amounts: vector) { let len = vector::length(&recipients); let i = 0; while (i < len) { coin::transfer(sender, *vector::borrow(&recipients, i), *vector::borrow(&amounts, i)); i = i + 1; }; } ``` **Resource Initialization**: Create and move resources to accounts: ```move public entry fun initialize_account(account: &signer) { move_to(account, AccountData { balance: 0, nonce: 0 }); } ``` ## Anti-Patterns to Avoid - **Returning Values**: Entry functions cannot return values. Use view functions for read operations. - **Excessive Computation**: Long-running computations cause high gas costs and potential timeouts. - **Global Locks**: Accessing single global resources creates bottlenecks under Block-STM. - **Unbounded Loops**: Loops over unbounded vectors risk gas exhaustion. ## Related Concepts - **View Functions**: Read-only functions for querying state without gas costs - **Script Functions**: Legacy transaction entry points, now superseded by entry functions - **Public Functions**: Module functions callable by other modules but not directly via transactions - **Inline Functions**: Private helper functions for code organization --- ## events ## Overview Events in Move provide a mechanism for smart contracts to emit structured notifications about state changes to off-chain systems. Events enable indexers, applications, and users to track on-chain activities without continuously polling resources. ## Technical Details Events are defined as Move structs and emitted using the `event::emit` function: ```move use aptos_framework::event; struct TransferEvent has drop, store { from: address, to: address, amount: u64 } public entry fun transfer_with_event(from: &signer, to: address, amount: u64) { // Transfer logic here event::emit(TransferEvent { from: signer::address_of(from), to, amount }); } ``` **Event Properties**: - Stored off-chain in transaction metadata, not on-chain state - Ordered sequentially within each transaction - Identified by type and containing transaction - Queryable via REST API and GraphQL indexer - Support generic type parameters - Require `drop` and `store` abilities ## How Events Work When code emits an event during transaction execution: 1. Event data is serialized and attached to the transaction 2. Validators include events in the committed transaction output 3. Indexers process events and make them queryable 4. Applications query events via REST or GraphQL APIs 5. Events provide an audit trail of contract activity Unlike state changes that modify resources, events create an append-only log that never changes. ## Practical Examples **Token Transfer Events:** ```move struct CoinTransferEvent has drop, store { sender: address, receiver: address, amount: u64, coin_type: TypeInfo } ``` **NFT Marketplace Events:** ```move struct ListingCreatedEvent has drop, store { seller: address, token_id: TokenId, price: u64, expiration: u64 } struct PurchaseEvent has drop, store { buyer: address, seller: address, token_id: TokenId, price: u64 } ``` **DeFi Protocol Events:** ```move struct SwapEvent has drop, store { user: address, coin_in_type: TypeInfo, coin_out_type: TypeInfo, amount_in: u64, amount_out: u64, fee: u64 } ``` ## Use Cases Events enable powerful off-chain functionality: 1. **User Activity Feeds**: Display transaction history and account activity in wallets and applications. 2. **Real-Time Notifications**: Trigger webhooks or push notifications when specific events occur. 3. **Analytics Dashboards**: Aggregate events to compute metrics like trading volume, user growth, or protocol usage. 4. **Compliance and Auditing**: Maintain immutable audit trails of all contract interactions for regulatory requirements. 5. **State Reconstruction**: Replay events to rebuild application state without querying all resources. 6. **Cross-Contract Coordination**: Monitor events from other contracts to trigger conditional logic. ## Best Practices **Structured Event Design**: Design events with all information needed by consumers. Include addresses, amounts, timestamps, and type information. **Consistent Naming**: Use descriptive event names with consistent patterns: `TransferEvent`, `MintEvent`, `BurnEvent`. **Emit After Success**: Only emit events after operations succeed to avoid confusing off-chain systems with failed attempt notifications. **Version Events**: When upgrading contracts, consider versioning events or adding optional fields to maintain backward compatibility with indexers. **Gas Efficiency**: Events are relatively cheap but not free. Emit only essential notifications. **Type Information**: Include type parameters or TypeInfo when events involve generic types to enable proper deserialization. ## Event Querying Access events via multiple endpoints: **REST API by Creation Number**: ``` GET /v1/accounts/{address}/events/{creation_number} ``` **REST API by Handle**: ``` GET /v1/accounts/{address}/events/{event_handle}/{field_name} ``` **GraphQL Indexer** (when available): Provides complex filtering, aggregation, and joins across multiple event types. ## Common Patterns **Event Handles** (Legacy Pattern): ```move struct EventStore has key { transfer_events: EventHandle } ``` **Modern Event Emission** (Recommended): ```move // No event handle needed public entry fun transfer(from: &signer, to: address, amount: u64) { // Logic event::emit(TransferEvent { from: signer::address_of(from), to, amount }); } ``` The modern approach is simpler and more efficient. ## Related Concepts - **Event Handles**: Legacy mechanism for organizing events (still supported but not recommended for new code) - **GraphQL Indexer**: Query engine for complex event analysis - **REST Event Endpoints**: Direct event access via REST API - **Transaction Metadata**: Events are stored with transaction results --- ## formal_verification # Formal Verification Formal verification in Move uses the Move Prover tool to mathematically verify that smart contracts behave correctly under all possible conditions. Unlike traditional testing which checks specific scenarios, formal verification provides mathematical proofs that your code satisfies specified properties for all possible inputs and states. ## Overview The Move Prover is a sophisticated verification tool that analyzes Move modules and proves that they satisfy formal specifications written in the Move Specification Language (MSL). It uses automated theorem proving techniques to verify safety properties, invariants, and functional correctness of your smart contracts before deployment. ## Technical Implementation Formal verification works by translating Move code and specifications into logical formulas that can be processed by SMT (Satisfiability Modulo Theories) solvers. The prover checks whether your code can violate any specified invariants or preconditions under any execution path. ### Specification Syntax ```move module 0x1::verified_coin { use std::signer; struct Balance has key { value: u64 } spec Balance { invariant value <= MAX_U64; } public fun transfer(from: &signer, to: address, amount: u64) acquires Balance { let from_addr = signer::address_of(from); let from_balance = &mut borrow_global_mut(from_addr).value; let to_balance = &mut borrow_global_mut(to).value; *from_balance = *from_balance - amount; *to_balance = *to_balance + amount; } spec transfer { requires exists(signer::address_of(from)); requires exists(to); requires borrow_global(signer::address_of(from)).value >= amount; ensures borrow_global(to).value == old(borrow_global(to).value) + amount; ensures borrow_global(signer::address_of(from)).value == old(borrow_global(signer::address_of(from)).value) - amount; } } ``` ## Real-World Use Cases 1. **DeFi Protocol Security**: Verify that token supply invariants hold across all transfer, mint, and burn operations, ensuring no tokens can be created or destroyed unexpectedly. 2. **Access Control Validation**: Prove that administrative functions can only be called by authorized accounts and that privilege escalation is impossible. 3. **Asset Conservation**: Verify that total value in lending protocols, DEXes, or vaults remains constant during operations, preventing loss of funds. 4. **Upgrade Safety**: Prove that module upgrades maintain backward compatibility and preserve critical invariants about stored data. 5. **Overflow Protection**: Mathematically verify that arithmetic operations cannot overflow or underflow, eliminating a major class of vulnerabilities. 6. **State Machine Correctness**: Verify that state transitions in governance systems, auctions, or multi-step processes follow valid sequences. ## Best Practices **Focus on Critical Properties**: Start by verifying the most important safety properties such as asset conservation, access control, and state invariants. Don't try to verify everything at once. **Use Modular Specifications**: Break down complex specifications into smaller, reusable components using schema and helper functions in MSL. **Test Specifications**: Specifications can have bugs too. Use the prover's counterexample feature to validate that your specifications catch actual bugs. **Iterative Refinement**: Begin with simple invariants and progressively add more detailed specifications as you gain confidence in the prover's behavior. **Performance Optimization**: Use timeouts, specify verification scope, and leverage modular verification to keep proof times manageable for large codebases. **Documentation**: Specifications serve as precise documentation of your contract's behavior. Keep them readable and well-commented. ## Running the Move Prover ```bash # Verify all modules in a package aptos move prove --package-dir . # Verify specific module aptos move prove --package-dir . --filter "0x1::verified_coin" # Generate detailed error traces aptos move prove --package-dir . --verbose # Set timeout for proofs aptos move prove --package-dir . --timeout 120 ``` The prover will report any specification violations with counterexamples showing how the property can be violated, or confirm that all specifications hold. ## Related Concepts - [Testing](/aptos/testing) - Complement formal verification with comprehensive unit tests - [Module Structure](/aptos/module_structure) - Organize code to facilitate verification - [Resource Management](/aptos/resource_management) - Understand resource semantics for writing correct specifications --- ## module_structure # Module Structure Move modules are the fundamental building blocks of smart contracts on Aptos. They encapsulate types, functions, and constants into reusable, composable units that can be published on-chain and invoked by transactions. Understanding proper module structure is essential for building maintainable, secure, and efficient smart contracts. ## Overview Move modules define types (structs), functions (both public and private), and constants under a specific account address. On Aptos, modules are published to the blockchain under an account address and become immutable once deployed, though they can be upgraded following specific compatibility rules. Each module has a unique identifier consisting of the publishing account address and the module name (e.g., `0x1::coin`). ## Module Anatomy A well-structured Move module typically contains the following components organized in a logical order: ```move module 0x1::example_token { // 1. Imports use std::signer; use std::string::String; use aptos_framework::event; use aptos_framework::timestamp; // 2. Error codes const ENOT_AUTHORIZED: u64 = 1; const EINSUFFICIENT_BALANCE: u64 = 2; const EALREADY_INITIALIZED: u64 = 3; // 3. Constants const MAX_SUPPLY: u64 = 1_000_000_000; const DECIMALS: u8 = 8; // 4. Structs (types) struct TokenStore has key { balance: u64, frozen: bool } struct Capabilities has key { mint_cap: MintCapability, burn_cap: BurnCapability } struct MintCapability has store, drop {} struct BurnCapability has store, drop {} // 5. Events struct TransferEvent has drop, store { from: address, to: address, amount: u64, timestamp: u64 } // 6. Event handles struct EventStore has key { transfer_events: event::EventHandle } // 7. Public entry functions (transaction entry points) public entry fun initialize(account: &signer) { // Implementation } public entry fun transfer(from: &signer, to: address, amount: u64) acquires TokenStore, EventStore { // Implementation } // 8. Public functions (callable by other modules) public fun balance_of(addr: address): u64 acquires TokenStore { // Implementation 0 } // 9. Public(friend) functions public(friend) fun mint(cap: &MintCapability, to: address, amount: u64) acquires TokenStore { // Implementation } // 10. Internal functions fun internal_transfer(from: address, to: address, amount: u64) acquires TokenStore { // Implementation } // 11. Helper functions fun validate_amount(amount: u64): bool { amount > 0 && amount <= MAX_SUPPLY } } ``` ## Abilities and Type Safety Move's ability system provides fine-grained control over how types can be used. The four abilities are: - **key**: Can be stored as a top-level resource under an account (required for global storage) - **store**: Can be stored inside other structs with the `key` ability - **copy**: Values can be copied (duplicated) - **drop**: Values can be implicitly discarded Use abilities judiciously to enforce proper resource semantics and prevent common vulnerabilities like resource duplication or accidental deletion. ## Real-World Use Cases 1. **Token Contracts**: Structure modules to manage fungible or non-fungible token supply, balances, and metadata with proper access controls and event emissions. 2. **DeFi Protocols**: Organize complex financial logic into separate modules for lending, borrowing, liquidity pools, and governance, each with clear interfaces. 3. **NFT Marketplaces**: Create modular systems with separate modules for listings, bids, royalties, and transfers to facilitate maintainability and upgrades. 4. **Governance Systems**: Structure voting, proposal, and execution logic into distinct modules with clear separation of concerns. 5. **Access Control Systems**: Build reusable authentication and authorization modules that other contracts can leverage through public interfaces. 6. **Oracle Integration**: Create structured modules that fetch and validate external data with proper error handling and event emission. ## Best Practices **Minimize Entry Function Logic**: Keep entry functions thin by delegating complex logic to internal functions. This improves testability and code reuse. **Emit Comprehensive Events**: Emit events for all state changes to enable off-chain indexing and user notifications. Include relevant context in event data. **Error Code Organization**: Define all error codes as module constants at the top of the file with descriptive names prefixed with 'E'. **Function Ordering**: Follow a consistent ordering pattern (entry functions first, then public, then internal) to improve code readability. **Use Friend Declarations**: Leverage the `friend` visibility modifier to expose functions only to trusted modules while maintaining encapsulation. **Document Acquires**: Always document which resources a function acquires to help developers understand global storage access patterns. **Separate Concerns**: Split large modules into smaller, focused modules that each handle a specific concern or feature. ## Module Dependencies ```move // In Move.toml [dependencies] AptosFramework = { git = "https://github.com/aptos-labs/aptos-core.git", subdir = "aptos-move/framework/aptos-framework", rev = "mainnet" } [addresses] my_project = "_" ``` Properly manage dependencies in your Move.toml file and use named addresses to make modules portable across different deployment environments. ## Related Concepts - [Upgradability](/aptos/upgradability) - Learn how to safely upgrade modules - [Resource Management](/aptos/resource_management) - Understand Move's resource model - [Testing](/aptos/testing) - Best practices for testing module functionality - [View Functions](/aptos/view_functions) - Implement gas-free read operations --- ## resource_management # Resource Management Resource management is one of Move's most distinctive and powerful features, providing built-in safety guarantees that prevent common blockchain vulnerabilities. Move's resource model ensures that digital assets cannot be copied, accidentally lost, or double-spent through compiler-enforced linear type semantics and explicit resource handling patterns. ## Overview Resources in Move are special types marked with the `key` ability that represent digital assets or critical state. Unlike regular data structures, resources have strict lifecycle rules: they cannot be copied or implicitly destroyed, must be explicitly moved between storage locations, and can only exist in one place at a time. This linear type system eliminates entire classes of vulnerabilities that plague other blockchain platforms. ## Resource Lifecycle Resources follow a strict lifecycle from creation to destruction: ```move module 0x1::resource_example { use std::signer; // Resource definition - key ability required for global storage struct Vault has key { balance: u64, owner: address } // Creating a resource public entry fun create_vault(account: &signer, initial_balance: u64) { let vault = Vault { balance: initial_balance, owner: signer::address_of(account) }; // Move resource into global storage move_to(account, vault); } // Accessing a resource - requires acquires annotation public fun get_balance(addr: address): u64 acquires Vault { let vault_ref = borrow_global(addr); vault_ref.balance } // Modifying a resource public entry fun deposit(account: &signer, amount: u64) acquires Vault { let addr = signer::address_of(account); let vault_ref = borrow_global_mut(addr); vault_ref.balance = vault_ref.balance + amount; } // Moving resource out of storage public entry fun destroy_vault(account: &signer) acquires Vault { let addr = signer::address_of(account); let Vault { balance: _, owner: _ } = move_from(addr); // Resource is destructured and destroyed } } ``` ## Acquires Annotation The `acquires` keyword is mandatory for functions that access global resources. It serves both as documentation and as a compiler check to prevent reentrancy vulnerabilities: ```move // Function that reads from one resource and writes to another public fun transfer_between_vaults( from: address, to: address, amount: u64 ) acquires Vault { let from_vault = borrow_global_mut(from); from_vault.balance = from_vault.balance - amount; let to_vault = borrow_global_mut(to); to_vault.balance = to_vault.balance + amount; } // Multiple resource types require listing all public fun complex_operation(addr: address) acquires Vault, UserProfile, Settings { // Can access all three resource types } ``` ## Resource Patterns ### Capability Pattern Use capability resources to control access to privileged operations: ```move struct MintCapability has key, store { total_minted: u64 } public fun mint_with_cap( cap: &mut MintCapability, recipient: address, amount: u64 ) { cap.total_minted = cap.total_minted + amount; // Mint logic here } ``` ### Witness Pattern Use one-time witnesses for initialization guarantees: ```move struct COIN has drop {} public fun initialize(witness: COIN, account: &signer) { // Can only be called once because witness is consumed } ``` ### Hot Potato Pattern Create types without drop ability to force handling: ```move struct Receipt { amount: u64, must_be_consumed: bool } public fun create_receipt(): Receipt { Receipt { amount: 100, must_be_consumed: true } } public fun consume_receipt(receipt: Receipt) { let Receipt { amount: _, must_be_consumed: _ } = receipt; } ``` ## Real-World Use Cases 1. **Token Implementations**: Manage token balances as resources to guarantee conservation of supply and prevent unauthorized minting or burning through compiler-enforced linearity. 2. **NFT Ownership**: Represent unique digital assets as resources that cannot be duplicated, ensuring true scarcity and provable ownership on-chain. 3. **Vault Systems**: Build secure storage mechanisms where assets can only be accessed by authorized parties, leveraging resource semantics for safety. 4. **Permission Systems**: Create capability resources that grant specific permissions, ensuring that access rights cannot be forged or duplicated. 5. **Escrow Services**: Hold resources in escrow with guaranteed atomic transfers, where assets must either complete the full transfer or remain in the original location. 6. **Gaming Assets**: Represent in-game items as resources with unique properties that cannot be duplicated or destroyed outside intended game mechanics. ## Best Practices **Always Document Acquires**: Explicitly list all resource types a function accesses in the acquires clause, even when it seems obvious. This helps prevent subtle bugs. **Check Resource Existence**: Use `exists(address)` before borrowing resources to handle cases where resources might not be initialized. **Avoid Cross-Module Resource Access**: Design modules to manage their own resources rather than accessing resources defined in other modules when possible. **Use Immutable Borrows**: Prefer `borrow_global` over `borrow_global_mut` when only reading data to reduce potential for concurrent access issues. **Structured Destruction**: When moving resources out of storage, always destructure them completely to ensure all fields are properly handled. **Resource Initialization**: Provide clear initialization functions and document preconditions for resource creation to prevent misuse. **Capability Distribution**: Carefully control how and when capability resources are created and distributed to maintain system security. ## Common Patterns ```move // Check-then-access pattern if (exists(addr)) { let vault = borrow_global(addr); // Use vault }; // Modify with validation public entry fun safe_withdraw(account: &signer, amount: u64) acquires Vault { let addr = signer::address_of(account); assert!(exists(addr), EVAULT_NOT_FOUND); let vault = borrow_global_mut(addr); assert!(vault.balance >= amount, EINSUFFICIENT_BALANCE); vault.balance = vault.balance - amount; } ``` ## Related Concepts - [Module Structure](/aptos/module_structure) - Organize resource definitions effectively - [Formal Verification](/aptos/formal_verification) - Prove resource invariants mathematically - [Object Model](/aptos/object_model) - Alternative resource composition approach - [Testing](/aptos/testing) - Test resource lifecycle operations --- ## testing # Testing Testing is crucial for building reliable smart contracts on Aptos. Move provides a comprehensive testing framework that supports unit tests, integration tests, and end-to-end testing scenarios. Proper testing helps catch bugs early, validates business logic, and provides confidence when deploying contracts that manage valuable assets. ## Overview Move's testing framework allows you to write tests directly in your Move source files using the `#[test]` attribute. Tests can interact with the blockchain state, simulate different signers, and validate both success and failure scenarios. The Aptos CLI provides commands to run tests with detailed output and coverage reporting. ## Unit Testing Basics Unit tests verify individual functions and modules in isolation: ```move module 0x1::calculator { public fun add(a: u64, b: u64): u64 { a + b } public fun divide(a: u64, b: u64): u64 { assert!(b != 0, 1); // EDIVIDE_BY_ZERO a / b } #[test] fun test_add() { assert!(add(2, 3) == 5, 0); assert!(add(0, 0) == 0, 0); assert!(add(100, 200) == 300, 0); } #[test] fun test_divide() { assert!(divide(10, 2) == 5, 0); assert!(divide(100, 10) == 10, 0); } #[test] #[expected_failure(abort_code = 1)] fun test_divide_by_zero() { divide(10, 0); // Should abort with error code 1 } } ``` ## Testing with Signers Test functions can receive signer parameters for testing account-specific logic: ```move module 0x1::vault { use std::signer; struct Vault has key { balance: u64 } public fun create_vault(account: &signer, initial: u64) { move_to(account, Vault { balance: initial }); } public fun deposit(account: &signer, amount: u64) acquires Vault { let vault = borrow_global_mut(signer::address_of(account)); vault.balance = vault.balance + amount; } #[test(account = @0x1)] fun test_create_vault(account: &signer) { create_vault(account, 100); assert!(exists(@0x1), 0); } #[test(account = @0x1)] fun test_deposit(account: &signer) acquires Vault { create_vault(account, 100); deposit(account, 50); let vault = borrow_global(@0x1); assert!(vault.balance == 150, 0); } #[test(account = @0x1)] #[expected_failure] fun test_double_create_fails(account: &signer) { create_vault(account, 100); create_vault(account, 200); // Should fail - resource already exists } } ``` ## Multi-Account Testing Test scenarios involving multiple accounts: ```move #[test(from = @0x1, to = @0x2)] fun test_transfer(from: &signer, to: &signer) acquires TokenStore { // Setup initialize(from, 1000); initialize(to, 0); // Execute transfer transfer(from, signer::address_of(to), 100); // Verify balances assert!(balance_of(@0x1) == 900, 0); assert!(balance_of(@0x2) == 100, 0); } #[test(alice = @0x1, bob = @0x2, charlie = @0x3)] fun test_multi_party_transaction( alice: &signer, bob: &signer, charlie: &signer ) acquires TokenStore { // Complex multi-account test scenario } ``` ## Testing Events Validate that events are emitted correctly: ```move #[test(account = @0x1)] fun test_transfer_event(account: &signer) acquires TokenStore, EventStore { use aptos_framework::event; initialize(account, 1000); // Get initial event counter let event_store = borrow_global(@0x1); let initial_count = event::counter(&event_store.transfer_events); // Execute operation transfer(account, @0x2, 100); // Verify event was emitted let final_count = event::counter(&event_store.transfer_events); assert!(final_count == initial_count + 1, 0); } ``` ## Test Helpers and Setup Create helper functions for common test scenarios: ```move #[test_only] module 0x1::test_helpers { use std::signer; use 0x1::vault; public fun setup_vault(account: &signer, balance: u64) { vault::create_vault(account, balance); } public fun create_test_accounts(): (signer, signer, signer) { // Test-only function to create multiple accounts } } // Use in tests #[test(account = @0x1)] fun test_with_helper(account: &signer) { test_helpers::setup_vault(account, 100); // Continue test } ``` ## Real-World Use Cases 1. **Token Contract Validation**: Test minting, burning, transfers, and balance tracking to ensure token economics work correctly under all conditions. 2. **Access Control Testing**: Verify that privileged functions can only be called by authorized accounts and that unauthorized access attempts fail properly. 3. **Edge Case Coverage**: Test boundary conditions like zero amounts, maximum values, empty collections, and invalid inputs. 4. **Failure Scenario Testing**: Use `#[expected_failure]` to verify that functions abort correctly when given invalid inputs or when preconditions aren't met. 5. **Upgrade Compatibility**: Test that upgraded modules maintain backward compatibility with existing on-chain state and don't break existing functionality. 6. **Integration Testing**: Test interactions between multiple modules to verify that complex workflows operate correctly end-to-end. ## Best Practices **Test Both Success and Failure**: Write tests for both happy paths and error conditions. Use `#[expected_failure]` to verify error handling. **Use Descriptive Test Names**: Name tests clearly to indicate what they're testing (e.g., `test_transfer_insufficient_balance_fails`). **Keep Tests Independent**: Each test should set up its own state and not depend on execution order or state from other tests. **Test Edge Cases**: Include tests for boundary values, empty inputs, maximum values, and unusual but valid scenarios. **Use Test-Only Code**: Mark helper functions and modules with `#[test_only]` to prevent them from being included in production builds. **Deterministic Testing**: Avoid randomness or time-dependent logic in tests to ensure reproducibility. **Coverage Goals**: Aim for comprehensive coverage of all public functions and critical internal logic paths. ## Running Tests ```bash # Run all tests in package aptos move test --package-dir . # Run tests with coverage aptos move test --package-dir . --coverage # Run specific test aptos move test --package-dir . --filter test_transfer # Run tests with gas profiling aptos move test --package-dir . --gas # Verbose output aptos move test --package-dir . --verbose ``` ## Advanced Testing Patterns ```move // Property-based testing pattern #[test] fun test_add_commutative() { let values = vector[1, 5, 10, 50, 100, 1000]; let i = 0; while (i < vector::length(&values)) { let j = 0; while (j < vector::length(&values)) { let a = *vector::borrow(&values, i); let b = *vector::borrow(&values, j); assert!(add(a, b) == add(b, a), 0); j = j + 1; }; i = i + 1; } } // State machine testing #[test(account = @0x1)] fun test_state_transitions(account: &signer) acquires StateMachine { initialize(account); assert!(get_state(@0x1) == STATE_INITIAL, 0); transition_to_active(account); assert!(get_state(@0x1) == STATE_ACTIVE, 0); transition_to_complete(account); assert!(get_state(@0x1) == STATE_COMPLETE, 0); } ``` ## Related Concepts - [Formal Verification](/aptos/formal_verification) - Mathematical proofs of correctness - [Module Structure](/aptos/module_structure) - Organize code for testability - [Resource Management](/aptos/resource_management) - Test resource lifecycle - [View Functions](/aptos/view_functions) - Test read-only operations --- ## upgradability # Upgradability Smart contract upgradability is a critical feature on Aptos that allows developers to fix bugs, add features, and improve performance while maintaining the same on-chain address. Move's upgrade system provides powerful flexibility with built-in safety checks to prevent breaking changes that could corrupt existing on-chain state or break dependent contracts. ## Overview On Aptos, modules can be upgraded by publishing new versions to the same address. The blockchain enforces compatibility rules to ensure that upgrades don't break existing functionality or corrupt stored data. Upgrades can be configured with different policies ranging from fully immutable (no upgrades allowed) to arbitrary (any changes permitted), with compatibility checks as the recommended middle ground. ## Upgrade Policies Aptos supports three upgrade policies that control what changes are permitted: ```move // In Move.toml or via CLI [package] name = "MyProject" version = "1.0.0" upgrade_policy = "compatible" // Options: immutable, compatible, arbitrary ``` **Immutable**: Once published, the module cannot be upgraded. This provides maximum security and predictability but eliminates flexibility to fix bugs or add features. **Compatible** (Recommended): Upgrades must maintain backward compatibility. Public functions, struct layouts, and type signatures cannot change in breaking ways, but you can add new functions and internal improvements. **Arbitrary**: Any changes are permitted including breaking changes to public APIs and struct layouts. Use with extreme caution as this can corrupt on-chain data. ## Compatibility Rules When using the compatible upgrade policy, the following rules apply: ### Allowed Changes - Adding new functions (public, entry, or internal) - Adding new structs and types - Adding new fields to structs (with care) - Modifying internal function implementations - Improving gas efficiency - Adding new modules to the package ### Prohibited Changes - Removing public functions - Changing public function signatures (parameters or return types) - Removing or reordering existing struct fields - Changing struct abilities (key, store, copy, drop) - Removing or renaming modules - Changing friend declarations that break existing integrations ## Upgrade Process ```bash # 1. Prepare the upgraded module # Edit your Move code with compatible changes # 2. Test the upgrade locally aptos move test --package-dir . # 3. Compile with upgrade check aptos move compile --package-dir . --save-metadata # 4. Deploy the upgrade aptos move publish \ --package-dir . \ --named-addresses my_project=0xYOUR_ADDRESS \ --profile mainnet # 5. Verify the upgrade aptos move view \ --function-id 0xYOUR_ADDRESS::module::version \ --profile mainnet ``` ## Version Management Implement version tracking in your modules: ```move module 0x1::upgradeable_contract { use std::signer; const VERSION: u64 = 2; // Increment with each upgrade struct Config has key { version: u64, admin: address, // Other config fields } public entry fun initialize(account: &signer) { move_to(account, Config { version: VERSION, admin: signer::address_of(account) }); } // Migration function for upgrades public entry fun migrate(admin: &signer) acquires Config { let config = borrow_global_mut(signer::address_of(admin)); assert!(config.version < VERSION, 1); // Already migrated // Perform migration logic if (config.version == 1) { // Migrate from v1 to v2 config.version = VERSION; }; } #[view] public fun get_version(addr: address): u64 acquires Config { borrow_global(addr).version } } ``` ## Safe Struct Evolution When adding fields to structs, ensure backward compatibility: ```move // Version 1 struct UserProfile has key { name: vector, created_at: u64 } // Version 2 - Safe addition with default handling struct UserProfile has key { name: vector, created_at: u64, avatar_url: Option> // Use Option for new fields } // Migration helper public fun migrate_profile(user: &signer) acquires UserProfile { let profile = borrow_global_mut(signer::address_of(user)); // Existing profiles automatically get None for new optional field } ``` ## Real-World Use Cases 1. **Bug Fixes**: Quickly patch security vulnerabilities or logical errors in deployed contracts without changing addresses or disrupting users. 2. **Feature Additions**: Add new functionality to existing protocols like new token types, additional governance mechanisms, or enhanced analytics. 3. **Performance Optimization**: Upgrade contract implementations to use more efficient algorithms or data structures while maintaining the same external interface. 4. **Parameter Tuning**: Adjust economic parameters, fee structures, or limits in DeFi protocols based on real-world usage and market conditions. 5. **Emergency Responses**: Implement circuit breakers, pause functionality, or other emergency measures when security issues are discovered. 6. **Protocol Evolution**: Gradually evolve complex protocols like DEXes or lending platforms by adding new features while maintaining backward compatibility with existing integrations. ## Best Practices **Always Use Compatible Mode**: Unless you have specific requirements, use the compatible upgrade policy to balance flexibility with safety. **Version All Modules**: Include version constants in all modules and expose them through view functions for transparency and debugging. **Test Upgrades Thoroughly**: Test upgraded modules against existing on-chain state before deploying to mainnet. Use testnet to validate migration paths. **Implement Migration Functions**: Provide explicit migration functions for users to upgrade their stored data when struct layouts change. **Document Breaking Changes**: Even when using arbitrary mode, clearly document all changes and provide migration guides for users and integrators. **Use Multi-Sig for Upgrades**: Require multiple signatures for upgrade transactions on production contracts to prevent unauthorized or accidental upgrades. **Gradual Rollout**: For major upgrades, consider implementing feature flags that allow gradual activation after deployment. **Preserve Historical Versions**: Keep records of all deployed versions with their code and deployment transactions for audit and recovery purposes. ## Package Manager Pattern For complex upgrades, consider implementing a package manager: ```move module 0x1::package_manager { struct PackageMetadata has key { name: vector, version: u64, upgrade_number: u64, upgrade_policy: u8, source_digest: vector } public entry fun record_upgrade( publisher: &signer, version: u64, digest: vector ) acquires PackageMetadata { let addr = signer::address_of(publisher); if (!exists(addr)) { move_to(publisher, PackageMetadata { name: b"MyPackage", version, upgrade_number: 0, upgrade_policy: 1, // compatible source_digest: digest }); } else { let metadata = borrow_global_mut(addr); metadata.version = version; metadata.upgrade_number = metadata.upgrade_number + 1; metadata.source_digest = digest; }; } } ``` ## Related Concepts - [Module Structure](/aptos/module_structure) - Design modules for upgradability - [Resource Management](/aptos/resource_management) - Handle resource migration - [Testing](/aptos/testing) - Test upgrade scenarios - [Formal Verification](/aptos/formal_verification) - Verify upgrade safety properties --- ## view_functions # View Functions View functions provide gas-free read access to on-chain state, enabling applications to query smart contract data without submitting transactions or paying fees. They are essential for building responsive user interfaces, analytics dashboards, and efficient off-chain systems that need to read blockchain state frequently. ## Overview View functions in Aptos are special functions marked with the `#[view]` attribute that can be called through the REST API without creating a transaction. They are read-only, cannot modify state, and execute immediately without waiting for block confirmation. This makes them perfect for displaying balances, checking permissions, computing derived values, and providing real-time data to applications. ## Defining View Functions View functions must be public and marked with the `#[view]` attribute: ```move module 0x1::token_info { use std::signer; use std::string::String; struct TokenStore has key { balance: u64, name: String, symbol: String, decimals: u8 } struct Supply has key { total: u64, max: u64 } // Simple view function #[view] public fun balance_of(owner: address): u64 acquires TokenStore { if (!exists(owner)) { return 0 }; borrow_global(owner).balance } // View function with multiple parameters #[view] public fun allowance(owner: address, spender: address): u64 acquires Allowances { // Return approved amount for spender 0 } // View function returning multiple values #[view] public fun token_metadata(addr: address): (String, String, u8) acquires TokenStore { let store = borrow_global(addr); (store.name, store.symbol, store.decimals) } // View function with computation #[view] public fun circulating_supply(): u64 acquires Supply { let supply = borrow_global(@0x1); supply.total } // View function checking conditions #[view] public fun is_paused(): bool acquires Config { borrow_global(@0x1).paused } // View function with vector return #[view] public fun get_holders(start: u64, limit: u64): vector
acquires HolderRegistry { // Return list of token holders vector::empty() } } ``` ## Calling View Functions ### REST API View functions are called via HTTP POST to the `/v1/view` endpoint: ```bash curl -X POST https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/view \ -H "Content-Type: application/json" \ -d '{ "function": "0x1::token_info::balance_of", "type_arguments": [], "arguments": ["0x123abc..."] }' ``` Response: ```json { "result": ["1000000"] } ``` ### TypeScript SDK ```typescript const config = new AptosConfig({ network: Network.MAINNET, fullnode: "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1" }); const aptos = new Aptos(config); // Call view function const balance = await aptos.view({ payload: { function: "0x1::token_info::balance_of", typeArguments: [], functionArguments: ["0x123abc..."] } }); console.log(`Balance: ${balance[0]}`); // Call view function with multiple returns const [name, symbol, decimals] = await aptos.view({ payload: { function: "0x1::token_info::token_metadata", typeArguments: [], functionArguments: ["0x1"] } }); ``` ### Python SDK ```python from aptos_sdk.client import RestClient from aptos_sdk.account_address import AccountAddress client = RestClient("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1") # Call view function balance = client.view_function( function="0x1::token_info::balance_of", type_arguments=[], arguments=["0x123abc..."] ) print(f"Balance: {balance[0]}") ``` ## Complex View Functions ### Aggregating Data ```move #[view] public fun get_portfolio_value(owner: address): u64 acquires TokenStore, PriceOracle { let total_value = 0u64; let store = borrow_global(owner); let price = get_token_price(); // Internal helper total_value = store.balance * price / 1000000; // Adjust for decimals total_value } #[view] public fun get_top_holders(limit: u64): vector
acquires HolderRegistry { // Query and sort holders by balance // Return top N addresses vector::empty() } ``` ### Pagination Support ```move #[view] public fun get_transactions( account: address, offset: u64, limit: u64 ): vector acquires TransactionHistory { let history = borrow_global(account); // Return paginated results vector::empty() } ``` ## Real-World Use Cases 1. **Wallet Displays**: Fetch token balances, NFT collections, and transaction history to display in user wallets without gas costs. 2. **DeFi Dashboards**: Query liquidity pool reserves, staking rewards, lending positions, and APY calculations for real-time financial data. 3. **NFT Marketplaces**: Check NFT ownership, metadata, listing prices, and royalty information to populate marketplace listings efficiently. 4. **Analytics Platforms**: Aggregate protocol metrics like total value locked, trading volumes, user counts, and historical statistics. 5. **Gaming Applications**: Retrieve player stats, inventory items, leaderboard positions, and game state without requiring transactions. 6. **Permission Checks**: Verify user access rights, admin privileges, or whitelist status before displaying UI elements or allowing actions. ## Best Practices **Keep Computations Light**: View functions execute during API calls, so avoid expensive computations. Consider pre-computing values in transaction functions and storing them. **Return Meaningful Defaults**: Use defensive programming to return sensible defaults (like 0 for balances) when resources don't exist, avoiding errors in calling code. **Use Pagination**: For functions returning large datasets, implement offset and limit parameters to prevent timeouts and excessive response sizes. **Cache Results**: On the application side, cache view function results when appropriate to reduce API calls and improve performance. **Validate Inputs**: Check that addresses and parameters are valid to provide better error messages than internal assertion failures. **Document Return Types**: Clearly document what each view function returns, especially when returning multiple values or complex structures. **Consider Gas Limits**: While view functions don't charge gas, they still have execution limits. Very complex computations may timeout. ## View Functions vs Entry Functions ```move // Entry function - Modifies state, requires transaction public entry fun transfer(from: &signer, to: address, amount: u64) acquires TokenStore { // Mutates state let from_store = borrow_global_mut(signer::address_of(from)); from_store.balance = from_store.balance - amount; // ... } // View function - Read-only, no transaction needed #[view] public fun balance_of(owner: address): u64 acquires TokenStore { // Only reads state borrow_global(owner).balance } ``` ## Error Handling ```move #[view] public fun safe_balance_of(owner: address): u64 acquires TokenStore { // Handle non-existent resources gracefully if (!exists(owner)) { return 0 }; let store = borrow_global(owner); store.balance } #[view] public fun get_allowance_or_max( owner: address, spender: address ): u64 acquires Allowances { if (!exists(owner)) { return 0xFFFFFFFFFFFFFFFF // Return max u64 if no allowance set }; // Return actual allowance 0 } ``` ## Performance Considerations View functions execute on fullnodes during API requests, so optimize for speed: - Minimize the number of `borrow_global` calls - Avoid nested loops with large iterations - Use early returns to skip unnecessary computation - Pre-compute complex values in transaction functions when possible - Consider implementing summary resources for expensive aggregations ## Related Concepts - [Module Structure](/aptos/module_structure) - Organize view functions effectively - [Resource Management](/aptos/resource_management) - Read resources safely - [Testing](/aptos/testing) - Test view function logic - [GraphQL API](/aptos/graphql_overview) - Alternative querying approach --- ## accounts_get ## Overview Returns core account information (sequence number and authentication key) for a given address. ## Endpoint `GET /v1/accounts/{address}` ## Aptos-Specific Notes - Accounts are resources; sequence numbers are required for building transactions. - Addresses are 0x-prefixed hex strings; leading zeros are accepted. ## Request ### Path Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | address | string | Yes | Account address (e.g., `0x1`) | ### Query Parameters None. ### Request Body None. ## Response ### Success Response (200) ``` { "sequence_number": "string", "authentication_key": "string" } ``` ### Error Responses | Status | Error Code | Description | | -- | -- | -- | | 400 | invalid_input | Invalid address format | | 404 | account_not_found | Account doesn't exist | | 500 | internal_error | Server error | ## Code Examples ``` curl -X GET https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1 \ -H "Accept: application/json" ``` SDK ``` from aptos_sdk.client import RestClient client = RestClient("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1") account = client.account("0x1") ``` ``` const aptos = new Aptos(new AptosConfig({ network: Network.MAINNET, fullnode: "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1" })); const account = await aptos.getAccountInfo({ accountAddress: "0x1" }); ``` ``` use aptos_sdk::rest_client::Client; let client = Client::new("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1".parse()?); let account = client.get_account("0x1").await?; ``` ## Common Use Cases - Checking account existence before transactions - Retrieving authentication keys for verification - Getting sequence numbers for transaction building ## Related Endpoints - accounts_resources - Get account resources - accounts_modules - Get account modules --- ## accounts_module ## Overview Fetch a specific Move module published under an account by module name. ## Endpoint `GET /v1/accounts/{address}/module/{module_name}` ## Request ### Path Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | address | string | Yes | Account address | | module_name | string | Yes | Module name (no address prefix) | ## Code Examples ``` curl -X GET https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/module/aptos_account \ -H "Accept: application/json" ``` ``` module = client.account_module("0x1", "aptos_account") ``` ``` const m = await aptos.getAccountModule({ accountAddress: "0x1", moduleName: "aptos_account" }); ``` ``` let m = client.get_account_module("0x1", "aptos_account").await?; ``` ## Response ### Success Response (200) Returns a Move module object containing: ```json { "bytecode": "0xa11ceb0b060000000...", "abi": { "address": "0x1", "name": "aptos_account", "friends": [], "exposed_functions": [...], "structs": [...] } } ``` The ABI includes complete type information, function signatures, and struct definitions for the module. ### Error Responses | Status | Error Code | Description | | -- | -- | -- | | 400 | invalid_input | Invalid address or module name format | | 404 | module_not_found | Module doesn't exist at this address | | 404 | account_not_found | Account doesn't exist | ## Use Cases This endpoint is essential for several blockchain development workflows: 1. **Smart Contract Verification**: Verify the bytecode and ABI of deployed modules to ensure they match expected implementations before interacting with them. 2. **ABI Discovery**: Retrieve complete type information and function signatures for integration with wallets, dapps, or SDKs without requiring the original Move source code. 3. **Upgrade Auditing**: Compare module versions across different ledger versions to track changes and validate upgrade compatibility rules. 4. **Development Tools**: IDE plugins and debugging tools use this endpoint to provide autocomplete, type checking, and inline documentation for on-chain modules. 5. **Security Analysis**: Security researchers analyze deployed module bytecode to identify potential vulnerabilities or verify formal verification properties. 6. **Cross-Contract Integration**: Before calling functions in another module, applications can inspect the ABI to ensure compatibility and understand input/output types. ## Best Practices **Module Name Format**: The module name parameter should not include the address prefix. Use `aptos_account` not `0x1::aptos_account`. **Caching Strategy**: Module bytecode rarely changes. Implement client-side caching with ledger version as the cache key to minimize API calls. Only refetch when you detect a module upgrade event. **ABI Type Resolution**: When parsing generic types in the ABI, ensure your client handles nested generics like `CoinStore` correctly. Use the full type path for disambiguation. **Version Pinning**: For production applications, consider querying modules at specific ledger versions rather than always using the latest state. This provides deterministic behavior even during network upgrades. **Error Handling**: A 404 response could mean either the account doesn't exist or the module doesn't exist at that account. Check the error message to distinguish these cases. ## Performance Considerations Module queries are relatively lightweight operations. The response size depends on module complexity - simple modules return a few KB, while complex framework modules may return 100KB+ of bytecode and ABI data. If you only need specific information from the ABI, consider parsing it client-side and caching the relevant portions. The REST API serves modules from the node's storage layer with minimal processing overhead. Response times are typically under 100ms for hot data. --- ## accounts_modules ## Overview Returns all Move modules published by an account. ## Endpoint `GET /v1/accounts/{address}/modules` ## Aptos-Specific Notes - Use for on-chain ABI discovery and upgrade audits. ## Request ### Path Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | address | string | Yes | Account address | ### Query Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | ledger_version | string | No | Historical version read | ### Request Body None. ## Response ``` [ { "bytecode": "0x...", "abi": { "name": "my_module" } } ] ``` ## Code Examples ``` curl -X GET https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/modules \ -H "Accept: application/json" ``` ``` modules = client.account_modules("0x1") ``` ``` const modules = await aptos.getAccountModules({ accountAddress: "0x1" }); ``` ``` let modules = client.get_account_modules("0x1").await?; ``` ## Related Endpoints - accounts_module - Get a single module by name --- ## accounts_resource ## Overview Fetch a specific resource under an account by its full type string. ## Endpoint `GET /v1/accounts/{address}/resource/{resource_type}` ## Aptos-Specific Notes - Encode generic types using fully qualified type strings. ## Request ### Path Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | address | string | Yes | Account address | | resource_type | string | Yes | Type tag, e.g. `0x1::dkg::DKGState` | ### Query Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | ledger_version | string | No | Historical version read | ### Request Body None. ## Response ``` { "type": "0x1::dkg::DKGState", "data": { "coin": { "value": "123" } } } ``` ## Code Examples ``` curl -X GET https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/resource/0x1::dkg::DKGState \ -H "Accept: application/json" ``` ``` resource = client.account_resource( "0x1", "0x1::dkg::DKGState" ) ``` ``` const r = await aptos.getAccountResource({ accountAddress: "0x1", resourceType: "0x1::dkg::DKGState", }); ``` ``` let r = client.get_account_resource("0x1", "0x1::dkg::DKGState").await?; ``` --- ## accounts_resources ## Overview Lists all Move resources stored under an account. Useful to discover balances, capabilities, and custom module data. ## Endpoint `GET /v1/accounts/{address}/resources` ## Aptos-Specific Notes - Resource types follow `address::module::Struct<...>`. - Large accounts may have many resources; use pagination parameters if present. ## Request ### Path Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | address | string | Yes | Account address (e.g., `0x1`) | ### Query Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | ledger_version | string | No | Read at a historical version | | limit | integer | No | Max number of resources to return | | start | string | No | Cursor for pagination | ### Request Body None. ## Response ### Success Response (200) ``` [ { "type": "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>", "data": { "coin": { "value": "123" } } } ] ``` ### Error Responses | Status | Error Code | Description | | -- | -- | -- | | 400 | invalid_input | Invalid address format | | 404 | account_not_found | Account doesn't exist | ## Code Examples ``` curl -X GET https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/resources?limit=100 \ -H "Accept: application/json" \ -H "Accept: application/json" ``` SDK ``` from aptos_sdk.client import RestClient client = RestClient("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1") resources = client.account_resources("0x1") ``` ``` const aptos = new Aptos(new AptosConfig({ network: Network.MAINNET, fullnode: "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1" })); const resources = await aptos.getAccountResources({ accountAddress: "0x1" }); ``` ``` use aptos_sdk::rest_client::Client; let client = Client::new("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1".parse()?); let resources = client.get_account_resources_bcs("0x1").await?; ``` ## Common Use Cases - Token balances (CoinStore, FA) - Capability checks - Reading application state ## Related Endpoints - accounts_resource - Get a single resource type --- ## accounts_transactions ## Overview Returns transactions where the account is the sender. Useful for pagination and activity feeds. ## Endpoint `GET /v1/accounts/{address}/transactions` ## Request ### Path Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | address | string | Yes | Sender address | ### Query Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | start | string | No | Starting version (cursor) | | limit | integer | No | Page size | ## Code Examples ``` curl -X GET https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/transactions?limit=25 \ -H "Accept: application/json" ``` ``` txns = client.get_account_transactions("0x1", params={"limit": 25}) ``` ``` const txns = await aptos.getAccountTransactions({ accountAddress: "0x1", limit: 25 }); ``` ``` let txns = client.get_account_transactions("0x1", None).await?; ``` --- ## blocks_by_height ## Overview Fetch a block by its height. Includes transactions and block metadata. ## Endpoint `GET /v1/blocks/by_height/{block_height}` ## Request ### Path Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | block_height | string | Yes | Block height | ### Query Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | with_transactions | boolean | No | Include transactions in response | ## Code Examples ``` curl -X GET https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/blocks/by_height/1000000?with_transactions=true \ -H "Accept: application/json" ``` ``` b = client.block_by_height(1000000, with_transactions=True) ``` ``` const b = await aptos.getBlockByHeight({ blockHeight: 1_000_000n, withTransactions: true }); ``` ``` let b = client.get_block_by_height(1_000_000, true).await?; ``` --- ## blocks_by_version ## Overview Fetch the block that contains a given ledger version. This endpoint is useful when you have a transaction version and need to understand its block context, including block metadata, timestamp, and related transactions. ## Endpoint `GET /v1/blocks/by_version/{version}` ## Request ### Path Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | version | string | Yes | Ledger version (transaction version) | ### Query Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | with_transactions | boolean | No | Include full transaction data in response | ## Response ### Success Response (200) Returns a block object containing: ```json { "block_height": "1000000", "block_hash": "0x...", "block_timestamp": "1234567890", "first_version": "123456700", "last_version": "123456789", "transactions": [...] } ``` When `with_transactions=true`, the transactions array contains complete transaction objects. Without this parameter, only block metadata is returned. ### Error Responses | Status | Error Code | Description | | -- | -- | -- | | 400 | invalid_input | Invalid version format | | 404 | version_not_found | Version doesn't exist yet | | 500 | internal_error | Server error | ## Code Examples ```bash curl -X GET https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/blocks/by_version/123456789?with_transactions=true \ -H "Accept: application/json" ``` ## Use Cases This endpoint serves several important purposes in blockchain development: 1. **Transaction Context Discovery**: Given a specific transaction version, retrieve its block context to understand when and how it was processed, including block timestamp and proposer information. 2. **Block Explorer Implementation**: Build block explorers that allow users to navigate from individual transactions to their containing blocks, showing all transactions processed together. 3. **Temporal Analysis**: Analyze transaction ordering and timing within blocks to understand MEV opportunities, transaction dependencies, or validator behavior. 4. **Event Correlation**: When investigating events across multiple transactions, use this endpoint to group related transactions that were executed in the same block. 5. **Audit Trail Construction**: Create comprehensive audit trails by linking transactions to their block context, providing immutable timestamps and ordering guarantees. 6. **State Snapshot Coordination**: Coordinate state snapshots across multiple accounts or resources by identifying block boundaries that represent consistent global state. ## Best Practices **Version vs Height**: This endpoint uses transaction version (ledger version), not block height. Transaction versions are sequential across all transactions, while block heights increment per block. Use `blocks/by_height` if you have a block height instead. **Pagination Strategy**: When `with_transactions=true`, large blocks can return megabytes of data. If you need to process many blocks, consider fetching metadata first, then selectively fetching transaction details only when needed. **Caching**: Block data is immutable once finalized. Implement aggressive caching for historical blocks (older than 100 versions from chain head) to minimize API load. **Version Boundaries**: Each block contains a range of versions from `first_version` to `last_version`. To process all transactions in a block, iterate through this range using individual transaction queries if needed. ## Performance Considerations Queries without `with_transactions` are fast and lightweight (typically under 50ms). Including full transaction data can increase response time to 200-500ms for blocks with many transactions, depending on transaction complexity and payload sizes. The response size can range from a few KB (metadata only) to several MB (large blocks with full transaction data). For high-throughput applications processing many blocks sequentially, consider using the transaction streaming API instead of polling individual blocks. --- ## estimate_gas_price ## Overview Retrieve current gas price estimates for Aptos transactions. This endpoint provides three tiers of gas pricing to help applications choose appropriate fees based on urgency: prioritized (fast), standard, and deprioritized (economy). ## Endpoint `GET /v1/estimate_gas_price` ## Request ### Path Parameters None. ### Query Parameters None. ### Request Body None. ## Response ### Success Response (200) Returns gas price estimates in octas (1 APT = 100,000,000 octas): ```json { "prioritized_gas_estimate": "150", "gas_estimate": "100", "deprioritized_gas_estimate": "50" } ``` **Field Descriptions**: - `prioritized_gas_estimate`: Higher gas price for faster inclusion, typically processed within 1-2 blocks - `gas_estimate`: Standard gas price for normal transaction speed, typically processed within 2-5 blocks - `deprioritized_gas_estimate`: Lower gas price for cost-sensitive, non-urgent transactions, may take longer to process All values are returned as string-encoded integers representing gas units in octas. ### Error Responses | Status | Error Code | Description | | -- | -- | -- | | 500 | internal_error | Server error estimating gas | | 503 | service_unavailable | Gas estimation temporarily unavailable | ## Code Examples ```bash curl -X GET https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/estimate_gas_price \ -H "Accept: application/json" ``` Python example with SDK: ```python from aptos_sdk.client import RestClient client = RestClient("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1") gas_estimates = client.estimate_gas_price() print(f"Standard gas price: {gas_estimates['gas_estimate']} octas") ``` TypeScript example: ```typescript const response = await fetch( "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/estimate_gas_price", { headers: { "Accept": "application/json" } } ); const estimates = await response.json(); console.log(`Prioritized: ${estimates.prioritized_gas_estimate} octas`); ``` ## Use Cases This endpoint is critical for building responsive and cost-effective applications: 1. **Dynamic Transaction Fee Setting**: Automatically adjust transaction gas prices based on current network conditions rather than using hardcoded values, ensuring reliable execution without overpaying. 2. **User Experience Optimization**: Offer users multiple speed/cost options (fast/normal/economy) by exposing the three gas tier estimates, similar to modern blockchain wallets. 3. **Batch Operation Cost Planning**: Estimate total costs for batch operations by multiplying gas estimates by expected gas consumption, helping optimize transaction batching strategies. 4. **Gas Price Monitoring**: Track gas price trends over time to identify network congestion patterns and schedule non-urgent operations during low-fee periods. 5. **Multi-Chain Cost Comparison**: Compare Aptos gas costs with other blockchains to provide users with informed decisions about which chain to use for specific operations. 6. **Smart Contract Budgeting**: Applications with gas sponsorship or limited budgets can use deprioritized estimates to maximize transaction throughput within budget constraints. ## Best Practices **Query Frequency**: Gas prices on Aptos are relatively stable compared to other chains due to the Block-STM parallel execution model. Query every 30-60 seconds for normal applications, or more frequently during known high-traffic events. **Price Selection Logic**: For user-initiated transactions, use the standard estimate. For urgent operations like liquidations or MEV, use prioritized. For background tasks or gas-sponsored operations, use deprioritized. **Safety Margins**: Add a 10-20% buffer to estimates to account for price fluctuations between estimation and submission, especially for prioritized transactions during volatile periods. **Transaction Expiration**: Set appropriate expiration timestamps (typically 60-120 seconds) that match your gas tier choice. Prioritized transactions should have shorter expirations, while deprioritized can be longer. **Error Recovery**: If gas estimation fails (500/503 errors), fall back to conservative hardcoded values. For mainnet, safe fallback values are: prioritized=200, standard=100, deprioritized=100 octas per gas unit. ## Performance Considerations This endpoint is extremely lightweight and typically responds in under 20ms. The estimates are calculated based on recent block gas usage and mempool analysis, updated every block (approximately every 4 seconds on mainnet). Gas estimates reflect the minimum gas unit price needed for inclusion, but actual transaction costs depend on gas consumption (max_gas_amount × gas_unit_price). A simple transfer might consume 5-10 gas units, while complex smart contract interactions can consume thousands. For reference, at 100 octas per gas unit, a simple APT transfer costs approximately 0.00001 APT (1000 gas units × 100 octas), making Aptos one of the most cost-effective layer-1 blockchains. --- ## events_by_creation_number ## Overview Retrieve events from a specific event stream identified by its creation number. Each event handle has a unique creation number that identifies the event stream at a particular account. This is the legacy event querying mechanism, useful for working with older contracts and event handles. ## Endpoint `GET /v1/accounts/{address}/events/{creation_number}` ## Request ### Path Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | address | string | Yes | Account address that owns the event stream | | creation_number | string | Yes | Event stream creation number (integer as string) | ### Query Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | start | string | No | Starting sequence number for pagination | | limit | integer | No | Maximum number of events to return (default: 25, max: 1000) | ## Response ### Success Response (200) Returns an array of event objects: ```json [ { "version": "123456789", "guid": { "creation_number": "0", "account_address": "0x1" }, "sequence_number": "42", "type": "0x1::coin::WithdrawEvent", "data": { "amount": "1000000" } } ] ``` Each event includes: - `version`: Ledger version when the event was emitted - `guid`: Globally unique identifier for the event stream - `sequence_number`: Sequential number within this event stream - `type`: Full Move type of the event payload - `data`: The structured event payload ### Error Responses | Status | Error Code | Description | | -- | -- | -- | | 400 | invalid_input | Invalid address or creation number format | | 404 | resource_not_found | Event stream doesn't exist | | 404 | account_not_found | Account doesn't exist | ## Code Examples ```bash curl -X GET https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/events/0?limit=10 \ -H "Accept: application/json" ``` Python example: ```python from aptos_sdk.client import RestClient client = RestClient("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1") events = client.account_events_by_creation_number("0x1", "0", start=None, limit=10) for event in events: print(f"Event at version {event['version']}: {event['type']}") ``` TypeScript example: ```typescript const response = await fetch( "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/events/0?limit=10", { headers: { "Accept": "application/json" } } ); const events = await response.json(); ``` ## Use Cases This endpoint serves several important purposes for event-driven applications: 1. **Legacy Contract Integration**: Query events from older contracts that use the legacy event handle system (pre-0x1::event::EventHandle model) without requiring contract upgrades. 2. **Event Stream Monitoring**: Monitor specific event streams for particular activities, such as tracking all coin withdrawal events from the treasury account. 3. **Historical Event Analysis**: Paginate through historical events to analyze patterns, aggregate statistics, or reconstruct state changes over time. 4. **Audit Trail Construction**: Build comprehensive audit logs by retrieving all events emitted by critical system accounts in chronological order. 5. **Notification Systems**: Implement real-time notification systems that poll for new events from specific handles and trigger webhooks or alerts. 6. **State Reconstruction**: Recreate account or module state by replaying events in sequence, useful for debugging or validation purposes. ## Best Practices **Creation Number Discovery**: Creation numbers are not easily discoverable without inspecting account resources first. Use the `accounts/{address}/resources` endpoint to find event handles with their creation numbers. **Pagination Strategy**: Start with `limit=1000` to minimize API calls for bulk historical retrieval. Use the last event's `sequence_number + 1` as the next `start` parameter for pagination. **Sequence Numbers**: Event sequence numbers within a stream are guaranteed to be sequential with no gaps. Missing sequence numbers indicate data synchronization issues. **Version Ordering**: While sequence numbers order events within a stream, use the `version` field to establish ordering across different event streams or accounts. **Legacy vs Modern**: For new contracts, prefer the modern event system using `0x1::event::emit()`. This endpoint primarily supports legacy code and backwards compatibility. **Rate Limiting**: Avoid polling this endpoint too frequently. For real-time needs, consider polling every 5-10 seconds or use the GraphQL indexer with subscriptions when available. ## Performance Considerations Event queries are efficient for reasonable ranges. Fetching 100 events typically completes in 50-100ms. However, requesting the maximum 1000 events can take 200-500ms depending on event payload sizes. Events are stored in chronological order, making forward pagination (increasing sequence numbers) faster than reverse traversal. The creation number index provides O(1) lookup to the event stream, but scanning requires sequential I/O. For applications requiring comprehensive event analysis across multiple accounts or event types, the GraphQL indexer provides more efficient bulk querying capabilities with complex filtering and aggregation support. --- ## events_by_handle ## Endpoint `GET /v1/accounts/{address}/events/{event_handle}/{field_name}` ## Request ### Path Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | address | string | Yes | Account address | | event_handle | string | Yes | Struct type with events | | field_name | string | Yes | Field in the struct producing events | ### Query Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | start | string | No | Starting sequence | | limit | integer | No | Page size | ## Response ### Success Response (200) Returns an array of event objects from the specified handle: ```json [ { "version": "123456789", "guid": { "creation_number": "3", "account_address": "0x1" }, "sequence_number": "5", "type": "0x1::account::CoinRegisterEvent", "data": { "type_info": { "account_address": "0x1", "module_name": "aptos_coin", "struct_name": "AptosCoin" } } } ] ``` ### Error Responses | Status | Error Code | Description | | -- | -- | -- | | 400 | invalid_input | Invalid address, handle, or field name format | | 404 | resource_not_found | Event handle or field doesn't exist | | 404 | account_not_found | Account doesn't exist | ## Code Examples ```bash curl -X GET "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/events/0x1::account::Account/coin_register_events?limit=5" \ -H "Accept: application/json" ``` Python example: ```python from aptos_sdk.client import RestClient client = RestClient("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1") events = client.account_events_by_event_handle( "0x1", "0x1::account::Account", "coin_register_events", limit=5 ) ``` TypeScript example: ```typescript const events = await aptos.getEventsByEventHandle({ accountAddress: "0x1", eventHandleStruct: "0x1::account::Account", fieldName: "coin_register_events", minimumLedgerVersion: 0, options: { limit: 5 } }); ``` ## Use Cases This endpoint enables powerful event-driven architecture patterns: 1. **Contract Event Monitoring**: Monitor specific event types emitted by smart contracts, such as tracking all token transfer events or NFT mint events from a marketplace contract. 2. **User Activity Tracking**: Build user activity feeds by querying events from user-controlled resources, showing transaction history and state changes. 3. **Cross-Contract Analytics**: Aggregate events across multiple contracts or accounts to analyze ecosystem-wide trends, such as total trading volume or user adoption metrics. 4. **Real-Time Notifications**: Poll event handles to detect new events and trigger notifications, webhooks, or automated responses for critical contract activities. 5. **State Verification**: Verify that expected state changes occurred by checking for corresponding events, useful for transaction confirmation UIs. 6. **Debugging and Testing**: During development, inspect event emissions to validate contract behavior and ensure events are emitted with correct data. ## Best Practices **Event Handle Structure**: The event handle path follows the pattern `address::module::Struct/field_name`. The struct must contain an `EventHandle` field with the specified name. **Type Information**: Always inspect the returned `type` field to understand the event payload structure. Event types are strongly typed in Move and the type string indicates the exact Move struct emitted. **Pagination**: For event streams with many events, use pagination with the `start` parameter set to the last seen `sequence_number + 1` to avoid missing events or duplicates. **Polling Frequency**: Poll at reasonable intervals (5-30 seconds) based on your use case. Too frequent polling wastes resources, while too infrequent polling may delay notifications. **Handle Discovery**: Find available event handles by querying account resources and inspecting struct fields of type `EventHandle`. The ABI from module queries shows event handle field names. ## Performance Considerations Event queries by handle are optimized with indexed lookups, typically completing in 50-150ms for reasonable limits. Response times increase with larger limit values and complex event payload structures. This method is more efficient than querying by creation number when you know the specific contract and field name, as it avoids resource enumeration overhead. However, for bulk event analysis across many handles, consider using the GraphQL indexer for better query flexibility and performance. --- ## healthy ## Overview Check the health and availability of the Aptos REST API node. This endpoint returns HTTP 200 when the node is operational and synced, making it ideal for monitoring, load balancing, and automated health checks in production environments. ## Endpoint `GET /v1/-/healthy` ## Request ### Path Parameters None. ### Query Parameters None. ### Request Body None. ## Response ### Success Response (200) Returns HTTP 200 with an empty or minimal response body when the node is healthy and ready to serve requests. The node is considered healthy when: - The REST API service is running and responsive - The underlying node is syncing or fully synced with the network - Database connections are operational - Critical system resources are available ### Error Responses | Status | Error Code | Description | | -- | -- | -- | | 503 | service_unavailable | Node is unhealthy, not synced, or starting up | | 500 | internal_error | Critical error preventing normal operation | Any non-200 response indicates the node should not receive production traffic. ## Code Examples Shell script for monitoring: ```bash curl -s -X GET -o /dev/null -w "%{http_code}\n" https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/-/healthy -H "Accept: application/json" ``` Python monitoring script: ```python def is_node_healthy(api_key): try: response = requests.get( f"https://api-aptos-mainnet.n.dwellir.com/{api_key}/v1/-/healthy", timeout=5 ) return response.status_code == 200 except requests.exceptions.RequestException: return False if is_node_healthy("YOUR_API_KEY"): print("Node is healthy") else: print("Node is unhealthy") ``` TypeScript health check: ```typescript async function checkNodeHealth(apiKey: string): Promise { try { const response = await fetch( `https://api-aptos-mainnet.n.dwellir.com/${apiKey}/v1/-/healthy`, { signal: AbortSignal.timeout(5000) } ); return response.status === 200; } catch (error) { return false; } } ``` Docker healthcheck in docker-compose.yml: ```yaml services: app: healthcheck: test: ["CMD", "curl", "-f", "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/-/healthy"] interval: 30s timeout: 10s retries: 3 start_period: 40s ``` ## Use Cases This endpoint is essential for production infrastructure: 1. **Load Balancer Health Checks**: Configure load balancers (AWS ALB, nginx, HAProxy) to use this endpoint for backend health checks, automatically routing traffic away from unhealthy nodes. 2. **Kubernetes Readiness Probes**: Set up Kubernetes readiness and liveness probes to ensure pods are only marked ready when the Aptos node is fully synced and operational. 3. **Monitoring and Alerting**: Integrate with monitoring systems (Prometheus, Datadog, New Relic) to track node availability and trigger alerts when health checks fail. 4. **Automated Failover**: Build high-availability systems that automatically switch to backup API endpoints when the primary node becomes unhealthy. 5. **CI/CD Pipeline Gates**: Use health checks in deployment pipelines to verify services are operational before promoting to production or completing rolling updates. 6. **Service Discovery**: Register nodes with service discovery systems (Consul, etcd) and use health checks to maintain an accurate registry of available endpoints. ## Best Practices **Timeout Configuration**: Set reasonable timeouts (3-5 seconds) for health check requests. If a node doesn't respond quickly, it's likely unhealthy and shouldn't serve traffic. **Check Frequency**: Balance between responsiveness and load. For critical services, check every 10-30 seconds. For monitoring dashboards, 60 seconds is typically sufficient. **Retry Logic**: Implement exponential backoff for retries. Don't immediately mark a node as unhealthy on a single failed check - wait for 2-3 consecutive failures. **Circuit Breaker Pattern**: After detecting an unhealthy node, implement a circuit breaker that waits before rechecking. Avoid overwhelming an unhealthy node with continuous health checks. **Multiple Nodes**: Never rely on a single node. Always maintain connections to multiple API endpoints and use health checks to select healthy ones dynamically. **Logging**: Log health check failures with timestamps and status codes for troubleshooting and capacity planning. ## Performance Considerations Health check requests are extremely lightweight and typically complete in under 20ms. They don't touch the blockchain state layer - the node simply reports its operational status. However, health checks do consume API rate limits and network resources. Avoid checking more frequently than every 5-10 seconds to prevent unnecessary load on shared infrastructure. For Dwellir's managed API infrastructure, health checks are already performed internally at the load balancer level. The health endpoint is exposed primarily for client-side monitoring and verification purposes. ## Integration with Other Endpoints Combine health checks with the `/v1` (ledger_info) endpoint for more detailed node status: - `/v1/-/healthy` - Quick operational check (< 20ms) - `/v1` - Detailed sync status with version information (50-100ms) Use `/healthy` for rapid health verification, then query `/v1` for diagnostic information if health checks start failing. --- ## ledger_info ## Endpoint `GET /v1` ## Response ``` { "chain_id": 1, "epoch": "string", "ledger_version": "string", "oldest_ledger_version": "string", "ledger_timestamp": "string", "block_height": "string", "oldest_block_height": "string", "node_role": "fullnode|validator|..." } ``` ## Code Examples ```bash curl -X GET https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1 \ -H "Accept: application/json" ``` Python example: ```python from aptos_sdk.client import RestClient client = RestClient("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1") ledger_info = client.info() print(f"Chain ID: {ledger_info['chain_id']}") print(f"Latest version: {ledger_info['ledger_version']}") print(f"Block height: {ledger_info['block_height']}") ``` TypeScript example: ```typescript const config = new AptosConfig({ fullnode: "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1" }); const aptos = new Aptos(config); const ledgerInfo = await aptos.getLedgerInfo(); console.log(`Epoch: ${ledgerInfo.epoch}, Version: ${ledgerInfo.ledger_version}`); ``` ## Use Cases This endpoint serves as the foundation for many blockchain operations: 1. **Transaction Building**: Retrieve the current ledger version and chain ID, both required for constructing valid transactions. The chain ID prevents replay attacks across different networks. 2. **Sync Status Verification**: Monitor the node's sync progress by comparing `ledger_version` against known network heights. Essential for ensuring your node or API provider is fully synced before executing critical operations. 3. **Historical Query Planning**: Use `oldest_ledger_version` and `oldest_block_height` to determine the available historical data range. Queries before these values will fail. 4. **Block Explorer Navigation**: Power block explorers with current height and version information, enabling users to navigate to the latest blocks and transactions. 5. **Time-Based Queries**: Convert between block times and versions using `ledger_timestamp`. Useful for retrieving state at specific historical moments. 6. **Network Health Monitoring**: Track `epoch` changes and `ledger_timestamp` progression to monitor network health and validator set transitions. ## Best Practices **Caching Strategy**: Ledger info changes every block (approximately every 4 seconds on mainnet). Cache this data for 2-5 seconds to minimize API calls while maintaining reasonable freshness. **Chain ID Validation**: Always verify the `chain_id` matches your expected network (1 for mainnet, 2 for testnet). This prevents accidental cross-network transaction submissions. **Version Management**: When building transactions, fetch fresh ledger info to get the latest version. Stale version data can cause transaction expiration issues. **Historical Data Awareness**: Check `oldest_ledger_version` before attempting historical queries. Nodes prune old data, and querying beyond the oldest version returns errors. **Timestamp Precision**: The `ledger_timestamp` is in microseconds since Unix epoch. Convert appropriately for your application's time handling. ## Performance Considerations This endpoint is highly optimized and typically responds in 20-50ms. It queries metadata from the node's fast-access cache layer without touching the transaction database or blockchain state. Response size is minimal (under 1KB), making it suitable for frequent polling. However, for applications requiring real-time updates, consider polling every 5-10 seconds rather than every block to balance freshness with API efficiency. The `node_role` field indicates whether you're querying a validator or fullnode. Validators have the most up-to-date data but are rarely exposed publicly. Fullnodes (like Dwellir's API) lag by a few seconds but provide stable, scalable access. ## Related Endpoints - `/v1/-/healthy` - Quick health check without detailed info - `/v1/blocks/by_height/{height}` - Fetch specific block data - `/v1/transactions` - Query recent transactions --- ## spec ## Overview Retrieve the complete OpenAPI 3.0 specification for the Aptos REST API. This machine-readable document describes all available endpoints, request/response schemas, parameters, and error codes, enabling automated client generation and API exploration. ## Endpoint `GET /v1/spec` ## Request ### Path Parameters None. ### Query Parameters None. ### Request Body None. ## Response ### Success Response (200) Returns a complete OpenAPI 3.0 specification document in JSON or YAML format (depending on Accept header): ```json { "openapi": "3.0.0", "info": { "title": "Aptos REST API", "version": "1.0.0" }, "paths": { "/accounts/{address}": {...}, "/transactions": {...} }, "components": { "schemas": {...} } } ``` The specification includes complete type definitions for all Move-related structures, transaction payloads, and response formats. ## Code Examples ```bash curl -X GET https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/spec \ -H "Accept: application/json" ``` Save specification to file: ```bash curl -X GET https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/spec \ -H "Accept: application/json" \ -o aptos-openapi.json ``` ## Use Cases The OpenAPI specification enables various development workflows: 1. **Client SDK Generation**: Generate type-safe API clients in any language using tools like OpenAPI Generator, Swagger Codegen, or language-specific generators. This eliminates manual API integration work and reduces errors. 2. **API Documentation**: Import the spec into API documentation tools like Swagger UI, Redoc, or Postman to create interactive documentation with request/response examples and try-it-out functionality. 3. **Contract Testing**: Use the specification to generate contract tests that validate API responses match expected schemas, catching breaking changes early. 4. **Mock Server Creation**: Generate mock API servers for frontend development and testing without depending on live blockchain infrastructure. 5. **IDE Integration**: Import specifications into REST clients (Insomnia, Postman) or IDE plugins (JetBrains HTTP Client, VSCode REST Client) for autocomplete and validation. 6. **API Change Tracking**: Compare specifications across versions to identify breaking changes, deprecated endpoints, or new functionality in API updates. ## Best Practices **Version Pinning**: The specification matches the API version of the node you're querying. For production applications, pin to a specific specification version and test thoroughly before upgrading. **Client Generation**: When generating clients, configure the generator to handle Aptos-specific patterns like string-encoded large numbers (u64, u128) and 0x-prefixed addresses. **Schema Validation**: Use the schemas from the specification to validate responses client-side, catching unexpected API changes or data corruption early. **Type Customization**: Many OpenAPI generators support custom templates. Customize generated code to integrate with your existing type systems or add blockchain-specific validations. **Caching**: The specification is relatively static. Cache it locally during development rather than fetching on every build. Update when you detect API version changes. **Format Selection**: Request JSON format (default) for programmatic use. YAML format is more human-readable for manual review but requires appropriate Accept header. ## Performance Considerations The specification document is large (typically 500KB-2MB) and rarely changes. Download once and cache locally for client generation and development purposes. This endpoint doesn't touch blockchain state - it serves a static or infrequently-updated document describing the API surface. Response times are typically under 100ms, primarily limited by document transfer time. Avoid fetching the specification at application runtime. Instead, generate clients during build time and ship compiled code to production. ## Integration with Development Tools **OpenAPI Generator**: ```bash openapi-generator generate \ -i https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/spec \ -g typescript-fetch \ -o ./generated/aptos-client ``` **Swagger UI**: ```javascript const ui = SwaggerUI({ url: "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/spec", dom_id: '#swagger-ui' }); ``` **Postman Import**: Download the spec and import directly into Postman to create a complete request collection with pre-configured endpoints and parameters. ## Related Resources - Aptos TypeScript SDK uses this specification as basis for type definitions - Official Aptos OpenAPI spec repository on GitHub - OpenAPI 3.0 specification documentation at swagger.io --- ## tables_item ## Endpoint `POST /v1/tables/{table_handle}/item` ## Request ### Path Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | table_handle | string | Yes | Table handle address | ### Request Body ``` { "key_type": "address", "value_type": "u128", "key": "0x619dc29a0aac8fa146714058e8dd6d2d0f3bdf5f6331907bf91f3acd81e6935" } ``` ## Response ### Success Response (200) Returns the value from the table, decoded according to the specified `value_type`: ```json "1234567890" ``` For simple types like `u128`, the response is a string-encoded number. For struct types, the response is a JSON object with the struct's fields. ### Error Responses | Status | Error Code | Description | | -- | -- | -- | | 400 | invalid_input | Invalid table handle, key type, value type, or key format | | 404 | table_item_not_found | Key doesn't exist in table | | 404 | table_not_found | Table handle doesn't exist | ## Code Examples > **Tip:** The handle `0x1b854694ae746cdbd8d44186ca4929b2b337df21d1c74633be19b2710552fdca` references the on-chain coin conversion map. The key shown here is the BCS-encoded metadata address for Aptos Coin, and the returned `u128` value is the circulating supply in octas. ```bash curl -s -X POST "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/tables/0x1b854694ae746cdbd8d44186ca4929b2b337df21d1c74633be19b2710552fdca/item" \ -H "Content-Type: application/json" \ -d '{"key_type":"address","value_type":"u128","key":"0x619dc29a0aac8fa146714058e8dd6d2d0f3bdf5f6331907bf91f3acd81e6935"}' ``` Python example: ```python response = requests.post( "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/tables/{handle}/item", json={ "key_type": "address", "value_type": "u128", "key": "0x1" } ) value = response.json() ``` TypeScript example: ```typescript const response = await aptos.getTableItem({ handle: "0x1b854...", data: { key_type: "address", value_type: "u128", key: "0x1" } }); ``` ## Use Cases Table queries are essential for accessing Aptos's on-chain data structures: 1. **Supply Tracking**: Query coin supply tables to retrieve current circulation, maximum supply, and minting statistics for fungible assets and coins. 2. **Configuration Lookups**: Access on-chain configuration tables for protocol parameters, fee structures, and governance settings without parsing raw resources. 3. **Mapping Queries**: Retrieve values from key-value mappings stored in Move tables, such as user balances, token ownership, or application-specific data. 4. **State Verification**: Verify specific state values in smart contracts by directly querying table items rather than fetching and parsing entire resources. 5. **Indexer Alternatives**: For simple lookups, table queries can be more efficient than setting up GraphQL indexers or processing full resource data. 6. **Analytics Queries**: Build analytics dashboards by querying statistical tables maintained by on-chain protocols. ## Best Practices **Type Accuracy**: Ensure `key_type` and `value_type` exactly match the table's Move type definitions. Type mismatches cause deserialization errors. **Key Encoding**: Keys must be properly BCS-encoded. For addresses, use the full 0x-prefixed 64-character hex string. For complex types, use BCS serialization libraries. **Handle Discovery**: Table handles are not easily discoverable. They're typically stored in resource fields of type `Table`. Query the resource first to extract the handle. **404 Handling**: A 404 can mean either the table doesn't exist or the key doesn't exist in the table. Check the error message to distinguish these cases. **Ledger Version**: Use the optional `ledger_version` query parameter to query tables at historical points in time for time-series analysis or state reconstruction. ## Performance Considerations Table item queries are optimized with indexed lookups, typically completing in 50-150ms. Performance depends on key complexity and value size. Simple numeric keys and values are fastest. Tables are implemented using a Merkle tree structure, providing O(log n) lookup time. However, the constant factors are low enough that even tables with millions of entries respond quickly. For bulk queries across many keys, consider whether querying the entire resource and parsing it client-side might be more efficient than multiple table queries. --- ## tables_raw_item ## Endpoint `POST /v1/tables/{table_handle}/raw_item` ## Request Body ``` { "key": { "addr": "0x1" }, "key_type": "vector", "value_type": "vector" } ``` ## Response ### Success Response (200) Returns the raw BCS-encoded bytes as a hex string: ```json { "bytes": "0x0123456789abcdef..." } ``` The bytes must be decoded using BCS deserialization based on the specified `value_type`. ### Error Responses | Status | Error Code | Description | | -- | -- | -- | | 400 | invalid_input | Invalid table handle, types, or key | | 404 | table_item_not_found | Key doesn't exist | | 404 | table_not_found | Table doesn't exist | ## Code Examples ```bash curl -s -X POST "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/tables/0xabc/raw_item" \ -H "Content-Type: application/json" \ -d '{"key_type":"vector","value_type":"vector","key":"0x00"}' ``` Python example with BCS decoding: ```python from aptos_sdk import bcs response = requests.post( "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/tables/{handle}/raw_item", json={"key_type": "address", "value_type": "u64", "key": "0x1"} ) raw_bytes = bytes.fromhex(response.json()['bytes'][2:]) # Remove 0x prefix value = bcs.deserialize(raw_bytes, bcs.uint64) ``` ## Use Cases Raw table queries serve specialized use cases requiring direct BCS access: 1. **Custom Deserialization**: Deserialize complex or custom Move types that aren't supported by the standard JSON API, using language-specific BCS libraries. 2. **Performance Optimization**: For high-throughput applications, BCS deserialization can be faster than JSON parsing, especially for numeric-heavy data. 3. **Type Flexibility**: Query tables without knowing the exact Move type structure, then decode based on discovered schemas or partial type information. 4. **Cross-Language Compatibility**: BCS is the canonical serialization format for Move. Use raw bytes for interoperability between different SDK implementations. 5. **Verification and Hashing**: Compute cryptographic hashes or signatures over the exact on-chain bytes without JSON encoding ambiguities. 6. **Low-Level Debugging**: Inspect raw serialization format to debug encoding issues or verify data integrity. ## Best Practices **BCS Knowledge Required**: This endpoint requires deep understanding of BCS serialization and Move type layouts. Use the standard `/tables/{handle}/item` endpoint unless you have specific needs for raw bytes. **Type Specification**: While you must specify `value_type`, the returned bytes are not validated against this type. It's your responsibility to ensure correct deserialization. **SDK Support**: Use BCS libraries from official SDKs (aptos-sdk for Python, @aptos-labs/ts-sdk for TypeScript) rather than implementing BCS deserialization yourself. **Hex Encoding**: Response bytes are 0x-prefixed hex strings. Strip the prefix before converting to byte arrays in most languages. **Performance Trade-offs**: While BCS deserialization can be faster, the overhead of HTTP requests typically dominates. Only use raw queries if you're batch-processing many items. ## Performance Considerations Performance characteristics are identical to the standard table item endpoint. The difference is purely in response format - JSON vs raw bytes. Response times are typically 50-150ms. For applications processing millions of table items, the reduced parsing overhead of BCS can save 10-30% CPU time compared to JSON deserialization, but network I/O remains the bottleneck. --- ## transactions_batch ## Overview Submit multiple signed transactions in a single API call for improved throughput and reduced latency. Batch submission is ideal for applications that need to submit many transactions quickly, such as airdrops, batch payments, or high-frequency trading operations. ## Endpoint `POST /v1/transactions/batch` ## Request ###Request Body Array of signed transaction objects: ```json [ { "sender": "0x...", "sequence_number": "1", "max_gas_amount": "2000", "gas_unit_price": "100", "expiration_timestamp_secs": "1234567890", "payload": { "type": "entry_function_payload", "function": "0x1::aptos_account::transfer", "type_arguments": ["0x1::aptos_coin::AptosCoin"], "arguments": ["0x2", "1000"] }, "signature": {...} } ] ``` ## Response ### Success Response (202) Returns array of transaction hashes or failure details: ```json { "transaction_failures": [] } ``` Individual transactions may fail while others succeed. Check response details for each transaction status. ### Error Responses | Status | Error Code | Description | | -- | -- | -- | | 400 | invalid_input | Malformed batch or transaction objects | | 413 | payload_too_large | Batch exceeds size limits | ## Code Examples ```bash curl -s -X POST "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/transactions/batch" \ -H "Content-Type: application/json" \ -d '[{"sender":"0x...","payload":{"type":"entry_function_payload","function":"0x1::aptos_account::transfer","type_arguments":["0x1::aptos_coin::AptosCoin"],"arguments":["0x2","1000"]}}]' ``` Python batch submission: ```python transactions = [build_transaction(recipient) for recipient in recipients] response = client.submit_batch_transactions(transactions) ``` ## Use Cases Batch submission provides significant advantages for several scenarios: 1. **Airdrops**: Distribute tokens to hundreds or thousands of addresses efficiently by batching transfer transactions. 2. **Payroll Systems**: Process employee payments or rewards in bulk with a single API interaction. 3. **DEX Operations**: Submit multiple swap or liquidity provision transactions together for atomic execution or improved throughput. 4. **NFT Minting**: Batch mint operations for collections, reducing API overhead and improving deployment speed. 5. **Gaming Rewards**: Distribute in-game rewards or achievements to multiple players efficiently. 6. **Multi-Account Operations**: Execute operations across multiple accounts you control with coordinated submission. ## Best Practices **Batch Size**: Keep batches under 100 transactions for optimal performance and reliability. Larger batches risk timeouts or partial failures. **Sequence Number Management**: Ensure sequence numbers are correct and contiguous for transactions from the same sender. Gaps or duplicates cause failures. **Gas Settings**: Set realistic gas limits for each transaction. One under-gased transaction doesn't affect others. **Error Handling**: Implement retry logic for failed transactions within a batch. Successful transactions won't be resubmitted. **Atomicity**: Batch submission doesn't guarantee atomic execution. Transactions execute independently and some may fail while others succeed. **Rate Limits**: Batching counts toward API rate limits based on total transaction count, not API calls. ## Performance Considerations Batch submission reduces HTTP overhead from N requests to 1 request for N transactions. This provides 5-10x throughput improvement for large batches compared to individual submission. Processing time scales with batch size: 100 transactions typically process in 200-500ms total versus 10-30 seconds for individual submissions. However, batched transactions still enter the mempool individually and execute in separate blocks based on gas price and network conditions. --- ## transactions_by_hash ## Overview Retrieve a transaction by its unique hash. This is the primary method for looking up transactions when users provide transaction IDs, typically after submission or from block explorers. ## Endpoint `GET /v1/transactions/by_hash/{txn_hash}` ## Request ### Path Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | txn_hash | string | Yes | 0x-prefixed transaction hash (64 hex characters) | ### Query Parameters None. ## Response ### Success Response (200) Returns a complete transaction object including execution results: ```json { "version": "123456789", "hash": "0x0985b017...", "state_change_hash": "0x...", "event_root_hash": "0x...", "gas_used": "8", "success": true, "vm_status": "Executed successfully", "sender": "0xabc...", "sequence_number": "42", "payload": {...}, "events": [...], "timestamp": "1234567890" } ``` ### Error Responses | Status | Error Code | Description | | -- | -- | -- | | 400 | invalid_input | Invalid hash format | | 404 | transaction_not_found | Transaction doesn't exist or pending | ## Code Examples ```bash curl -X GET https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/transactions/by_hash/0x0985b0179db0c0971bb9bf331dff7fdae6dacf73cee48a1ec6be614f41d4d383 \ -H "Accept: application/json" ``` Python example: ```python from aptos_sdk.client import RestClient client = RestClient("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1") txn = client.transaction_by_hash("0x0985b017...") print(f"Success: {txn['success']}, Gas: {txn['gas_used']}") ``` TypeScript example: ```typescript const txn = await aptos.getTransactionByHash({ transactionHash: "0x0985b017..." }); console.log(`Status: ${txn.vm_status}`); ``` ## Use Cases Transaction hash lookups are fundamental to blockchain applications: 1. **Transaction Confirmation**: After submitting a transaction, poll by hash to check execution status and confirm success or failure. 2. **Receipt Generation**: Retrieve full transaction details including events, gas usage, and state changes to generate user-facing receipts. 3. **Block Explorer Links**: Enable users to click transaction hashes in your UI and view complete transaction details. 4. **Debugging Failed Transactions**: When transactions fail, retrieve the full transaction object to inspect `vm_status` and understand why execution failed. 5. **Event Processing**: Extract emitted events from specific transactions to update application state or trigger notifications. 6. **Audit Logging**: Store transaction hashes in your database, then retrieve full details on-demand for audit trails without storing complete transaction data. ## Best Practices **Hash Format**: Transaction hashes must be 0x-prefixed 64-character hex strings (32 bytes). Validate format before querying to avoid 400 errors. **Pending Transactions**: Newly submitted transactions return 404 until they're executed and committed. Use `/transactions/wait_by_hash` for blocking behavior. **Caching**: Transaction data is immutable once committed. Cache successfully retrieved transactions indefinitely to minimize API calls. **Sequence vs Hash**: If you know the transaction version (sequence number in the global ledger), use `/transactions/by_version` for faster lookups. **Error Interpretation**: Check both `success` and `vm_status` fields. A transaction can execute (`success: false`) but fail application-level checks. ## Performance Considerations Hash lookups use indexed storage and typically complete in 50-100ms. This is slightly slower than version-based lookups because hash indexes are secondary indexes. Transaction objects can be large (10KB-1MB) depending on payload size, number of events, and state changes. Complex smart contract interactions generate larger responses. For bulk transaction retrieval, consider using version-based queries or the transaction list endpoint with pagination instead of individual hash lookups. --- ## transactions_by_version ## Overview Retrieve a transaction by its ledger version number. This is the fastest way to query transactions when you know the version, which is assigned sequentially to every transaction on the blockchain. Versions provide a total ordering of all state changes in Aptos. ## Endpoint `GET /v1/transactions/by_version/{txn_version}` ## Request ### Path Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | txn_version | string | Yes | Ledger version number (non-negative integer as string) | ### Query Parameters None. ## Response ### Success Response (200) Returns a complete transaction object: ```json { "version": "123456789", "hash": "0x...", "state_change_hash": "0x...", "event_root_hash": "0x...", "gas_used": "8", "success": true, "vm_status": "Executed successfully", "sender": "0x...", "sequence_number": "42", "max_gas_amount": "2000", "gas_unit_price": "100", "expiration_timestamp_secs": "1234567890", "payload": {...}, "signature": {...}, "events": [...], "timestamp": "1234567890" } ``` ### Error Responses | Status | Error Code | Description | | -- | -- | -- | | 400 | invalid_input | Invalid version format (must be non-negative integer) | | 404 | transaction_not_found | Version doesn't exist yet or is before oldest_ledger_version | ## Code Examples ```bash curl -X GET https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/transactions/by_version/123456789 \ -H "Accept: application/json" ``` Python example: ```python from aptos_sdk.client import RestClient client = RestClient("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1") txn = client.transaction_by_version(123456789) print(f"Hash: {txn['hash']}, Sender: {txn['sender']}") ``` TypeScript example: ```typescript const txn = await aptos.getTransactionByVersion({ ledgerVersion: 123456789n }); console.log(`Gas used: ${txn.gas_used}`); ``` ## Use Cases Version-based transaction queries are essential for many blockchain operations: 1. **Sequential Processing**: Iterate through all transactions sequentially by incrementing version numbers, ensuring no transactions are missed during indexing or analysis. 2. **Event Stream Processing**: Process transactions in order from a known checkpoint version, maintaining consistent state reconstruction. 3. **Block Processing**: After retrieving a block with its version range (`first_version` to `last_version`), fetch individual transactions within that range. 4. **Historical Analysis**: Access transactions at specific points in blockchain history using version numbers as stable references. 5. **State Snapshots**: Reconstruct state at any historical version by replaying all transactions up to that version. 6. **Performance Optimization**: Version lookups are faster than hash lookups because versions are the primary index for transaction storage. ## Best Practices **Version Range Awareness**: Check `/v1` (ledger_info) to get `oldest_ledger_version` and `ledger_version` to understand the available version range. Queries outside this range will fail. **Sequential Access Patterns**: When processing many sequential transactions, version-based queries are significantly more efficient than hash-based queries due to better database locality. **Pagination**: For bulk processing, use the `/v1/transactions` endpoint with pagination instead of individual version queries. **Version vs Hash**: Use version queries when you have version numbers (from blocks, event streams, or sequential processing). Use hash queries when users provide transaction IDs. **Immutability**: Transaction data at a specific version is immutable. Implement aggressive caching for historical versions (older than latest - 100) to minimize API load. **Error Handling**: A 404 can mean the version is too new (not yet processed) or too old (pruned). Compare against ledger_info to distinguish these cases. ## Performance Considerations Version-based lookups are the fastest transaction query method, typically completing in 30-80ms. They use the primary index on transaction storage, providing optimal I/O patterns. Response sizes match other transaction queries (10KB-1MB depending on transaction complexity). However, the reduced query latency makes version-based access preferred for high-throughput indexing pipelines. For sequential processing of large version ranges, consider using the transaction streaming API which provides better throughput than individual REST queries. ## Version Number Properties Transaction versions have important properties: - Globally unique across the entire blockchain - Monotonically increasing with no gaps - Assigned sequentially in block order - Starts at version 0 (genesis transaction) - Each block contains a contiguous range of versions These properties make versions ideal for streaming, checkpointing, and state machine replication use cases. --- ## transactions_encode ## Endpoint `POST /v1/transactions/encode_submission` ## Request Body ``` { "sender": "0x..", "sequence_number": "..", "payload": { "type": "entry_function_payload", "function": "0x1::aptos_account::transfer", "type_arguments": ["0x1::aptos_coin::AptosCoin"], "arguments": ["0x2","1000"] } } ``` ## Response ### Success Response (200) Returns the BCS-encoded transaction bytes as a hex string: ```json { "encoded": "0xb5e97db07fa0bd0e5598aa3643a9bc6f6693bddc1a9fec9e674a461eaa00b193..." } ``` These bytes can be signed and submitted without additional encoding. ### Error Responses | Status | Error Code | Description | | -- | -- | -- | | 400 | invalid_input | Invalid transaction format or missing required fields | | 400 | invalid_payload | Payload doesn't conform to entry function or script requirements | ## Code Examples ```bash curl -s -X POST "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/transactions/encode_submission" \ -H "Content-Type: application/json" \ -d '{"sender":"0x...","sequence_number":"1","payload":{"type":"entry_function_payload","function":"0x1::aptos_account::transfer","type_arguments":["0x1::aptos_coin::AptosCoin"],"arguments":["0x2","1000"]}}' ``` Python workflow: ```python from aptos_sdk.client import RestClient from aptos_sdk.account import Account client = RestClient("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1") account = Account.load_key("private_key_hex") # Build transaction raw_txn = {...} # Transaction object encoded = client.encode_submission(raw_txn) # Sign encoded bytes signature = account.sign(bytes.fromhex(encoded['encoded'][2:])) # Submit signed transaction client.submit_transaction({...}) ``` ## Use Cases Transaction encoding serves several important purposes: 1. **Offline Signing**: Encode transactions on an online machine, transfer encoded bytes to an air-gapped signing device, then return signatures for submission without exposing private keys to networked systems. 2. **Hardware Wallet Integration**: Send encoded transaction bytes to hardware wallets (Ledger, Trezor) for signing, maintaining security while using blockchain APIs. 3. **Multi-Step Workflows**: Separate transaction construction, approval, signing, and submission into distinct steps, useful for organizational approval processes. 4. **Cross-Platform Signing**: Encode on one platform (web API) and sign on another (mobile app, desktop wallet) without requiring full SDK on both sides. 5. **Transaction Inspection**: Encode transactions to get their exact on-chain representation before signing, useful for verification and auditing. 6. **Gas Estimation**: Generate encoded transactions for simulation to accurately estimate gas costs before actual signing and submission. ## Best Practices **Complete Transaction Fields**: Include all required fields: sender, sequence_number, max_gas_amount, gas_unit_price, expiration_timestamp_secs, payload, and chain_id. Missing fields cause encoding failures. **Sequence Number Management**: Fetch the latest sequence number from `/v1/accounts/{address}` immediately before encoding to avoid conflicts with concurrent transactions. **Expiration Timestamps**: Set expiration_timestamp_secs to current time + 60-120 seconds. Too short causes timing issues, too long delays failure detection. **Chain ID Verification**: Always verify chain_id matches your target network (1 for mainnet, 2 for testnet) to prevent cross-network replay attacks. **Encoding Validation**: After encoding, optionally decode the bytes client-side to verify correctness before sending to signing devices. **Byte Handling**: The returned hex string is 0x-prefixed. Remove prefix before converting to byte arrays for signing in most programming languages. ## Performance Considerations Encoding is a fast, pure computational operation without blockchain state access. Response times are typically 20-50ms, dominated by network latency rather than encoding overhead. Encoded transaction sizes vary: - Simple transfers: ~100-200 bytes - Smart contract calls: 300-1000 bytes - Complex multi-agent transactions: 1-5KB These sizes are negligible for modern networks but matter for hardware wallet display limitations and QR code encoding use cases. ## Security Considerations Encoding itself doesn't involve cryptographic keys or sensitive data. However, the encoded bytes represent a transaction ready for signing. Ensure encoded transactions are transmitted securely to signing devices and not modified in transit, as any tampering would cause signature verification failures. For maximum security, verify the transaction contents (recipient, amount, function being called) on the signing device's display before approving signatures. --- ## transactions_list ## Endpoint `GET /v1/transactions` ## Query Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | start | string | No | Starting version | | limit | integer | No | Page size | ## Response ### Success Response (200) Returns an array of transaction objects ordered by version: ```json [ { "version": "123456789", "hash": "0x...", "sender": "0x...", "success": true, "vm_status": "Executed successfully", "gas_used": "8", "payload": {...}, "events": [...], "timestamp": "1234567890" } ] ``` ### Error Responses | Status | Error Code | Description | | -- | -- | -- | | 400 | invalid_input | Invalid start version or limit value | ## Code Examples ```bash curl -X GET https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/transactions?limit=25 \ -H "Accept: application/json" ``` Python pagination example: ```python from aptos_sdk.client import RestClient client = RestClient("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1") start_version = 0 limit = 100 while True: txns = client.transactions(start=start_version, limit=limit) if not txns: break for txn in txns: process_transaction(txn) start_version = int(txns[-1]['version']) + 1 ``` TypeScript example: ```typescript const txns = await aptos.getTransactions({ options: { offset: 0, limit: 25 } }); console.log(`Fetched ${txns.length} transactions`); ``` ## Use Cases Transaction listing serves multiple critical purposes: 1. **Blockchain Explorers**: Display recent transactions on the homepage or activity feed, showing latest network activity to users. 2. **Indexing Pipelines**: Sequentially process all transactions from a starting point to build custom indexes, analytics, or application-specific databases. 3. **Activity Monitoring**: Poll recent transactions to monitor network activity, detect specific transaction patterns, or trigger alerts. 4. **Historical Analysis**: Retrieve historical transaction ranges for data analysis, research, or regulatory compliance requirements. 5. **State Reconstruction**: Replay transactions in order to reconstruct account or contract state at any point in history. 6. **Testing and Debugging**: Fetch recent transactions to understand network behavior during development and troubleshooting. ## Best Practices **Optimal Limit Values**: Use `limit=100-1000` for efficient bulk retrieval. Smaller limits require more API calls, larger limits may hit response size constraints. **Pagination Pattern**: Use the last transaction's `version + 1` as the next `start` parameter. Never rely on limit*page calculations as they miss concurrent transactions. **Rate Limiting**: When processing historical data, implement rate limiting (10-20 requests/second) to avoid overwhelming the API and hitting quota limits. **Cursor Persistence**: Save your current position (start version) frequently. If processing stops, resume from the last successfully processed version rather than restarting. **Empty Response Handling**: An empty array means you've reached the current head of the chain. Wait 5-10 seconds before polling again to allow new transactions to be processed. **Version Gaps**: Transactions are contiguous with no version gaps. If you encounter gaps, it indicates a processing error that needs investigation. ## Performance Considerations Transaction list queries are optimized for sequential access patterns. Fetching 100 transactions typically completes in 100-200ms. Response times scale linearly with limit up to the maximum of 1000 transactions. Total response size depends on transaction complexity: - Simple transfers: ~2KB per transaction - Smart contract calls: ~5-15KB per transaction - Complex multi-agent transactions: ~20-50KB per transaction For high-throughput processing, consider using the transaction streaming API which provides better performance than REST pagination for sequential access to large ranges. The default `limit` when not specified is typically 25 transactions. Always specify explicit limits for production code to ensure consistent behavior. ## Comparison with Streaming API For processing large ranges of transactions: - REST pagination: Simpler integration, works with any HTTP client, better for sporadic queries - Streaming API: Higher throughput (10-100x), lower latency, better for continuous synchronization Choose REST for ad-hoc queries and small ranges. Choose streaming for real-time tailing or bulk historical processing. --- ## transactions_simulate ## Overview Simulate transaction execution without committing changes to the blockchain. This endpoint executes transactions in a sandboxed environment, returning gas costs, execution results, and potential errors without consuming gas or affecting on-chain state. ## Endpoint `POST /v1/transactions/simulate` ## Request ### Request Body Submit a transaction object similar to `/transactions` submission, but signatures can be omitted or set to zero-filled placeholders: ```json { "sender": "0x...", "sequence_number": "42", "max_gas_amount": "2000", "gas_unit_price": "100", "expiration_timestamp_secs": "1234567890", "payload": { "type": "entry_function_payload", "function": "0x1::aptos_account::transfer", "type_arguments": ["0x1::aptos_coin::AptosCoin"], "arguments": ["0x2", "1000"] } } ``` ## Response ### Success Response (200) Returns simulation results showing what would happen if the transaction were executed: ```json { "version": "123456789", "hash": "0x...", "state_change_hash": "0x...", "event_root_hash": "0x...", "gas_used": "8", "success": true, "vm_status": "Executed successfully", "changes": [...], "events": [...], "timestamp": "1234567890" } ``` When `success: false`, inspect `vm_status` for the failure reason. ### Error Responses | Status | Error Code | Description | | -- | -- | -- | | 400 | invalid_input | Malformed transaction or payload | | 400 | simulation_failed | Transaction failed during simulation | ## Code Examples ```bash curl -s -X POST "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/transactions/simulate" \ -H "Content-Type: application/json" \ -d '{"sender":"0x...","payload":{"type":"entry_function_payload","function":"0x1::aptos_account::transfer","type_arguments":["0x1::aptos_coin::AptosCoin"],"arguments":["0x2","1000"]}}' ``` Python gas estimation: ```python from aptos_sdk.client import RestClient client = RestClient("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1") txn = {...} # Transaction object simulation = client.simulate_transaction(txn, sender_account) print(f"Estimated gas: {simulation[0]['gas_used']}") print(f"Will succeed: {simulation[0]['success']}") ``` TypeScript example: ```typescript const simulation = await aptos.transaction.simulate.simple({ signerPublicKey: account.publicKey, transaction: rawTxn }); console.log(`Gas estimate: ${simulation[0].gas_used}`); ``` ## Use Cases Transaction simulation is critical for building robust applications: 1. **Gas Estimation**: Accurately estimate gas costs before submission to set appropriate `max_gas_amount` and avoid under-provisioning that causes transaction failures. 2. **Pre-Flight Validation**: Verify transactions will succeed before asking users to sign, improving UX by catching errors early and preventing failed transaction costs. 3. **Complex Transaction Testing**: Test multi-step or conditional logic in smart contracts to ensure correct behavior before committing real transactions. 4. **Fee Display**: Show users estimated transaction fees before confirmation, enabling informed consent about transaction costs. 5. **Dry Runs**: Test transaction sequences (batch operations, DEX swaps, liquidations) to verify expected outcomes before execution. 6. **Error Debugging**: When developing smart contracts, simulate transactions to understand why they fail without spending gas on failed attempts. ## Best Practices **Realistic Parameters**: Use realistic `max_gas_amount` and `gas_unit_price` values for accurate simulation. The VM may behave differently with unrealistic limits. **Current State**: Simulations execute against current blockchain state. For time-sensitive operations, simulate immediately before submission as state can change rapidly. **Sequence Numbers**: Use the account's next sequence number from `/v1/accounts/{address}`. Incorrect sequence numbers cause simulation failures. **Signature Requirements**: Most simulations don't require valid signatures. Use zero-filled signature placeholders to avoid signing overhead. **Multiple Simulations**: Simulate variants (different gas limits, argument values) to understand transaction behavior under various conditions. **Expiration Handling**: Set expiration_timestamp_secs to a future time that matches intended submission time for accurate replay protection simulation. **State Changes Inspection**: Examine the `changes` array to understand what state modifications will occur, useful for verifying contract correctness. ## Performance Considerations Simulations execute the full transaction logic including Move VM execution, making them comparable in cost to actual execution. Response times typically range from 50-500ms depending on transaction complexity. Simple transfers simulate in 50-100ms, while complex smart contract interactions can take 200-500ms. Simulations are slightly faster than real execution because they skip consensus and signature verification. For batch gas estimation, simulate transactions in parallel using concurrent API requests rather than sequential simulation to minimize latency. ## Simulation vs Actual Execution Key differences between simulation and real execution: - No gas charges apply to simulations - State changes are rolled back after simulation - Simulations use current state, execution uses state at ledger version - Failed simulations don't increment account sequence numbers - Simulation results show hypothetical state changes that won't persist Use simulation for cost estimation and validation, but be aware that state changes between simulation and execution can cause different outcomes for state-dependent logic. --- ## transactions_submit ## Endpoint `POST /v1/transactions` ## Request Body ``` { "sender": "0x...", "sequence_number": "...", "max_gas_amount": "...", "gas_unit_price": "...", "expiration_timestamp_secs": "...", "payload": { "type": "entry_function_payload", "function": "0x1::aptos_account::transfer", "type_arguments": ["0x1::aptos_coin::AptosCoin"], "arguments": ["0x2", "1000"] }, "signature": { "type": "ed25519_signature", "public_key": "0x..", "signature": "0x.." } } ``` ## Success Response (202) Returns a pending transaction object: ``` { "hash": "0x...", "sender": "0x...", "sequence_number": "...", "gas_unit_price": "...", "max_gas_amount": "...", "expiration_timestamp_secs": "...", "payload": { ... } } ``` Use `GET /v1/transactions/wait_by_hash/{hash}` to wait for execution. ## Example ``` curl -s -X POST "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/transactions" \ -H "Content-Type: application/json" \ -d '{"sender":"0x...","sequence_number":"1","payload":{"type":"entry_function_payload","function":"0x1::aptos_account::transfer","type_arguments":["0x1::aptos_coin::AptosCoin"],"arguments":["0x2","1000"]}}' ``` --- ## transactions_wait_by_hash ## Endpoint `GET /v1/transactions/wait_by_hash/{txn_hash}` ## Query Parameters | Name | Type | Required | Description | |------|------|----------|-------------| | timeout_secs | integer | No | Max time to wait | ## Example > **Note:** Shared Dwellir fullnodes do not expose the blocking `/transactions/wait_by_hash` helper. The snippet below emulates the same behavior by polling `transactions/by_hash` until the transaction appears. ``` curl -X GET https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/transactions/wait_by_hash/0x0985b0179db0c0971bb9bf331dff7fdae6dacf73cee48a1ec6be614f41d4d383?timeout_secs=20 \ -H "Accept: application/json" ``` --- ## view ## Endpoint `POST /v1/view` ## Request Body ``` { "function": "0x1::coin::balance", "type_arguments": ["0x1::aptos_coin::AptosCoin"], "arguments": ["0x1"] } ``` ## Response ``` [ "0x... or value depending on function" ] ``` ## Code Examples ```bash curl -s -X POST "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/view" \ -H "Content-Type: application/json" \ -d '{"function":"0x1::coin::balance","type_arguments":["0x1::aptos_coin::AptosCoin"],"arguments":["0x1"]}' ``` Python example: ```python result = client.view_function( "0x1::coin::balance", ["0x1::aptos_coin::AptosCoin"], ["0x1"] ) print(f"Balance: {result[0]}") ``` TypeScript example: ```typescript const result = await aptos.view({ payload: { function: "0x1::coin::balance", typeArguments: ["0x1::aptos_coin::AptosCoin"], functionArguments: ["0x1"] } }); ``` ## Use Cases View functions enable efficient read-only blockchain queries: 1. **Balance Queries**: Check account balances without transaction overhead or gas costs. 2. **State Inspection**: Read contract state variables and computed values efficiently. 3. **Validation Checks**: Verify conditions before transaction submission to prevent failed transactions. 4. **UI Data Fetching**: Power application UIs with real-time blockchain data without polling full resources. 5. **Price Feeds**: Query DEX prices, oracle data, or computed values for display or trading logic. 6. **Permission Checks**: Verify user permissions or capabilities before allowing operations. ## Best Practices **Function Visibility**: Only functions marked `public fun` or `public entry fun` with `#[view]` attribute can be called via this endpoint. **Gas-Free**: View functions don't consume gas or require signatures, making them ideal for frequent queries. **Type Arguments**: Provide full type paths including generics for functions requiring type parameters. **Argument Encoding**: Arguments are passed as JSON values and automatically BCS-encoded by the API. **Caching**: View function results reflect current state. Cache appropriately based on how frequently the underlying state changes. **Ledger Version**: Optionally specify a ledger_version query parameter to query historical state at specific points in time. ## Performance Considerations View functions execute directly in the Move VM without consensus or state commitment overhead. Response times are typically 20-100ms depending on function complexity. Simple reads complete in 20-50ms, while complex computations may take 100-200ms. View functions are significantly faster than full transaction simulation for read operations. For frequently accessed data, consider implementing client-side caching with TTLs based on block time (4-5 seconds on mainnet). --- ## authentication > Coming soon: Need support for this? Email [support@dwellir.com](mailto:support@dwellir.com) if you want early access # Streaming Authentication Streaming API authentication provides secure access control for gRPC transaction streams, ensuring only authorized clients can subscribe to blockchain data feeds. Proper authentication is essential for production deployments, rate limiting, access control, and preventing unauthorized resource consumption. ## Overview The Aptos streaming service uses bearer token authentication negotiated during channel setup. This approach provides security without sacrificing performance, allowing long-lived streaming connections while maintaining proper access controls. Authentication tokens are validated once during connection establishment and remain valid for the duration of the stream. ## Authentication Methods ### Bearer Token Authentication ```typescript // Create metadata with API key const metadata = new Metadata(); metadata.add("authorization", `Bearer ${process.env.API_KEY}`); // Establish authenticated connection const client = new TransactionStreamClient( "stream.aptos.dwellir.com:443", credentials.createSsl(), { channelOverride: channel } ); // Use metadata in stream requests const stream = client.subscribe(request, metadata); ``` ### Mutual TLS (mTLS) For enterprise deployments, mTLS provides certificate-based authentication: ```typescript const rootCert = fs.readFileSync("ca-cert.pem"); const clientKey = fs.readFileSync("client-key.pem"); const clientCert = fs.readFileSync("client-cert.pem"); const sslCredentials = credentials.createSsl( rootCert, clientKey, clientCert ); const client = new TransactionStreamClient( "stream.aptos.dwellir.com:443", sslCredentials ); ``` ## Real-World Use Cases 1. **Production Services**: Secure streaming connections for production applications handling sensitive transaction data or serving multiple users. 2. **Multi-Tenant Systems**: Isolate stream access per customer using separate API keys with individual rate limits and quotas. 3. **Analytics Platforms**: Authenticate data ingestion pipelines that process blockchain streams for business intelligence and reporting. 4. **Trading Systems**: Secure real-time market data feeds for trading bots and algorithmic trading systems with guaranteed access. 5. **Compliance Monitoring**: Authenticate regulatory compliance systems that monitor transactions for suspicious activities or reporting requirements. 6. **Enterprise Infrastructure**: Integrate blockchain streams into corporate systems with certificate-based authentication and access controls. ## Best Practices **Rotate Keys Regularly**: Implement automated key rotation schedules to minimize exposure if credentials are compromised. **Use Environment Variables**: Never hard-code API keys or certificates - store them securely in environment variables or secrets management systems. **Implement Retry Logic**: Handle authentication failures gracefully with exponential backoff and automatic retry mechanisms. **Monitor Authentication Status**: Track authentication failures and unusual patterns that might indicate security issues. **Separate Keys Per Environment**: Use different API keys for development, staging, and production to prevent accidental production access. **Implement Timeout Handling**: Set appropriate timeout values for authentication handshakes to fail fast on connection issues. **Log Security Events**: Maintain audit logs of authentication attempts, failures, and key usage for security monitoring. ## Connection Management ```typescript class AuthenticatedStreamClient { private client: TransactionStreamClient; private metadata: Metadata; constructor(apiKey: string) { this.metadata = new Metadata(); this.metadata.add("authorization", `Bearer ${apiKey}`); this.client = new TransactionStreamClient( "stream.aptos.dwellir.com:443", credentials.createSsl() ); } subscribe(request: SubscribeRequest): ClientReadableStream { return this.client.subscribe(request, this.metadata); } // Handle authentication errors private handleAuthError(error: Error) { if (error.message.includes("Unauthenticated")) { console.error("Authentication failed - check API key"); // Trigger key refresh or alert } } } ``` ## Security Considerations **TLS Encryption**: Always use TLS/SSL encryption for streaming connections to protect credentials and data in transit. **Key Storage**: Store API keys and certificates in secure vaults (HashiCorp Vault, AWS Secrets Manager, etc.) rather than configuration files. **Access Scope**: Request minimum necessary permissions for API keys - don't use admin keys for read-only streaming. **Expiration Policies**: Implement key expiration policies and automated renewal processes to maintain security hygiene. **Rate Limiting**: Understand rate limits associated with your API keys and implement client-side throttling. **Error Handling**: Don't expose authentication details in error messages or logs that might leak credentials. ## Troubleshooting ### Authentication Failures ```typescript stream.on("error", (error) => { if (error.code === grpc.status.UNAUTHENTICATED) { console.error("Authentication failed"); // Check API key validity // Verify key has required permissions // Confirm key hasn't expired } }); ``` ### Connection Issues ```typescript const connectionDeadline = new Date(Date.now() + 5000); const stream = client.subscribe(request, metadata, { deadline: connectionDeadline }); stream.on("status", (status) => { if (status.code !== grpc.status.OK) { console.error(`Connection failed: ${status.details}`); } }); ``` ## Related Concepts - [Streaming Overview](/aptos/streaming_overview) - Introduction to transaction streaming - [Real-Time Streaming](/aptos/real_time) - Live transaction processing - [Custom Processors](/aptos/custom_processors) - Building stream processors - [Historical Replay](/aptos/historical_replay) - Replaying past transactions --- ## custom_processors > Coming soon: Need support for this? Email [support@dwellir.com](mailto:support@dwellir.com) if you want early access # Custom Processors Custom processors transform raw blockchain transactions into application-specific data models, enabling efficient real-time indexing and analytics. Building custom processors allows you to extract exactly the information your application needs while filtering irrelevant data, creating optimized databases tailored to your use cases. ## Overview A custom processor subscribes to transaction streams, decodes relevant transactions and events, transforms the data into your application's schema, and writes it to your database. This approach is more efficient than polling APIs or running full nodes, providing millisecond-latency updates with minimal infrastructure overhead. ## Processor Architecture ```typescript class AptosStreamProcessor { private stream: ClientReadableStream; private database: Database; async start() { this.stream = this.subscribeToTransactions(); this.stream.on("data", async (transaction) => { try { await this.processTransaction(transaction); } catch (error) { console.error("Processing error:", error); this.handleError(error, transaction); } }); this.stream.on("error", (error) => { console.error("Stream error:", error); this.reconnect(); }); this.stream.on("end", () => { console.log("Stream ended"); this.reconnect(); }); } private async processTransaction(tx: Transaction) { // Filter transactions by type if (!this.shouldProcess(tx)) return; // Decode transaction payload const decoded = this.decodeTransaction(tx); // Transform to application model const model = this.transformToModel(decoded); // Write to database await this.database.insert(model); // Update indexes await this.updateIndexes(model); // Emit events for real-time features this.emit("transaction", model); } private shouldProcess(tx: Transaction): boolean { // Filter logic - only process relevant transactions return ( tx.type === "user_transaction" && tx.payload?.function?.startsWith("0x1::coin::transfer") ); } } ``` ## Real-World Use Cases 1. **NFT Marketplace Indexing**: Process mint, transfer, and sale events in real-time to keep marketplace listings and analytics up-to-date without polling. 2. **DeFi Protocol Analytics**: Track swap events, liquidity changes, and yield updates across multiple protocols for portfolio dashboards and price feeds. 3. **Wallet Transaction History**: Index all transactions for user addresses into optimized databases for instant transaction history queries. 4. **Gaming State Management**: Process game move events and state changes to maintain real-time leaderboards and player inventories. 5. **Compliance Monitoring**: Scan transaction streams for patterns matching compliance rules, flagging suspicious activities in real-time. 6. **Price Oracle Updates**: Extract DEX swap data to compute and publish price feeds with sub-second latency for DeFi applications. ## Best Practices **Idempotent Processing**: Design processors to handle duplicate events safely since streaming guarantees at-least-once delivery, not exactly-once. **Checkpoint Progress**: Persistently track the last processed transaction version to enable resumption after restarts without reprocessing. **Batch Database Writes**: Buffer decoded events and write in batches to reduce database load and improve throughput. **Handle Reorgs Carefully**: Although rare on Aptos, implement logic to handle chain reorganizations if processing near the chain head. **Monitor Performance**: Track processing latency, throughput, and error rates to detect bottlenecks and degradations early. **Implement Circuit Breakers**: Automatically pause processing when error rates exceed thresholds to prevent cascading failures. **Schema Versioning**: Plan for schema evolution - use versioned data models to support processor upgrades without downtime. ## Event Decoding ```typescript interface DecodedEvent { type: string; data: any; address: string; sequence: bigint; } function decodeEvent(event: Event): DecodedEvent { const eventType = event.type.name; switch (eventType) { case "0x1::coin::WithdrawEvent": return { type: "coin_withdraw", data: { amount: BigInt(event.data.amount), coinType: event.type.typeArgs[0] }, address: event.key.accountAddress, sequence: BigInt(event.sequenceNumber) }; case "0x1::coin::DepositEvent": return { type: "coin_deposit", data: { amount: BigInt(event.data.amount), coinType: event.type.typeArgs[0] }, address: event.key.accountAddress, sequence: BigInt(event.sequenceNumber) }; default: return null; } } ``` ## State Management ```typescript class ProcessorState { private currentVersion: bigint = 0n; private checkpointInterval: number = 100; async saveCheckpoint() { await this.database.upsert("processor_state", { name: "main_processor", last_version: this.currentVersion.toString(), timestamp: new Date() }); } async loadCheckpoint(): Promise { const state = await this.database.findOne("processor_state", { name: "main_processor" }); return state ? BigInt(state.last_version) : 0n; } async updateVersion(version: bigint) { this.currentVersion = version; // Periodic checkpointing if (version % BigInt(this.checkpointInterval) === 0n) { await this.saveCheckpoint(); } } } ``` ## Error Handling ```typescript class ProcessorErrorHandler { private errorCounts: Map = new Map(); private maxRetries: number = 3; async handleProcessingError(error: Error, tx: Transaction) { const txHash = tx.hash; const count = (this.errorCounts.get(txHash) || 0) + 1; if (count >= this.maxRetries) { // Log to dead letter queue await this.deadLetterQueue.push({ transaction: tx, error: error.message, attempts: count, timestamp: new Date() }); this.errorCounts.delete(txHash); return; } this.errorCounts.set(txHash, count); // Exponential backoff await this.sleep(Math.pow(2, count) * 1000); // Retry processing await this.processTransaction(tx); } private sleep(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } } ``` ## Performance Optimization - **Parallel Processing**: Process independent transactions concurrently using worker pools - **Database Connection Pooling**: Reuse database connections to reduce overhead - **Selective Decoding**: Only decode fields you need rather than full transaction payloads - **Caching**: Cache frequently accessed data (token metadata, account info) to reduce database queries - **Compression**: Compress large payloads before storage to save space and I/O ## Monitoring Metrics ```typescript class ProcessorMetrics { transactionsProcessed: number = 0; eventsDecoded: number = 0; processingLatency: number[] = []; errorCount: number = 0; recordProcessing(startTime: number) { this.transactionsProcessed++; this.processingLatency.push(Date.now() - startTime); // Keep only recent latencies if (this.processingLatency.length > 1000) { this.processingLatency.shift(); } } getMetrics() { return { total: this.transactionsProcessed, errors: this.errorCount, avgLatency: this.processingLatency.reduce((a, b) => a + b, 0) / this.processingLatency.length, throughput: this.transactionsProcessed / (Date.now() / 1000) }; } } ``` ## Related Concepts - [Streaming Overview](/aptos/streaming_overview) - Introduction to streaming - [Historical Replay](/aptos/historical_replay) - Backfilling historical data - [Real-Time Streaming](/aptos/real_time) - Live transaction processing - [Authentication](/aptos/authentication) - Securing stream access --- ## historical_replay > Coming soon: Need support for this? Email [support@dwellir.com](mailto:support@dwellir.com) if you want early access # Historical Replay Historical replay enables replaying transactions from any point in blockchain history, essential for backfilling indexes, auditing past events, rebuilding state, and analyzing historical patterns. This feature provides efficient access to the entire transaction history without running full archive nodes. ## Overview The streaming API supports replaying transactions from genesis or any specific version forward, delivering historical data with the same performance and reliability as real-time streams. This enables applications to build complete indexes from scratch, verify historical states, or analyze long-term trends efficiently. ## Starting from Specific Versions ```typescript const client = new TransactionStreamClient( "stream.aptos.dwellir.com:443", credentials.createSsl() ); // Replay from specific version const request = { startingVersion: 100000000n, // Start from version 100M includeEvents: true, includeChanges: true }; const stream = client.subscribe(request, metadata); stream.on("data", (transaction) => { console.log(`Processing historical transaction: ${transaction.version}`); // Process transaction }); ``` ## Genesis Replay ```typescript // Replay from genesis (version 0) const genesisRequest = { startingVersion: 0n, includeEvents: true, includeChanges: false // Optimize bandwidth if changes not needed }; const genesisStream = client.subscribe(genesisRequest, metadata); let processedCount = 0; const startTime = Date.now(); genesisStream.on("data", (transaction) => { processedCount++; if (processedCount % 10000 === 0) { const elapsed = (Date.now() - startTime) / 1000; const rate = processedCount / elapsed; console.log(`Processed ${processedCount} transactions (${rate.toFixed(0)} tx/s)`); } }); ``` ## Real-World Use Cases 1. **Index Backfilling**: Build complete indexes from genesis when launching new applications or adding new index types to existing systems. 2. **Data Migration**: Migrate historical data from one database or schema to another by replaying transactions through updated processors. 3. **Historical Analysis**: Analyze long-term trends, patterns, and statistics by processing years of blockchain history efficiently. 4. **Audit and Compliance**: Replay specific time periods to audit transactions, verify compliance, or investigate historical events. 5. **State Reconstruction**: Rebuild application state from scratch by replaying all relevant transactions to verify correctness or recover from corruption. 6. **Research and Analytics**: Process complete blockchain history for academic research, market analysis, or protocol performance studies. ## Best Practices **Checkpoint Regularly**: Save progress frequently during historical replay to enable resumption without reprocessing millions of transactions. **Batch Processing**: Process transactions in batches and commit to database periodically rather than per-transaction to maximize throughput. **Resource Management**: Monitor memory usage and implement buffering strategies to handle high-throughput replay without overwhelming systems. **Progress Tracking**: Implement detailed progress tracking with estimated completion times to monitor long-running historical replays. **Parallel Processing**: Split historical ranges across multiple workers to parallelize processing and reduce total replay time. **Validate Completeness**: Track version gaps and verify continuous coverage to ensure no transactions are missed during replay. **Optimize Queries**: Use efficient database bulk insert operations and disable unnecessary indexes during replay for maximum throughput. ## Batch Replay Implementation ```typescript class HistoricalReplayProcessor { private batchSize: number = 1000; private buffer: Transaction[] = []; async replayRange(startVersion: bigint, endVersion: bigint) { const request = { startingVersion: startVersion, includeEvents: true }; const stream = client.subscribe(request, metadata); stream.on("data", async (transaction) => { // Stop at end version if (transaction.version > endVersion) { stream.cancel(); await this.flushBuffer(); return; } this.buffer.push(transaction); // Process in batches if (this.buffer.length >= this.batchSize) { await this.processBatch(this.buffer); this.buffer = []; } }); } private async processBatch(transactions: Transaction[]) { const records = transactions.map(tx => this.transformTransaction(tx)); // Bulk insert await this.database.bulkInsert("transactions", records); // Update checkpoint const lastVersion = transactions[transactions.length - 1].version; await this.saveCheckpoint(lastVersion); } private async flushBuffer() { if (this.buffer.length > 0) { await this.processBatch(this.buffer); } } } ``` ## Progress Monitoring ```typescript class ReplayMonitor { private startVersion: bigint; private endVersion: bigint; private currentVersion: bigint; private startTime: number; constructor(start: bigint, end: bigint) { this.startVersion = start; this.endVersion = end; this.currentVersion = start; this.startTime = Date.now(); } update(version: bigint) { this.currentVersion = version; } getProgress(): ReplayProgress { const total = Number(this.endVersion - this.startVersion); const processed = Number(this.currentVersion - this.startVersion); const percent = (processed / total) * 100; const elapsed = Date.now() - this.startTime; const rate = processed / (elapsed / 1000); const remaining = (total - processed) / rate; return { percent: percent.toFixed(2), processed, total, rate: rate.toFixed(0), eta: new Date(Date.now() + remaining * 1000).toISOString() }; } } ``` ## Parallel Replay Strategy ```typescript async function parallelReplay( startVersion: bigint, endVersion: bigint, workerCount: number ) { const totalRange = endVersion - startVersion; const rangePerWorker = totalRange / BigInt(workerCount); const workers = []; for (let i = 0; i < workerCount; i++) { const workerStart = startVersion + (rangePerWorker * BigInt(i)); const workerEnd = i === workerCount - 1 ? endVersion : workerStart + rangePerWorker; workers.push(replayRange(workerStart, workerEnd, i)); } await Promise.all(workers); } async function replayRange( start: bigint, end: bigint, workerId: number ) { console.log(`Worker ${workerId}: Replaying ${start} to ${end}`); const processor = new HistoricalReplayProcessor(); await processor.replayRange(start, end); console.log(`Worker ${workerId}: Complete`); } ``` ## Recovery and Resumption ```typescript class ReplayState { async saveCheckpoint(version: bigint, workerId: string) { await db.upsert("replay_checkpoints", { worker_id: workerId, last_version: version.toString(), updated_at: new Date() }); } async loadCheckpoint(workerId: string): Promise { const checkpoint = await db.findOne("replay_checkpoints", { worker_id: workerId }); return checkpoint ? BigInt(checkpoint.last_version) : null; } async resumeReplay(startVersion: bigint, endVersion: bigint, workerId: string) { // Try to resume from last checkpoint const checkpoint = await this.loadCheckpoint(workerId); const resumeFrom = checkpoint || startVersion; console.log(`Resuming from version ${resumeFrom}`); return this.replayRange(resumeFrom, endVersion); } } ``` ## Performance Optimization - **Disable Indexes**: Drop or disable indexes during bulk replay, rebuild after completion - **Batch Commits**: Commit database transactions in large batches (10k-100k records) - **Skip Validation**: Disable expensive validations during replay since data is already validated - **Compression**: Use compression for network transfer to reduce bandwidth usage - **SSD Storage**: Use fast SSDs for database writes during high-throughput replay ## Related Concepts - [Streaming Overview](/aptos/streaming_overview) - Introduction to streaming - [Real-Time Streaming](/aptos/real_time) - Processing current transactions - [Custom Processors](/aptos/custom_processors) - Building replay processors - [Authentication](/aptos/authentication) - Securing replay streams --- ## Transaction Streaming Overview > Coming soon: Need support for this? Email [support@dwellir.com](mailto:support@dwellir.com) if you want early access # Transaction Streaming Overview The streaming service delivers ordered transactions over gRPC with support for historical replay and real-time tails. ## Example Client (TypeScript) ``` // Placeholder endpoint const target = 'endpoint.coming.soon'; // Connect and subscribe ... ``` --- ## real_time > Coming soon: Need support for this? Email [support@dwellir.com](mailto:support@dwellir.com) if you want early access # Real-Time Streaming Real-time transaction streaming provides millisecond-latency access to finalized Aptos transactions as they occur on-chain, enabling responsive applications, trading systems, monitoring tools, and live dashboards. This feature delivers transactions with minimal delay after consensus, significantly faster than polling-based approaches. ## Overview Real-time streaming subscribes to the head of the blockchain, delivering transactions immediately as they are finalized by consensus. This approach provides consistent low-latency updates without the overhead and inconsistency of polling, ideal for applications requiring immediate awareness of on-chain state changes. ## Basic Real-Time Subscription ```typescript const client = new TransactionStreamClient( "stream.aptos.dwellir.com:443", credentials.createSsl() ); const metadata = new Metadata(); metadata.add("authorization", `Bearer ${process.env.API_KEY}`); // Subscribe to head of chain (no starting version = latest) const request = { includeEvents: true, includeChanges: true }; const stream = client.subscribe(request, metadata); stream.on("data", (transaction) => { console.log(`New transaction: ${transaction.hash}`); console.log(`Version: ${transaction.version}`); console.log(`Timestamp: ${transaction.timestamp}`); // Process transaction in real-time processTransaction(transaction); }); stream.on("error", (error) => { console.error("Stream error:", error); // Implement reconnection logic }); stream.on("end", () => { console.log("Stream ended"); // Reconnect }); ``` ## Real-World Use Cases 1. **Trading Bots**: Execute arbitrage or market-making strategies based on millisecond-fresh DEX swap data and price movements. 2. **Live Dashboards**: Display real-time protocol metrics, transaction volumes, gas prices, and network activity without refresh delays. 3. **Notification Systems**: Send instant push notifications when users receive payments, NFTs transfer, or important events occur. 4. **Gaming Applications**: Update game state, leaderboards, and player inventories immediately as transactions finalize on-chain. 5. **Security Monitoring**: Detect suspicious patterns, unusual transactions, or potential attacks in real-time for immediate response. 6. **Price Oracles**: Publish up-to-the-second price feeds by processing DEX trades and liquidity changes as they happen. ## Best Practices **Handle Reconnections Gracefully**: Implement automatic reconnection with exponential backoff when streams disconnect to maintain continuous coverage. **Track Last Processed Version**: Persist the last successfully processed version to resume streams without gaps after restarts. **Implement Buffering**: Buffer incoming transactions during processing spikes to prevent backpressure and dropped connections. **Monitor Stream Health**: Track message rates, latency, and error rates to detect and respond to degradation quickly. **Use Asynchronous Processing**: Process transactions asynchronously to avoid blocking the stream and falling behind. **Set Appropriate Timeouts**: Configure keepalive and timeout values to detect dead connections quickly. **Handle Duplicates**: Implement idempotent processing since network issues may cause duplicate transaction deliveries. ## Event Filtering ```typescript class RealTimeProcessor { private stream: ClientReadableStream; async start() { const request = { includeEvents: true, // Optional: filter by transaction type transactionFilters: { userTransaction: true, genesisTransaction: false, blockMetadataTransaction: false, stateCheckpointTransaction: false } }; this.stream = client.subscribe(request, metadata); this.stream.on("data", (tx) => { // Further filter by event type if (this.isRelevantTransaction(tx)) { this.processTransaction(tx); } }); } private isRelevantTransaction(tx: Transaction): boolean { // Filter by function calls if (tx.payload?.function) { return tx.payload.function.startsWith("0x1::coin::transfer"); } // Filter by events if (tx.events) { return tx.events.some(event => event.type.includes("WithdrawEvent") || event.type.includes("DepositEvent") ); } return false; } } ``` ## Latency Optimization ```typescript class LowLatencyProcessor { private processingQueue: Transaction[] = []; private processing: boolean = false; onTransaction(tx: Transaction) { this.processingQueue.push(tx); if (!this.processing) { this.processBatch(); } } private async processBatch() { this.processing = true; while (this.processingQueue.length > 0) { const batch = this.processingQueue.splice(0, 100); // Process batch in parallel await Promise.all( batch.map(tx => this.processTransactionFast(tx)) ); } this.processing = false; } private async processTransactionFast(tx: Transaction) { // Minimal processing for lowest latency const essential = this.extractEssentialData(tx); await this.fastWrite(essential); this.emitEvent(essential); } } ``` ## Connection Management ```typescript class StreamManager { private stream: ClientReadableStream | null = null; private reconnectAttempts: number = 0; private maxReconnectAttempts: number = 10; async connect() { try { this.stream = client.subscribe(request, metadata); this.stream.on("data", (tx) => { this.reconnectAttempts = 0; // Reset on successful data this.handleTransaction(tx); }); this.stream.on("error", (error) => { console.error("Stream error:", error); this.reconnect(); }); this.stream.on("end", () => { console.log("Stream ended"); this.reconnect(); }); } catch (error) { console.error("Connection error:", error); this.reconnect(); } } private async reconnect() { if (this.reconnectAttempts >= this.maxReconnectAttempts) { console.error("Max reconnection attempts reached"); return; } this.reconnectAttempts++; const backoff = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000); console.log(`Reconnecting in ${backoff}ms (attempt ${this.reconnectAttempts})`); await this.sleep(backoff); await this.connect(); } private sleep(ms: number): Promise { return new Promise(resolve => setTimeout(resolve, ms)); } disconnect() { if (this.stream) { this.stream.cancel(); this.stream = null; } } } ``` ## Metrics and Monitoring ```typescript class StreamMetrics { private lastTransactionTime: number = Date.now(); private transactionCount: number = 0; private latencies: number[] = []; recordTransaction(tx: Transaction, receivedAt: number) { this.transactionCount++; this.lastTransactionTime = receivedAt; // Calculate latency (time from tx timestamp to receipt) const txTime = new Date(tx.timestamp).getTime(); const latency = receivedAt - txTime; this.latencies.push(latency); // Keep only recent latencies if (this.latencies.length > 1000) { this.latencies.shift(); } } getMetrics() { const avgLatency = this.latencies.reduce((a, b) => a + b, 0) / this.latencies.length; const timeSinceLastTx = Date.now() - this.lastTransactionTime; return { totalProcessed: this.transactionCount, averageLatency: avgLatency.toFixed(0) + "ms", timeSinceLastTransaction: timeSinceLastTx + "ms", isHealthy: timeSinceLastTx < 5000 // Alert if > 5s without tx }; } } ``` ## Performance Considerations - **Network Proximity**: Deploy processors close to streaming endpoints to minimize network latency - **Concurrent Processing**: Use worker pools to process transactions in parallel without blocking the stream - **Memory Management**: Implement backpressure handling to prevent memory exhaustion during bursts - **Database Optimization**: Use connection pooling and bulk operations for database writes - **Caching**: Cache frequently accessed data to avoid database lookups during processing ## Related Concepts - [Streaming Overview](/aptos/streaming_overview) - Introduction to streaming - [Historical Replay](/aptos/historical_replay) - Processing past transactions - [Custom Processors](/aptos/custom_processors) - Building stream processors - [Authentication](/aptos/authentication) - Securing stream connections --- ## arb_getL1ConfirmationNumber - Get L1 confir... # arb_getL1ConfirmationNumber Get L1 confirmation number on the Arbitrum network. ## Parameters Varies by method. Please refer to the official documentation: [Arbitrum docs (finality & confirmations)](https://docs.arbitrum.io/for-devs/troubleshooting-building#how-many-block-numbers-must-we-wait-for-in-arbitrum-before-we-can-confidently-state-that-the-transaction-has-reached-finality) for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "arb_getL1ConfirmationNumber", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'arb_getL1ConfirmationNumber', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Arbitrum documentation](/docs/arbitrum).* --- ## arb_getTransactionReceipt - Get Arbitrum-sp... # arb_getTransactionReceipt Get Arbitrum-specific receipt on the Arbitrum network. ## Parameters Varies by method. Please refer to the official documentation: [Arbitrum docs (transaction lifecycle)](https://docs.arbitrum.io/how-arbitrum-works/l1-to-l2-messaging) for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "arb_getTransactionReceipt", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'arb_getTransactionReceipt', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Arbitrum documentation](/docs/arbitrum).* --- ## debug_traceBlock - Arbitrum RPC Method # debug_traceBlock Traces all transactions in a block on Arbitrum by block RLP. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Analyze transaction execution step-by-step - **Smart contract analysis** - Debug contract interactions - **Security auditing** - Trace internal calls for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockRlp` | `DATA` | Yes | RLP-encoded block data | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Use debug_traceBlockByNumber instead (more practical) const traces = await provider.send('debug_traceBlockByNumber', ['latest', {}]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by block number - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by block hash --- ## debug_traceBlockByHash - Arbitrum RPC Method # debug_traceBlockByHash Traces all transactions in a block on Arbitrum by block hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0xcb51ef4d410f0ddfdf102f18e40a7e44748001bae0b0f5bc065aadd13fa3c9b0", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0xcb51ef4d410f0ddfdf102f18e40a7e44748001bae0b0f5bc065aadd13fa3c9b0", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0xcb51ef4d410f0ddfdf102f18e40a7e44748001bae0b0f5bc065aadd13fa3c9b0'; const traces = await provider.send('debug_traceBlockByHash', [blockHash, { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by number - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceBlockByNumber - Arbitrum RPC Method # debug_traceBlockByNumber Traces all transactions in a block on Arbitrum by block number. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('debug_traceBlockByNumber', ['latest', { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by hash - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceCall - Arbitrum RPC Method # debug_traceCall Traces a call without creating a transaction on Arbitrum. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction simulation** - Debug before sending - **Gas analysis** - Analyze gas usage per opcode - **Contract debugging** - Step through execution for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `call` | `Object` | Yes | Call object (same as eth_call) | | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ { "to": "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "data": "0x70a0823100000000000000000000000013867a801e352e219c2d2AC29288Bf086e5C81ef" }, "latest", {} ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ {"to": "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "data": "0x70a0823100000000000000000000000013867a801e352e219c2d2AC29288Bf086e5C81ef"}, "latest", {"tracer": "callTracer"} ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const trace = await provider.send('debug_traceCall', [ { to: '0x13867a801e352e219c2d2AC29288Bf086e5C81ef', data: '0x70a0823100000000000000000000000013867a801e352e219c2d2AC29288Bf086e5C81ef' }, 'latest', { tracer: 'callTracer' } ]); console.log('Trace:', trace); ``` ## Related Methods - [`eth_call`](./eth_call) - Execute call without trace - [`debug_traceTransaction`](./debug_traceTransaction) - Trace actual transaction --- ## debug_traceTransaction - Arbitrum RPC Method # debug_traceTransaction Traces a transaction execution on Arbitrum by transaction hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Understand exactly what happened - **Failure analysis** - Find where and why a transaction reverted - **Gas optimization** - Analyze gas usage for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Tracer Options - `{}` - Default opcode tracer (verbose) - `{ tracer: "callTracer" }` - Call tree tracer - `{ tracer: "prestateTracer" }` - Pre-state tracer ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x6d26bc1cde1ce724eadaf4448431aa79a323ab58212c4ec39b5569b201ffaee2", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x6d26bc1cde1ce724eadaf4448431aa79a323ab58212c4ec39b5569b201ffaee2", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x6d26bc1cde1ce724eadaf4448431aa79a323ab58212c4ec39b5569b201ffaee2'; // Call tracer - shows internal calls const callTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'callTracer' } ]); console.log('Type:', callTrace.type); console.log('From:', callTrace.from); console.log('To:', callTrace.to); console.log('Gas used:', parseInt(callTrace.gasUsed, 16)); // Prestate tracer - shows state before execution const prestateTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'prestateTracer' } ]); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x6d26bc1cde1ce724eadaf4448431aa79a323ab58212c4ec39b5569b201ffaee2' # Call tracer trace = w3.provider.make_request('debug_traceTransaction', [ tx_hash, {'tracer': 'callTracer'} ]) print(f'Trace type: {trace["result"]["type"]}') print(f'Gas used: {int(trace["result"]["gasUsed"], 16)}') ``` ## Related Methods - [`debug_traceCall`](./debug_traceCall) - Trace without executing - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace entire block --- ## eth_accounts - Arbitrum RPC Method # eth_accounts Returns a list of addresses owned by the client on Arbitrum. > **Why Arbitrum?** Build on Ethereum's leading Layer 2 with 46% L2 market share and $12B+ TVL with full EVM compatibility, 1.5M daily transactions, and $3B+ DAO treasury for ecosystem growth. ## Important Note On public RPC endpoints like Dwellir, `eth_accounts` returns an empty array because the node does not hold any private keys. This method is primarily useful for: - Local development nodes (Ganache, Hardhat, Anvil) - Private nodes with managed accounts - Wallet provider connections (MetaMask injects accounts) ## When to Use This Method `eth_accounts` is relevant for DeFi developers, protocol teams, and dApp builders seeking Ethereum scalability in specific scenarios: - **Development Testing** — Retrieve test accounts from local nodes - **Wallet Detection** — Check if a wallet provider has connected accounts - **Client Verification** — Confirm node account access capabilities ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `Array` | List of 20-byte account addresses owned by the client | **Return format**: Array of `0x` prefixed hexadecimal addresses (typically empty for public nodes) ## Request ```json { "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 } ``` ## Response ### Successful Response (Public Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [] } ``` ### Successful Response (Local Development Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [ "0x407d73d8a49eeb85d32cf465507dd71d507100c1", "0x85d32cf465507dd71d507100c1407d73d8a49eeb" ] } ``` ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_accounts', params: [], id: 1 }) }); const { result } = await response.json(); console.log('Accounts:', result); // Using ethers.js const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const accounts = await provider.listAccounts(); console.log('Accounts:', accounts); ``` ```python def get_accounts(): response = requests.post( 'https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_accounts', 'params': [], 'id': 1 } ) return response.json()['result'] accounts = get_accounts() print(f'Accounts: {accounts}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) print(f'Accounts: {w3.eth.accounts}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/rpc" ) func main() { client, err := rpc.Dial("https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } var accounts []string err = client.CallContext(context.Background(), &accounts, "eth_accounts") if err != nil { log.Fatal(err) } fmt.Printf("Accounts: %v\n", accounts) } ``` ## Common Use Cases ### 1. Development Environment Detection Check if running against a development node with test accounts: ```javascript async function isDevEnvironment(provider) { const accounts = await provider.listAccounts(); return accounts.length > 0; } const isDev = await isDevEnvironment(provider); if (isDev) { console.log('Development environment detected'); } ``` ### 2. Wallet Connection Check Verify wallet provider has connected accounts: ```javascript async function checkWalletConnection() { if (typeof window.ethereum === 'undefined') { return { connected: false, reason: 'No wallet detected' }; } const accounts = await window.ethereum.request({ method: 'eth_accounts' }); return { connected: accounts.length > 0, accounts: accounts }; } ``` ### 3. Fallback Account Selection Use first available account or request connection: ```javascript async function getActiveAccount() { // Check existing connections let accounts = await window.ethereum.request({ method: 'eth_accounts' }); // Request connection if no accounts if (accounts.length === 0) { accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); } return accounts[0] || null; } ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32601 | Method not found | Node may not support this method | | -32603 | Internal error | Retry with exponential backoff | ```javascript async function safeGetAccounts(provider) { try { const accounts = await provider.listAccounts(); return { success: true, accounts }; } catch (error) { if (error.code === -32601) { console.warn('eth_accounts not supported on this node'); return { success: false, accounts: [], reason: 'unsupported' }; } throw error; } } ``` ## Related Methods - [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102) — Request wallet connection (browser wallets) - [`eth_getBalance`](./eth_getBalance) — Get account balance - [`eth_getTransactionCount`](./eth_getTransactionCount) — Get account nonce --- ## eth_blockNumber - Arbitrum RPC Method # eth_blockNumber Returns the number of the most recent block on Arbitrum. > **Why Arbitrum?** Build on Ethereum's leading Layer 2 with 46% L2 market share and $12B+ TVL with full EVM compatibility, 1.5M daily transactions, and $3B+ DAO treasury for ecosystem growth. ## When to Use This Method `eth_blockNumber` is fundamental for DeFi developers, protocol teams, and dApp builders seeking Ethereum scalability: - **Syncing Applications** — Keep your dApp in sync with the latest Arbitrum blockchain state - **Transaction Monitoring** — Verify confirmations by comparing block numbers - **Event Filtering** — Set the correct block range for querying logs on high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications - **Health Checks** — Monitor node connectivity and sync status ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `QUANTITY` | Hexadecimal string representing the current block number | **Return format**: `0x` prefixed hexadecimal (e.g., `0x5BAD55` = 6,008,149 in decimal) ## Request ```json { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } ``` ## Response ### Successful Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5BAD55" } ``` ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error" } } ``` ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }) }); const { result } = await response.json(); const blockNumber = parseInt(result, 16); console.log('Arbitrum block:', blockNumber); // Using ethers.js const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockNumber = await provider.getBlockNumber(); console.log('Arbitrum block:', blockNumber); ``` ```python def get_block_number(): response = requests.post( 'https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_blockNumber', 'params': [], 'id': 1 } ) result = response.json()['result'] return int(result, 16) block_number = get_block_number() print(f'Arbitrum block: {block_number}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) print(f'Arbitrum block: {w3.eth.block_number}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockNumber, err := client.BlockNumber(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Arbitrum block: %d\n", blockNumber) } ``` ## Common Use Cases ### 1. Block Confirmation Counter Monitor transaction confirmations on Arbitrum: ```javascript async function getConfirmations(provider, txHash) { const tx = await provider.getTransaction(txHash); if (!tx || !tx.blockNumber) return 0; const currentBlock = await provider.getBlockNumber(); return currentBlock - tx.blockNumber + 1; } // Wait for specific confirmations async function waitForConfirmations(provider, txHash, confirmations = 6) { let currentConfirmations = 0; while (currentConfirmations < confirmations) { currentConfirmations = await getConfirmations(provider, txHash); console.log(`Confirmations: ${currentConfirmations}/${confirmations}`); await new Promise(r => setTimeout(r, 2000)); } return true; } ``` ### 2. Event Log Filtering Query events from recent blocks on Arbitrum: ```javascript async function getRecentEvents(provider, contract, eventName, blockRange = 100) { const currentBlock = await provider.getBlockNumber(); const fromBlock = currentBlock - blockRange; const filter = contract.filters[eventName](); const events = await contract.queryFilter(filter, fromBlock, currentBlock); return events; } ``` ### 3. Node Health Monitoring Check if your Arbitrum node is synced: ```javascript async function checkNodeHealth(provider) { try { const blockNumber = await provider.getBlockNumber(); const block = await provider.getBlock(blockNumber); const now = Date.now() / 1000; const blockAge = now - block.timestamp; if (blockAge > 60) { console.warn(`Node may be behind. Last block was ${blockAge}s ago`); return false; } console.log(`Node healthy. Latest block: ${blockNumber}`); return true; } catch (error) { console.error('Node unreachable:', error); return false; } } ``` ## Performance Optimization ### Caching Strategy Cache block numbers to reduce API calls: ```javascript class BlockNumberCache { constructor(ttl = 2000) { this.cache = null; this.timestamp = 0; this.ttl = ttl; } async get(provider) { const now = Date.now(); if (this.cache && (now - this.timestamp) < this.ttl) { return this.cache; } this.cache = await provider.getBlockNumber(); this.timestamp = now; return this.cache; } invalidate() { this.cache = null; this.timestamp = 0; } } const blockCache = new BlockNumberCache(); ``` ### Batch Requests Combine with other calls for efficiency: ```javascript const batch = [ { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }, { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 }, { jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 } ]; const response = await fetch('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await response.json(); ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32603 | Internal error | Retry with exponential backoff | | -32005 | Rate limit exceeded | Implement rate limiting client-side | | -32000 | Execution reverted | Check node sync status | ```javascript async function safeGetBlockNumber(provider, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await provider.getBlockNumber(); } catch (error) { if (error.code === -32005) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } else if (i === maxRetries - 1) { throw error; } } } } ``` ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) — Get full block details by number - [`eth_getBlockByHash`](./eth_getBlockByHash) — Get block details by hash - [`eth_syncing`](./eth_syncing) — Check if node is still syncing --- ## eth_call - Arbitrum RPC Method # eth_call Executes a new message call immediately without creating a transaction on Arbitrum. Used for reading smart contract state. > **Why Arbitrum?** Build on Ethereum's leading Layer 2 with 46% L2 market share and $12B+ TVL with full EVM compatibility, 1.5M daily transactions, and $3B+ DAO treasury for ecosystem growth. ## Use Cases The `eth_call` method is essential for: - **Reading contract state** - Query view/pure functions - **Simulating transactions** - Test execution without gas costs - **DeFi integrations** - Check prices, balances, allowances for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications - **Complex queries** - Execute multi-step contract logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | 20-byte address executing the call | | `to` | `DATA` | Yes | 20-byte contract address | | `gas` | `QUANTITY` | No | Gas limit for the call | | `gasPrice` | `QUANTITY` | No | Gas price in wei | | `value` | `QUANTITY` | No | Value to send in wei | | `data` | `DATA` | Yes | Encoded function call data | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_call", "params": [ { "to": "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "data": "0x70a0823100000000000000000000000013867a801e352e219c2d2AC29288Bf086e5C81ef" }, "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | The return value of the executed contract function | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000" } ``` ## Code Examples ```bash # Call ERC20 balanceOf function curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{ "to": "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "data": "0x70a0823100000000000000000000000013867a801e352e219c2d2AC29288Bf086e5C81ef" }, "latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // ERC20 ABI for common functions const ERC20_ABI = [ "function balanceOf(address owner) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function totalSupply() view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)" ]; // Read ERC20 token balance async function getTokenBalance(tokenAddress, walletAddress) { const contract = new Contract(tokenAddress, ERC20_ABI, provider); const balance = await contract.balanceOf(walletAddress); const decimals = await contract.decimals(); const symbol = await contract.symbol(); return { raw: balance.toString(), formatted: (Number(balance) / Math.pow(10, decimals)).toFixed(4), symbol: symbol }; } // Direct eth_call async function directCall(to, data) { const result = await provider.call({ to, data }); return result; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) def get_erc20_balance(token_address, wallet_address): # balanceOf(address) selector function_signature = "balanceOf(address)" function_selector = w3.keccak(text=function_signature)[:4].hex() # Encode address parameter encoded_address = wallet_address[2:].lower().zfill(64) data = function_selector + encoded_address # Make the call result = w3.eth.call({ 'to': token_address, 'data': data }) return int(result.hex(), 16) balance = get_erc20_balance( '0x13867a801e352e219c2d2AC29288Bf086e5C81ef', '0x13867a801e352e219c2d2AC29288Bf086e5C81ef' ) print(f'Balance: {balance}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0x13867a801e352e219c2d2AC29288Bf086e5C81ef") data := common.FromHex("0x70a0823100000000000000000000000013867a801e352e219c2d2AC29288Bf086e5C81ef") msg := ethereum.CallMsg{ To: &contractAddress, Data: data, } result, err := client.CallContract(context.Background(), msg, nil) if err != nil { log.Fatal(err) } fmt.Printf("Result: 0x%x\n", result) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Contract function reverted | | -32602 | Invalid parameters | Invalid data encoding | | -32015 | VM execution error | Contract logic error | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas for transaction - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send actual transaction --- ## eth_chainId - Arbitrum RPC Method # eth_chainId Returns the chain ID used for transaction signing on Arbitrum. > **Why Arbitrum?** Build on Ethereum's leading Layer 2 with 46% L2 market share and $12B+ TVL with full EVM compatibility, 1.5M daily transactions, and $3B+ DAO treasury for ecosystem growth. ## Use Cases The `eth_chainId` method is essential for: - **Transaction signing** - Ensure transactions are signed for the correct network - **Network verification** - Confirm connection to the expected chain - **Multi-chain apps** - Handle different networks programmatically - **Wallet integration** - Validate network before transactions ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Chain ID in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1" } ``` ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const network = await provider.getNetwork(); console.log('Chain ID:', network.chainId); // Verify network before transaction async function verifyNetwork(expectedChainId) { const network = await provider.getNetwork(); if (network.chainId !== BigInt(expectedChainId)) { throw new Error(`Wrong network. Expected ${expectedChainId}, got ${network.chainId}`); } return true; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) chain_id = w3.eth.chain_id print(f'Chain ID: {chain_id}') # Verify network def verify_network(expected_chain_id): chain_id = w3.eth.chain_id if chain_id != expected_chain_id: raise ValueError(f'Wrong network. Expected {expected_chain_id}, got {chain_id}') return True ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } chainID, err := client.ChainID(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Chain ID: %d\n", chainID) } ``` ## Related Methods - [`net_version`](./net_version) - Get network version - [`eth_syncing`](./eth_syncing) - Check sync status --- ## eth_coinbase - Get coinbase address # eth_coinbase Get coinbase address on the Arbitrum network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_coinbase](https://ethereum.org/developers/docs/apis/json-rpc/#eth_coinbase) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_coinbase", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_coinbase', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Arbitrum documentation](/docs/arbitrum).* --- ## eth_estimateGas - Arbitrum RPC Method # eth_estimateGas Estimates the gas necessary to execute a transaction on Arbitrum. > **Why Arbitrum?** Build on Ethereum's leading Layer 2 with 46% L2 market share and $12B+ TVL with full EVM compatibility, 1.5M daily transactions, and $3B+ DAO treasury for ecosystem growth. ## Use Cases The `eth_estimateGas` method is essential for: - **Transaction preparation** - Set appropriate gas limits - **Cost estimation** - Calculate transaction costs before sending - **Error detection** - Identify reverts before spending gas - **DeFi operations** - Estimate costs for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | Sender address | | `to` | `DATA` | No | Recipient address | | `gas` | `QUANTITY` | No | Gas limit | | `gasPrice` | `QUANTITY` | No | Gas price | | `value` | `QUANTITY` | No | Value in wei | | `data` | `DATA` | No | Transaction data | ## Request ```json { "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "to": "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "value": "0x1" }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Estimated gas amount in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5208" } ``` **Note**: `0x5208` = 21000 gas (standard ETH transfer) ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "to": "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "value": "0x1" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Estimate simple transfer async function estimateTransfer(to, value) { const gasEstimate = await provider.estimateGas({ to: to, value: parseEther(value) }); console.log('Estimated gas:', gasEstimate.toString()); return gasEstimate; } // Estimate contract call async function estimateContractCall(contract, method, args) { const gasEstimate = await contract[method].estimateGas(...args); console.log('Estimated gas:', gasEstimate.toString()); // Add 20% buffer for safety return gasEstimate * 120n / 100n; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) def estimate_transfer(to, value_in_ether): gas_estimate = w3.eth.estimate_gas({ 'to': to, 'value': w3.to_wei(value_in_ether, 'ether') }) print(f'Estimated gas: {gas_estimate}') return gas_estimate def estimate_contract_call(contract, method, args): func = getattr(contract.functions, method) gas_estimate = func(*args).estimate_gas() # Add 20% buffer return int(gas_estimate * 1.2) # Estimate simple transfer gas = estimate_transfer('0x13867a801e352e219c2d2AC29288Bf086e5C81ef', 0.1) ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } toAddress := common.HexToAddress("0x13867a801e352e219c2d2AC29288Bf086e5C81ef") msg := ethereum.CallMsg{ To: &toAddress, Value: big.NewInt(1000000000000000000), } gasLimit, err := client.EstimateGas(context.Background(), msg) if err != nil { log.Fatal(err) } fmt.Printf("Estimated gas: %d\n", gasLimit) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Transaction would fail | | -32602 | Invalid params | Invalid transaction parameters | **Tip**: If estimation fails, the transaction would likely revert if sent. ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_estimateL1Fee - Estimate L1 data postin... # eth_estimateL1Fee Estimate L1 data posting fee on the Arbitrum network. ## Parameters Varies by method. Please refer to the official documentation: [Arbitrum docs (L1 fee calculation)](https://docs.arbitrum.io/for-devs/troubleshooting-building#how-is-the-l1-portion-of-an-arbitrum-transactions-gas-fee-computed) for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateL1Fee", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_estimateL1Fee', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Arbitrum documentation](/docs/arbitrum).* --- ## eth_feeHistory - Arbitrum RPC Method # eth_feeHistory Returns historical gas information on Arbitrum for fee estimation. ## Use Cases - **Fee prediction** - Estimate future gas prices based on history - **Gas analytics** - Analyze fee trends over time - **Optimal timing** - Find best times for transactions on high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockCount` | `QUANTITY` | Yes | Number of blocks in the range | | `newestBlock` | `QUANTITY\|TAG` | Yes | Highest block of the range | | `rewardPercentiles` | `Array` | Yes | Percentiles to sample for priority fees | ## Request ```json { "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const feeHistory = await provider.send('eth_feeHistory', ['0xa', 'latest', [25, 50, 75]]); console.log('Base fees:', feeHistory.baseFeePerGas.map(f => formatUnits(f, 'gwei'))); console.log('Reward (25th percentile):', feeHistory.reward.map(r => formatUnits(r[0], 'gwei'))); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) fee_history = w3.eth.fee_history(10, 'latest', [25, 50, 75]) print(f'Base fees: {[w3.from_wei(f, "gwei") for f in fee_history["baseFeePerGas"]]}') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee --- ## eth_gasPrice - Arbitrum RPC Method # eth_gasPrice Returns the current gas price on Arbitrum in wei. > **Why Arbitrum?** Build on Ethereum's leading Layer 2 with 46% L2 market share and $12B+ TVL with full EVM compatibility, 1.5M daily transactions, and $3B+ DAO treasury for ecosystem growth. ## Use Cases The `eth_gasPrice` method is essential for: - **Transaction pricing** - Set appropriate gas prices - **Cost estimation** - Calculate transaction costs before sending - **Gas monitoring** - Track network congestion - **DeFi operations** - Optimize costs for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Current gas price in wei (hexadecimal) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x3b9aca00" } ``` **Note**: `0x3b9aca00` = 1 Gwei (1,000,000,000 wei) ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); const gasPrice = feeData.gasPrice; console.log('Gas Price:', formatUnits(gasPrice, 'gwei'), 'Gwei'); // Calculate transaction cost async function estimateTransactionCost(gasLimit) { const feeData = await provider.getFeeData(); const cost = feeData.gasPrice * BigInt(gasLimit); return formatUnits(cost, 'ether'); } const cost = await estimateTransactionCost(21000); console.log('Transfer cost:', cost, 'ETH'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) gas_price = w3.eth.gas_price print(f'Gas Price: {w3.from_wei(gas_price, "gwei")} Gwei') # Calculate transaction cost def estimate_transaction_cost(gas_limit): gas_price = w3.eth.gas_price cost = gas_price * gas_limit return w3.from_wei(cost, 'ether') cost = estimate_transaction_cost(21000) print(f'Transfer cost: {cost} ETH') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } gasPrice, err := client.SuggestGasPrice(context.Background()) if err != nil { log.Fatal(err) } // Convert to Gwei gwei := new(big.Float).Quo( new(big.Float).SetInt(gasPrice), big.NewFloat(1e9), ) fmt.Printf("Gas Price: %f Gwei\n", gwei) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32603 | Internal error | Node error | ## Related Methods - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee (EIP-1559) - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas needed --- ## eth_getBalance - Arbitrum RPC Method # eth_getBalance Returns the balance of a given address on Arbitrum. > **Why Arbitrum?** Build on Ethereum's leading Layer 2 with 46% L2 market share and $12B+ TVL with full EVM compatibility, 1.5M daily transactions, and $3B+ DAO treasury for ecosystem growth. ## Use Cases The `eth_getBalance` method is essential for: - **Wallet applications** - Display user balances - **Transaction validation** - Check if account has sufficient funds - **DeFi applications** - Monitor collateral and liquidity for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications - **Account monitoring** - Track balance changes over time ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address to check balance for | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Integer of the current balance in wei (hexadecimal) | **Note**: 1 native token = 10^18 wei. Convert using `balance / 10^18`. ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1a055690d9db80000" } ``` ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x13867a801e352e219c2d2AC29288Bf086e5C81ef'; const balanceWei = await provider.getBalance(address); const balance = formatEther(balanceWei); console.log(`Balance: ${balance}`); // Get balance at specific block const historicalBalance = await provider.getBalance(address, 1000000); console.log(`Historical balance: ${formatEther(historicalBalance)}`); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x13867a801e352e219c2d2AC29288Bf086e5C81ef' balance_wei = w3.eth.get_balance(address) balance = w3.from_wei(balance_wei, 'ether') print(f'Balance: {balance}') # Get balance at specific block historical_balance = w3.eth.get_balance(address, block_identifier=1000000) print(f'Historical balance: {w3.from_wei(historical_balance, "ether")}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0x13867a801e352e219c2d2AC29288Bf086e5C81ef") balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } // Convert to ether fbalance := new(big.Float).SetInt(balance) ethValue := new(big.Float).Quo(fbalance, big.NewFloat(1e18)) fmt.Printf("Balance: %f\n", ethValue) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid address format or block parameter | | -32000 | Execution error | Node execution error | ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_getTransactionCount`](./eth_getTransactionCount) - Get account nonce --- ## eth_getBlockByHash - Arbitrum RPC Method # eth_getBlockByHash Returns information about a block by hash on Arbitrum. > **Why Arbitrum?** Build on Ethereum's leading Layer 2 with 46% L2 market share and $12B+ TVL with full EVM compatibility, 1.5M daily transactions, and $3B+ DAO treasury for ecosystem growth. ## Use Cases The `eth_getBlockByHash` method is essential for: - **Block verification** - Verify block data using its unique hash - **Chain reorganization handling** - Track blocks during reorgs - **Cross-chain bridges** - Verify block finality for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications - **Deterministic queries** - Get consistent block data regardless of chain state ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0xcb51ef4d410f0ddfdf102f18e40a7e44748001bae0b0f5bc065aadd13fa3c9b0", false ], "id": 1 } ``` ## Returns Returns the same block object as `eth_getBlockByNumber`, or `null` if no block is found. | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used | | `transactions` | `Array` | Transaction objects or hashes | ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0xcb51ef4d410f0ddfdf102f18e40a7e44748001bae0b0f5bc065aadd13fa3c9b0", false ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0xcb51ef4d410f0ddfdf102f18e40a7e44748001bae0b0f5bc065aadd13fa3c9b0'; const block = await provider.getBlock(blockHash); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) block_hash = '0xcb51ef4d410f0ddfdf102f18e40a7e44748001bae0b0f5bc065aadd13fa3c9b0' block = w3.eth.get_block(block_hash) print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockHash := common.HexToHash("0xcb51ef4d410f0ddfdf102f18e40a7e44748001bae0b0f5bc065aadd13fa3c9b0") block, err := client.BlockByHash(context.Background(), blockHash) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block hash format | | -32000 | Block not found | Block with this hash does not exist | ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) - Get block by number - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number --- ## eth_getBlockByNumber - Arbitrum RPC Method # eth_getBlockByNumber Returns information about a block by block number on Arbitrum. > **Why Arbitrum?** Build on Ethereum's leading Layer 2 with 46% L2 market share and $12B+ TVL with full EVM compatibility, 1.5M daily transactions, and $3B+ DAO treasury for ecosystem growth. ## Use Cases The `eth_getBlockByNumber` method is essential for: - **Block explorers** - Display complete block information - **Transaction indexers** - Process all transactions in a block - **Analytics platforms** - Analyze blockchain data for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications - **Timestamp verification** - Get block timestamps for time-based logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used by all transactions | | `gasLimit` | `QUANTITY` | Maximum gas allowed in block | | `transactions` | `Array` | Array of transaction objects or hashes | | `baseFeePerGas` | `QUANTITY` | Base fee per gas (EIP-1559) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": { "number": "0x5BAD55", "hash": "0xcb51ef4d410f0ddfdf102f18e40a7e44748001bae0b0f5bc065aadd13fa3c9b0", "parentHash": "0x...", "timestamp": "0x64d8f6d0", "gasUsed": "0x1234", "gasLimit": "0x1c9c380", "transactions": [], "baseFeePerGas": "0x5f5e100" } } ``` ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Get latest block const block = await provider.getBlock('latest'); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); console.log('Transactions:', block.transactions.length); // Get block with full transactions const blockWithTxs = await provider.getBlock('latest', true); for (const tx of blockWithTxs.prefetchedTransactions) { console.log('Transaction:', tx.hash); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) # Get latest block block = w3.eth.get_block('latest') print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') print(f'Transactions: {len(block.transactions)}') # Get block with full transactions block_full = w3.eth.get_block('latest', full_transactions=True) for tx in block_full.transactions: print(f'Transaction: {tx.hash.hex()}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } // Get latest block block, err := client.BlockByNumber(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) fmt.Printf("Timestamp: %d\n", block.Time()) fmt.Printf("Transactions: %d\n", len(block.Transactions())) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block number or parameter format | | -32000 | Block not found | Block does not exist | ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number - [`eth_getBlockByHash`](./eth_getBlockByHash) - Get block by hash - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_getCode - Arbitrum RPC Method # eth_getCode Returns the bytecode at a given address on Arbitrum. > **Why Arbitrum?** Build on Ethereum's leading Layer 2 with 46% L2 market share and $12B+ TVL with full EVM compatibility, 1.5M daily transactions, and $3B+ DAO treasury for ecosystem growth. ## Use Cases The `eth_getCode` method is essential for: - **Contract verification** - Check if address is a contract - **Security analysis** - Verify deployed bytecode matches expected - **DeFi integrations** - Validate contracts before interactions - **Protocol analysis** - Analyze contract deployments for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Contract bytecode or `0x` if EOA | ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x13867a801e352e219c2d2AC29288Bf086e5C81ef'; const code = await provider.getCode(address); if (code === '0x') { console.log('Address is an EOA (externally owned account)'); } else { console.log('Address is a contract'); console.log('Bytecode length:', code.length); } // Check if address is a contract async function isContract(address) { const code = await provider.getCode(address); return code !== '0x'; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x13867a801e352e219c2d2AC29288Bf086e5C81ef' code = w3.eth.get_code(address) if code == b'': print('Address is an EOA') else: print('Address is a contract') print(f'Bytecode length: {len(code.hex())}') # Check if address is a contract def is_contract(address): code = w3.eth.get_code(address) return code != b'' ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0x13867a801e352e219c2d2AC29288Bf086e5C81ef") code, err := client.CodeAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } if len(code) == 0 { fmt.Println("Address is an EOA") } else { fmt.Printf("Contract bytecode length: %d\n", len(code)) } } ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_getStorageAt`](./eth_getStorageAt) - Get contract storage --- ## eth_getFilterChanges - Arbitrum RPC Method # eth_getFilterChanges Polling method for a filter on Arbitrum, returns an array of logs since last poll. ## Use Cases - **Event streaming** - Get new events incrementally - **Real-time monitoring** - Track contract activity for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications - **Efficient indexing** - Process only new events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Poll loop async function pollFilter(filterId, interval = 2000) { while (true) { const changes = await provider.send('eth_getFilterChanges', [filterId]); if (changes.length > 0) { console.log('New events:', changes); } await new Promise(r => setTimeout(r, interval)); } } ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter --- ## eth_getFilterLogs - Arbitrum RPC Method # eth_getFilterLogs Returns an array of all logs matching filter with given ID on Arbitrum. ## Use Cases - **Historical queries** - Get all matching logs for a filter - **Full event history** - Retrieve complete event data for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const logs = await provider.send('eth_getFilterLogs', [filterId]); console.log('All matching logs:', logs.length); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_getLogs - Arbitrum RPC Method # eth_getLogs Returns an array of all logs matching a given filter object on Arbitrum. > **Why Arbitrum?** Build on Ethereum's leading Layer 2 with 46% L2 market share and $12B+ TVL with full EVM compatibility, 1.5M daily transactions, and $3B+ DAO treasury for ecosystem growth. ## Use Cases The `eth_getLogs` method is essential for: - **Event indexing** - Track contract events for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications - **Token transfers** - Monitor ERC20/ERC721 transfers - **DeFi analytics** - Track swaps, liquidity events, and more - **Notification systems** - Alert on specific on-chain events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block (default: `"latest"`) | | `toBlock` | `QUANTITY\|TAG` | No | Ending block (default: `"latest"`) | | `address` | `DATA\|Array` | No | Contract address(es) to filter | | `topics` | `Array` | No | Array of topic filters | | `blockHash` | `DATA` | No | Filter single block by hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns Array of log objects: | Field | Type | Description | |-------|------|-------------| | `address` | `DATA` | Contract that emitted the log | | `topics` | `Array` | Array of indexed topics | | `data` | `DATA` | Non-indexed log data | | `blockNumber` | `QUANTITY` | Block number | | `transactionHash` | `DATA` | Transaction hash | | `logIndex` | `QUANTITY` | Log index in block | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": [{ "address": "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."], "data": "0x...", "blockNumber": "0x5BAD55", "transactionHash": "0x...", "logIndex": "0x0" }] } ``` ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Get Transfer events const TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'; async function getTransferEvents(tokenAddress, fromBlock, toBlock) { const logs = await provider.getLogs({ address: tokenAddress, topics: [TRANSFER_TOPIC], fromBlock: fromBlock, toBlock: toBlock }); return logs.map(log => ({ from: '0x' + log.topics[1].slice(26), to: '0x' + log.topics[2].slice(26), blockNumber: log.blockNumber, transactionHash: log.transactionHash })); } const events = await getTransferEvents( '0x13867a801e352e219c2d2AC29288Bf086e5C81ef', 'latest', 'latest' ); console.log('Transfer events:', events); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' def get_transfer_events(token_address, from_block, to_block): logs = w3.eth.get_logs({ 'address': token_address, 'topics': [TRANSFER_TOPIC], 'fromBlock': from_block, 'toBlock': to_block }) events = [] for log in logs: events.append({ 'from': '0x' + log['topics'][1].hex()[26:], 'to': '0x' + log['topics'][2].hex()[26:], 'block': log['blockNumber'], 'tx': log['transactionHash'].hex() }) return events events = get_transfer_events( '0x13867a801e352e219c2d2AC29288Bf086e5C81ef', 'latest', 'latest' ) print(f'Found {len(events)} transfer events') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0x13867a801e352e219c2d2AC29288Bf086e5C81ef") transferTopic := common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef") query := ethereum.FilterQuery{ FromBlock: big.NewInt(0), ToBlock: nil, Addresses: []common.Address{contractAddress}, Topics: [][]common.Hash, } logs, err := client.FilterLogs(context.Background(), query) if err != nil { log.Fatal(err) } fmt.Printf("Found %d events\n", len(logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32005 | Query returned more than 10000 results | Reduce block range | | -32602 | Invalid params | Invalid filter parameters | ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create a filter for logs - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for new logs --- ## eth_getStorageAt - Arbitrum RPC Method # eth_getStorageAt Returns the value from a storage position at a given address on Arbitrum. ## Use Cases - **Contract analysis** - Read raw storage values - **State verification** - Verify contract state - **Security auditing** - Analyze storage layout for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications - **Protocol monitoring** - Track state changes ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte contract address | | `position` | `QUANTITY` | Yes | Storage slot position | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "0x0", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "0x0", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x13867a801e352e219c2d2AC29288Bf086e5C81ef'; const slot = 0; const storage = await provider.getStorage(address, slot); console.log('Storage at slot 0:', storage); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x13867a801e352e219c2d2AC29288Bf086e5C81ef' storage = w3.eth.get_storage_at(address, 0) print(f'Storage at slot 0: {storage.hex()}') ``` ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_call`](./eth_call) - Call contract functions --- ## eth_getTransactionByHash - Arbitrum RPC Method # eth_getTransactionByHash Returns the information about a transaction by transaction hash on Arbitrum. > **Why Arbitrum?** Build on Ethereum's leading Layer 2 with 46% L2 market share and $12B+ TVL with full EVM compatibility, 1.5M daily transactions, and $3B+ DAO treasury for ecosystem growth. ## Use Cases The `eth_getTransactionByHash` method is essential for: - **Transaction tracking** - Get details of pending or confirmed transactions - **Payment verification** - Verify transaction parameters - **Debugging** - Analyze transaction data for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications - **Block explorers** - Display transaction information ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x6d26bc1cde1ce724eadaf4448431aa79a323ab58212c4ec39b5569b201ffaee2"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `hash` | `DATA` | Transaction hash | | `from` | `DATA` | Sender address | | `to` | `DATA` | Recipient address | | `value` | `QUANTITY` | Value in wei | | `gas` | `QUANTITY` | Gas provided | | `gasPrice` | `QUANTITY` | Gas price in wei | | `input` | `DATA` | Transaction input data | | `nonce` | `QUANTITY` | Sender's nonce | | `blockHash` | `DATA` | Block hash (null if pending) | | `blockNumber` | `QUANTITY` | Block number (null if pending) | ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x6d26bc1cde1ce724eadaf4448431aa79a323ab58212c4ec39b5569b201ffaee2"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x6d26bc1cde1ce724eadaf4448431aa79a323ab58212c4ec39b5569b201ffaee2'; const tx = await provider.getTransaction(txHash); if (tx) { console.log('From:', tx.from); console.log('To:', tx.to); console.log('Value:', formatEther(tx.value)); console.log('Block:', tx.blockNumber); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x6d26bc1cde1ce724eadaf4448431aa79a323ab58212c4ec39b5569b201ffaee2' tx = w3.eth.get_transaction(tx_hash) if tx: print(f'From: {tx["from"]}') print(f'To: {tx["to"]}') print(f'Value: {w3.from_wei(tx["value"], "ether")}') print(f'Block: {tx["blockNumber"]}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x6d26bc1cde1ce724eadaf4448431aa79a323ab58212c4ec39b5569b201ffaee2") tx, isPending, err := client.TransactionByHash(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Pending: %v\n", isPending) fmt.Printf("Value: %s\n", tx.Value().String()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash format | ## Related Methods - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction receipt - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionCount - Arbitrum RPC Method # eth_getTransactionCount Returns the number of transactions sent from an address on Arbitrum (the nonce). ## Use Cases - **Transaction building** - Get correct nonce for new transactions - **Account analysis** - Count total outgoing transactions - **Nonce management** - Handle pending transaction queues - **Wallet operations** - Prepare transactions for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag (`pending` for next nonce) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x13867a801e352e219c2d2AC29288Bf086e5C81ef'; const nonce = await provider.getTransactionCount(address); console.log('Nonce:', nonce); // Get pending nonce for new transaction const pendingNonce = await provider.getTransactionCount(address, 'pending'); console.log('Next nonce:', pendingNonce); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x13867a801e352e219c2d2AC29288Bf086e5C81ef' nonce = w3.eth.get_transaction_count(address) print(f'Nonce: {nonce}') # Get pending nonce pending_nonce = w3.eth.get_transaction_count(address, 'pending') print(f'Next nonce: {pending_nonce}') ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionReceipt - Arbitrum RPC Method # eth_getTransactionReceipt Returns the receipt of a transaction by transaction hash on Arbitrum. Receipt is only available for mined transactions. > **Why Arbitrum?** Build on Ethereum's leading Layer 2 with 46% L2 market share and $12B+ TVL with full EVM compatibility, 1.5M daily transactions, and $3B+ DAO treasury for ecosystem growth. ## Use Cases The `eth_getTransactionReceipt` method is essential for: - **Transaction confirmation** - Verify transaction was mined successfully - **Gas analysis** - Check actual gas used vs estimated - **Event parsing** - Read emitted events from logs - **Status verification** - Confirm success/failure for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x6d26bc1cde1ce724eadaf4448431aa79a323ab58212c4ec39b5569b201ffaee2"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `status` | `QUANTITY` | `1` (success) or `0` (failure) | | `transactionHash` | `DATA` | Transaction hash | | `blockHash` | `DATA` | Block hash | | `blockNumber` | `QUANTITY` | Block number | | `gasUsed` | `QUANTITY` | Gas used by this transaction | | `cumulativeGasUsed` | `QUANTITY` | Total gas used in block up to this tx | | `logs` | `Array` | Array of log objects | | `contractAddress` | `DATA` | Created contract address (if deployment) | ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x6d26bc1cde1ce724eadaf4448431aa79a323ab58212c4ec39b5569b201ffaee2"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x6d26bc1cde1ce724eadaf4448431aa79a323ab58212c4ec39b5569b201ffaee2'; const receipt = await provider.getTransactionReceipt(txHash); if (receipt) { console.log('Status:', receipt.status === 1 ? 'Success' : 'Failed'); console.log('Gas Used:', receipt.gasUsed.toString()); console.log('Block:', receipt.blockNumber); console.log('Logs:', receipt.logs.length); // Parse specific events for (const log of receipt.logs) { console.log('Event from:', log.address); } } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x6d26bc1cde1ce724eadaf4448431aa79a323ab58212c4ec39b5569b201ffaee2' receipt = w3.eth.get_transaction_receipt(tx_hash) if receipt: status = 'Success' if receipt['status'] == 1 else 'Failed' print(f'Status: {status}') print(f'Gas Used: {receipt["gasUsed"]}') print(f'Block: {receipt["blockNumber"]}') print(f'Logs: {len(receipt["logs"])}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x6d26bc1cde1ce724eadaf4448431aa79a323ab58212c4ec39b5569b201ffaee2") receipt, err := client.TransactionReceipt(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Status: %d\n", receipt.Status) fmt.Printf("Gas Used: %d\n", receipt.GasUsed) fmt.Printf("Logs: %d\n", len(receipt.Logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash | **Note**: Returns `null` if transaction is not yet mined. ## Related Methods - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details - [`eth_getLogs`](./eth_getLogs) - Query logs by filter --- ## eth_hashrate - Get node hashrate # eth_hashrate Get node hashrate on the Arbitrum network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_hashrate](https://ethereum.org/developers/docs/apis/json-rpc/#eth_hashrate) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_hashrate", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_hashrate', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Arbitrum documentation](/docs/arbitrum).* --- ## eth_maxPriorityFeePerGas - Arbitrum RPC Method # eth_maxPriorityFeePerGas Returns the current recommended priority fee per gas on Arbitrum for EIP-1559 transactions. ## Use Cases - **EIP-1559 transactions** - Set appropriate priority fees - **Transaction acceleration** - Calculate tips for faster inclusion - **Gas optimization** - Balance speed vs cost for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); console.log('Max Priority Fee:', formatUnits(feeData.maxPriorityFeePerGas, 'gwei'), 'Gwei'); console.log('Max Fee Per Gas:', formatUnits(feeData.maxFeePerGas, 'gwei'), 'Gwei'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) priority_fee = w3.eth.max_priority_fee print(f'Max Priority Fee: {w3.from_wei(priority_fee, "gwei")} Gwei') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get legacy gas price - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data --- ## eth_mining - Check if node is mining # eth_mining Check if node is mining on the Arbitrum network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_mining](https://ethereum.org/developers/docs/apis/json-rpc/#eth_mining) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_mining', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Arbitrum documentation](/docs/arbitrum).* --- ## eth_newBlockFilter - Arbitrum RPC Method # eth_newBlockFilter Creates a filter on Arbitrum to notify when a new block arrives. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newBlockFilter', []); // Poll for new blocks const newBlocks = await provider.send('eth_getFilterChanges', [filterId]); console.log('New block hashes:', newBlocks); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_blockNumber`](./eth_blockNumber) - Get current block --- ## eth_newFilter - Arbitrum RPC Method # eth_newFilter Creates a filter object on Arbitrum to notify when state changes (logs). ## Use Cases - **Event monitoring** - Subscribe to contract events - **Real-time updates** - Track events for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications - **Indexing** - Build event indexes incrementally ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block | | `toBlock` | `QUANTITY\|TAG` | No | Ending block | | `address` | `DATA\|Array` | No | Contract address(es) | | `topics` | `Array` | No | Topic filters | ## Request ```json { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0x13867a801e352e219c2d2AC29288Bf086e5C81ef", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0x13867a801e352e219c2d2AC29288Bf086e5C81ef" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Create filter const filterId = await provider.send('eth_newFilter', [{ fromBlock: 'latest', address: '0x13867a801e352e219c2d2AC29288Bf086e5C81ef', topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'] }]); // Poll for changes const changes = await provider.send('eth_getFilterChanges', [filterId]); console.log('New events:', changes); // Cleanup await provider.send('eth_uninstallFilter', [filterId]); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for changes - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_newPendingTransactionFilter - Arbitrum RPC Method # eth_newPendingTransactionFilter Creates a filter on Arbitrum to notify when new pending transactions arrive. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newPendingTransactionFilter', []); // Poll for pending transactions const pendingTxs = await provider.send('eth_getFilterChanges', [filterId]); console.log('Pending transaction hashes:', pendingTxs); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_protocolVersion - Get protocol version # eth_protocolVersion Get protocol version on the Arbitrum network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_protocolVersion](https://ethereum.org/developers/docs/apis/json-rpc/#eth_protocolversion) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_protocolVersion", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_protocolVersion', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Arbitrum documentation](/docs/arbitrum).* --- ## eth_sendRawTransaction - Arbitrum RPC Method # eth_sendRawTransaction Submits a pre-signed transaction for broadcast to Arbitrum. > **Why Arbitrum?** Build on Ethereum's leading Layer 2 with 46% L2 market share and $12B+ TVL with full EVM compatibility, 1.5M daily transactions, and $3B+ DAO treasury for ecosystem growth. ## Use Cases The `eth_sendRawTransaction` method is essential for: - **Broadcasting transactions** - Submit signed transactions to the network - **Wallet operations** - Send native tokens and interact with contracts - **DeFi operations** - Execute swaps, provide liquidity for high-volume DeFi (GMX, Uniswap, Aave), gaming, and cross-chain applications - **Batch operations** - Submit multiple transactions efficiently ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `signedTransactionData` | `DATA` | Yes | The signed transaction data (RLP encoded) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | 32-byte transaction hash | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c808504a817c80082520894..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const wallet = new Wallet('YOUR_PRIVATE_KEY', provider); // Send native tokens async function sendTransaction(to, value) { const tx = await wallet.sendTransaction({ to: to, value: parseEther(value) }); console.log('Transaction hash:', tx.hash); // Wait for confirmation const receipt = await tx.wait(); console.log('Confirmed in block:', receipt.blockNumber); return receipt; } // Send to contract async function sendContractTransaction(contract, method, args, value = '0') { const tx = await contract[method](...args, { value: parseEther(value) }); return await tx.wait(); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) def send_transaction(private_key, to, value_in_ether): account = w3.eth.account.from_key(private_key) # Build transaction tx = { 'nonce': w3.eth.get_transaction_count(account.address), 'to': to, 'value': w3.to_wei(value_in_ether, 'ether'), 'gas': 21000, 'gasPrice': w3.eth.gas_price, 'chainId': w3.eth.chain_id } # Sign transaction signed_tx = account.sign_transaction(tx) # Send transaction tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) print(f'Transaction hash: {tx_hash.hex()}') # Wait for confirmation receipt = w3.eth.wait_for_transaction_receipt(tx_hash) print(f'Confirmed in block: {receipt["blockNumber"]}') return receipt ``` ```go package main "context" "crypto/ecdsa" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY") if err != nil { log.Fatal(err) } publicKey := privateKey.Public() publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey) fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA) nonce, _ := client.PendingNonceAt(context.Background(), fromAddress) value := big.NewInt(1000000000000000000) gasLimit := uint64(21000) gasPrice, _ := client.SuggestGasPrice(context.Background()) toAddress := common.HexToAddress("0x13867a801e352e219c2d2AC29288Bf086e5C81ef") tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil) chainID, _ := client.NetworkID(context.Background()) signedTx, _ := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey) err = client.SendTransaction(context.Background(), signedTx) if err != nil { log.Fatal(err) } fmt.Printf("Transaction hash: %s\n", signedTx.Hash().Hex()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Nonce too low | Transaction nonce already used | | -32000 | Insufficient funds | Account has insufficient balance | | -32000 | Gas too low | Gas limit insufficient | | -32000 | Replacement underpriced | Gas price too low for replacement | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas required - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction result --- ## eth_sendTransaction - Send transaction (wal... # eth_sendTransaction > **Important**: Dwellir's shared Arbitrum endpoints do not manage user private keys. JSON-RPC nodes cannot unlock your account, so `eth_sendTransaction` calls will fail. Sign transactions client-side and broadcast them with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Why this method is disabled on shared nodes - [`eth_sendTransaction` requires the node to hold and unlock the `from` account's private key](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction). - Managed infrastructure providers disable it for security reasons rather than storing customer keys on shared servers (for example, [Infura explicitly blocks the method on shared endpoints](https://docs.infura.io/api/networks/ethereum/json-rpc-methods/eth_sendtransaction)). ## Recommended workflow 1. Build the raw transaction locally with your wallet or SDK. 2. Sign the payload client-side (hardware wallet, custodial service, or library). 3. Submit the signed hex string with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Example response from the shared endpoint ```bash curl -s -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"0x0000000000000000000000000000000000000000"}],"id":1}' ``` ```json {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"unknown account"}} ``` Need help? Contact our [support team](mailto:support@dwellir.com) or use the dedicated [`eth_sendRawTransaction`](./eth_sendRawTransaction) guide. --- ## eth_signTransaction - Sign transaction (rar... # eth_signTransaction Signs a transaction using an unlocked account on the node. **Important**: Most RPC providers don't support this method for security reasons, as it requires private keys to be stored on the server. ## Security Considerations - This method requires an unlocked account on the node - Private keys must be available to the RPC server - Most production RPC providers disable this method - Use client-side signing libraries instead for better security ## Parameters 1. `Object` - The transaction object: - `from`: `DATA`, 20 Bytes - The address the transaction is sent from - `to`: `DATA`, 20 Bytes - (optional) The address the transaction is directed to - `gas`: `QUANTITY` - (optional) Integer of the gas provided for the transaction execution - `gasPrice`: `QUANTITY` - (optional) Integer of the gasPrice used for each paid gas - `value`: `QUANTITY` - (optional) Integer of the value sent with this transaction - `data`: `DATA` - (optional) The compiled code of a contract OR the hash of the invoked method signature and encoded parameters ## Returns `DATA` - The signed transaction data, ready for transmission via `eth_sendRawTransaction`. ## Implementation Example ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_signTransaction", "params": [{ "from": "0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a" }], "id": 1 }' ``` ```javascript const response = await fetch('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_signTransaction', params: [{ from: '0x9b2055d370f73ec7d8a03e965129118dc8f5bf83', to: '0xd46e8dd67c5d32be8058bb8eb970870f07244567', gas: '0x76c0', gasPrice: '0x9184e72a000', value: '0x9184e72a' }], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0xf86c808504a817c8008276c094d46e8dd67c5d32be8058bb8eb970870f072445675849184e72a8001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804" } ``` **Note**: This method is typically not available on hosted RPC providers for security reasons. The response shows a signed transaction ready for broadcast. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Arbitrum documentation](/docs/arbitrum).* --- ## eth_syncing - Arbitrum RPC Method # eth_syncing Returns syncing status of Arbitrum node. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 } ``` ## Returns Returns `false` if not syncing, or an object with sync status. ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const syncing = await provider.send('eth_syncing', []); if (syncing === false) { console.log('Node is fully synced'); } else { console.log('Syncing:', syncing); } ``` ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get current block - [`net_peerCount`](./net_peerCount) - Get peer count --- ## eth_uninstallFilter - Arbitrum RPC Method # eth_uninstallFilter Uninstalls a filter on Arbitrum. Should be called when no longer needed. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID to uninstall | ## Request ```json { "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if filter was found and uninstalled | ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const success = await provider.send('eth_uninstallFilter', [filterId]); console.log('Filter removed:', success); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter --- ## Arbitrum - Leading Ethereum L2 Scaling Solution # Arbitrum - Leading Ethereum Layer 2 Scaling Solution ## Why Build on Arbitrum? Arbitrum is the leading Ethereum Layer 2 scaling solution, processing more transactions than Ethereum mainnet itself. Built with Optimistic Rollup technology, Arbitrum offers: ### 🚀 **Lightning Fast Performance** - **Sub-second block times** - Ultra-fast L2 transaction confirmations - **10-50x lower costs** than Ethereum mainnet - **40,000 TPS capacity** - Massive throughput for any scale ### 🛡️ **Enterprise Security** - **$15B+ secured** - Largest L2 by Total Value Locked - **Ethereum security** - Full fraud proof protection - **Battle-tested** - Processing 1M+ transactions daily since 2021 ### 🌍 **Massive Ecosystem** - **3M+ unique addresses** - Largest L2 user base - **600+ protocols** - Complete DeFi, Gaming, and NFT ecosystem - **Native integrations** - GMX, Uniswap V3, Aave, Curve ## Quick Start with Arbitrum Connect to Arbitrum One in seconds with Dwellir's optimized endpoints: ### Installation & Setup ```javascript // Connect to Arbitrum One mainnet const provider = new JsonRpcProvider( 'https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); // Get the latest block const block = await provider.getBlock('latest'); console.log('Latest block:', block.number); // Query account balance const balance = await provider.getBalance('0x...'); console.log('Balance:', balance.toString()); ``` ```javascript const Web3 = require('web3'); // Connect to Arbitrum One mainnet const web3 = new Web3( 'https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); // Get chain ID to verify connection const chainId = await web3.eth.getChainId(); console.log('Connected to Arbitrum:', chainId === 42161); // Get gas price for optimal transaction pricing const gasPrice = await web3.eth.getGasPrice(); console.log('Current gas price:', gasPrice); ``` ```typescript // Create Arbitrum client const client = createPublicClient({ chain: arbitrum, transport: http('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'), }); // Read contract data const data = await client.readContract({ address: '0x...', abi: contractAbi, functionName: 'balanceOf', args: ['0x...'], }); ``` ## Network Information Chain ID 42161 Mainnet Block Time 2 seconds Average Gas Token ETH Native token RPC Standard Ethereum JSON-RPC 2.0 ## JSON-RPC API Reference Arbitrum supports the full [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/). Access all standard methods plus L2-specific optimizations. ## Common Integration Patterns ### 🔄 Transaction Monitoring Monitor pending and confirmed transactions efficiently: ```javascript // Watch for transaction confirmation async function waitForTransaction(txHash) { const receipt = await provider.waitForTransaction(txHash, 1); // L2 specific: Check L1 data availability if (receipt.l1Fee) { console.log('L1 data cost:', receipt.l1Fee); } return receipt; } ``` ### 💰 Gas Optimization Optimize gas costs on Arbitrum One: ```javascript // Estimate L2 execution gas const l2Gas = await provider.estimateGas(tx); // Get current L1 data fee (Arbitrum specific) const l1DataFee = await provider.send('eth_estimateL1Fee', [tx]); // Total cost = L2 execution + L1 data posting const totalCost = l2Gas + BigInt(l1DataFee); ``` ### 🔍 Event Filtering Efficiently query contract events: ```javascript // Query events with automatic retry and pagination async function getEvents(contract, eventName, fromBlock = 0) { const filter = contract.filters[eventName](); const events = []; const batchSize = 2000; // Arbitrum recommended batch size for (let i = fromBlock; i <= currentBlock; i += batchSize) { const batch = await contract.queryFilter( filter, i, Math.min(i + batchSize - 1, currentBlock) ); events.push(...batch); } return events; } ``` ## Performance Best Practices ### 1. **Batch Requests** Combine multiple RPC calls for optimal performance: ```javascript const batch = [ { method: 'eth_blockNumber', params: [] }, { method: 'eth_gasPrice', params: [] }, { method: 'eth_getBalance', params: [address, 'latest'] } ]; const results = await provider.send(batch); ``` ### 2. **Connection Pooling** Reuse provider instances to minimize connection overhead: ```javascript // Singleton pattern for provider class ArbitrumProvider { static instance = null; static getInstance() { if (!this.instance) { this.instance = new JsonRpcProvider( 'https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); } return this.instance; } } ``` ### 3. **Smart Caching** Cache immutable data to reduce API calls: ```javascript const cache = new Map(); async function getCachedBlockData(blockNumber) { const key = `block_${blockNumber}`; if (!cache.has(key)) { const block = await provider.getBlock(blockNumber); cache.set(key, block); } return cache.get(key); } ``` ## Troubleshooting Common Issues ### Error: "Insufficient funds for L1 fee" Arbitrum transactions require ETH for both L2 execution and L1 data availability: ```javascript // Always account for L1 fees in balance checks const balance = await provider.getBalance(address); const l1Fee = await provider.send('eth_estimateL1Fee', [tx]); const l2Gas = await provider.estimateGas(tx); const totalRequired = l2Gas + BigInt(l1Fee) + tx.value; if (balance < totalRequired) { throw new Error(`Need ${totalRequired - balance} more ETH`); } ``` ### Error: "Transaction underpriced" Arbitrum uses EIP-1559 pricing. Always use dynamic gas pricing: ```javascript // Get current fee data const feeData = await provider.getFeeData(); const tx = { to: recipient, value: amount, maxFeePerGas: feeData.maxFeePerGas, maxPriorityFeePerGas: feeData.maxPriorityFeePerGas, gasLimit: 21000n }; ``` ### Error: "Rate limit exceeded" Implement exponential backoff for resilient applications: ```javascript async function callWithRetry(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error.code === 429 && i < maxRetries - 1) { await new Promise(r => setTimeout(r, 2 ** i * 1000)); } else { throw error; } } } } ``` ## Migration Guide ### From Ethereum Mainnet Moving from L1 to Arbitrum One requires minimal changes: ```javascript // Before (Ethereum) const provider = new JsonRpcProvider('https://eth-rpc.example.com'); // After (Arbitrum) const provider = new JsonRpcProvider( 'https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); // ✅ Smart contracts work identically // ✅ Same tooling and libraries // ⚠️ Different chain ID (42161) // ⚠️ Separate block numbers // ⚠️ L1 data fees apply ``` ## Resources & Tools ### Official Resources - [Arbitrum Documentation](https://docs.arbitrum.io) - [Arbitrum Bridge](https://bridge.arbitrum.io) - [Arbitrum Block Explorer](https://arbiscan.io) ### Developer Tools - [Hardhat Config](https://docs.arbitrum.io/for-devs/quickstart-solidity-hardhat) - [Foundry Setup](https://docs.arbitrum.io/for-devs/quickstart-solidity-hardhat) - [Development Frameworks](https://docs.arbitrum.io/build-decentralized-apps/reference/development-frameworks) ### Need Help? - 📧 **Email**: support@dwellir.com - 📚 **Docs**: You're here! - 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com) --- *Start building on Arbitrum with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)* --- ## net_listening - Arbitrum RPC Method # net_listening Returns `true` if client is actively listening for network connections on Arbitrum. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if listening | ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const listening = await provider.send('net_listening', []); console.log('Node listening:', listening); ``` ## Related Methods - [`net_peerCount`](./net_peerCount) - Get peer count --- ## net_peerCount - Arbitrum RPC Method # net_peerCount Returns number of peers currently connected to Arbitrum client. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Number of connected peers (hexadecimal) | ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const peerCount = await provider.send('net_peerCount', []); console.log('Peer count:', parseInt(peerCount, 16)); ``` ## Related Methods - [`net_listening`](./net_listening) - Check if listening --- ## net_version - Arbitrum RPC Method # net_version Returns the current network ID on Arbitrum. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Network ID as a string | ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const networkId = await provider.send('net_version', []); console.log('Network ID:', networkId); ``` ## Related Methods - [`eth_chainId`](./eth_chainId) - Get chain ID --- ## web3_clientVersion - Arbitrum RPC Method # web3_clientVersion Returns the current client version on Arbitrum. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Client version string | ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const version = await provider.send('web3_clientVersion', []); console.log('Client version:', version); ``` --- ## web3_sha3 - Arbitrum RPC Method # web3_sha3 Returns Keccak-256 (not standard SHA3-256) of the given data on Arbitrum. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `data` | `DATA` | Yes | Data to hash | ## Request ```json { "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Keccak-256 hash of the data | ## Code Examples ```bash curl -X POST https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Using RPC const hash = await provider.send('web3_sha3', ['0x68656c6c6f']); console.log('Hash:', hash); // Using ethers directly (faster) const localHash = keccak256(toUtf8Bytes('hello')); console.log('Local hash:', localHash); ``` --- ## author_pendingExtrinsics - Asset Hub RPC Method # author_pendingExtrinsics Returns all pending extrinsics in the transaction pool on Asset Hub. ## Use Cases - **Mempool monitoring** - Track pending transactions - **Transaction status** - Check if your transaction is pending for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Pool analysis** - Monitor network activity ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "author_pendingExtrinsics", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_pendingExtrinsics", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const pending = await api.rpc.author.pendingExtrinsics(); console.log('Pending extrinsics:', pending.length); pending.forEach((ext, idx) => { console.log(`${idx}: ${ext.method.section}.${ext.method.method}`); }); await api.disconnect(); ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction --- ## author_rotateKeys - Asset Hub RPC Method # author_rotateKeys Generate a new set of session keys on Asset Hub. This method creates fresh cryptographic keys for validator operations and stores them in the node's keystore. The returned keys must be registered on-chain via `session.setKeys`. ## Use Cases - **Validator setup** - Generate initial session keys for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Key rotation** - Periodically rotate keys for security best practices - **Recovery** - Generate new keys after potential key compromise ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | `Bytes` | Concatenated SCALE-encoded public keys for all session key types | ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_rotateKeys", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Generate new session keys const keys = await api.rpc.author.rotateKeys(); console.log('New session keys:', keys.toHex()); // These keys need to be registered on-chain: // api.tx.session.setKeys(keys, proof) await api.disconnect(); ``` ```python url = 'https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'author_rotateKeys', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json() if 'result' in result: session_keys = result['result'] print(f'New session keys: {session_keys}') print('Register these keys using session.setKeys extrinsic') else: print(f"Error: {result.get('error')}") ``` ## Validator Setup Workflow 1. **Generate keys** - Call `author_rotateKeys` on your validator node 2. **Register on-chain** - Submit `session.setKeys(keys, proof)` extrinsic 3. **Wait for session** - Keys become active in the next session 4. **Verify** - Check `session.nextKeys` storage ## Security Considerations - Only call this method on your own validator node - Session keys are stored in the node's keystore - Rotate keys periodically and after any security incident - Never expose this RPC method publicly ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit setKeys transaction - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - View pending transactions --- ## author_submitAndWatchExtrinsic - Asset Hub RPC Method # author_submitAndWatchExtrinsic Submit a signed extrinsic to and subscribe to status updates. This WebSocket method provides real-time feedback on transaction progress from submission through finalization. ## Use Cases - **Transaction tracking** - Monitor extrinsic lifecycle for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **UI feedback** - Show users real-time transaction status - **Confirmation workflows** - Wait for specific finality level before proceeding ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `Bytes` | Yes | SCALE-encoded signed extrinsic | ## Returns Returns a subscription that emits `ExtrinsicStatus` updates: | Status | Description | |--------|-------------| | `future` | In future queue (nonce too high) | | `ready` | In ready queue, waiting for block | | `broadcast` | Broadcast to peers | | `inBlock` | Included in block (hash provided) | | `retracted` | Block retracted (reorg) | | `finalityTimeout` | Finality timeout | | `finalized` | Finalized in block (hash provided) | | `usurped` | Replaced by another extrinsic | | `dropped` | Dropped from pool | | `invalid` | Invalid extrinsic | ## Code Examples ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const keyring = new Keyring({ type: 'sr25519' }); // Create and sign a transfer const sender = keyring.addFromUri('//Alice'); const transfer = api.tx.balances.transferKeepAlive( '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 1000000000000n ); // Submit and watch const unsub = await transfer.signAndSend(sender, ({ status, events }) => { console.log(`Status: ${status.type}`); if (status.isInBlock) { console.log(`Included in block: ${status.asInBlock.toHex()}`); } if (status.isFinalized) { console.log(`Finalized in block: ${status.asFinalized.toHex()}`); unsub(); } }); ``` ```python async def submit_and_watch(signed_extrinsic_hex): uri = 'wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: # Submit and subscribe await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'author_submitAndWatchExtrinsic', 'params': [signed_extrinsic_hex], 'id': 1 })) # Get subscription ID response = json.loads(await ws.recv()) if 'error' in response: print(f"Error: {response['error']}") return sub_id = response['result'] print(f'Watching with subscription: {sub_id}') # Listen for status updates while True: message = json.loads(await ws.recv()) if 'params' in message: status = message['params']['result'] print(f"Status: {status}") # Check for finalization if isinstance(status, dict) and 'finalized' in status: print(f"Finalized in: {status['finalized']}") break # asyncio.run(submit_and_watch('0x...')) ``` ## Status Flow ``` ready → broadcast → inBlock → finalized ↘ retracted (if reorg) ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit without watching (fire-and-forget) - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - View transaction pool - [`payment_queryInfo`](./payment_queryInfo) - Estimate fees before submission --- ## author_submitExtrinsic - Asset Hub RPC Method # author_submitExtrinsic Submit a signed extrinsic to Asset Hub for inclusion in a block. ## Use Cases - **Transaction submission** - Broadcast signed transactions - **dApp interactions** - Execute on-chain operations for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Automated systems** - Submit programmatic transactions ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `String` | Yes | Hex-encoded signed extrinsic | ## Request ```json { "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": ["0x..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Transaction hash | ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": ["0x..."], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const keyring = new Keyring({ type: 'sr25519' }); const sender = keyring.addFromUri('//Alice'); // Build and sign transaction const transfer = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000); const hash = await transfer.signAndSend(sender); console.log('Transaction hash:', hash.toHex()); await api.disconnect(); ``` ## Related Methods - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - Get pending transactions - [`payment_queryInfo`](./payment_queryInfo) - Estimate fees --- ## beefy_getFinalizedHead - Asset Hub RPC Method # beefy_getFinalizedHead Returns the block hash of the latest BEEFY-finalized block on Asset Hub. BEEFY (Bridge Efficiency Enabling Finality Yielder) provides additional finality proofs optimized for light clients and bridges. ## Use Cases - **Cross-chain bridges** - Verify finality proofs for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Light clients** - Efficient finality verification without full GRANDPA proofs - **Trustless bridges** - Generate compact finality proofs for external chains ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | `Hash` | Block hash of the latest BEEFY-finalized block | ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "beefy_getFinalizedHead", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get BEEFY finalized head const beefyHead = await api.rpc.beefy.getFinalizedHead(); console.log('BEEFY finalized:', beefyHead.toHex()); // Compare with GRANDPA finalized const grandpaHead = await api.rpc.chain.getFinalizedHead(); console.log('GRANDPA finalized:', grandpaHead.toHex()); await api.disconnect(); ``` ```python url = 'https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'beefy_getFinalizedHead', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json() if 'result' in result: print(f"BEEFY finalized: {result['result']}") else: print(f"Error: {result.get('error')}") ``` ## BEEFY vs GRANDPA Finality | Aspect | GRANDPA | BEEFY | |--------|---------|-------| | **Purpose** | Primary finality | Bridge-optimized finality | | **Proof size** | Larger (full validator set) | Compact (aggregated signatures) | | **Latency** | Immediate | Slightly delayed | | **Use case** | On-chain finality | Cross-chain bridges | ## Availability BEEFY is enabled on relay chains and some parachains. If BEEFY is not enabled, this method will return an error. ## Related Methods - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - GRANDPA finalized head - [`grandpa_roundState`](./grandpa_roundState) - GRANDPA consensus state - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks --- ## chain_getBlock - Asset Hub RPC Method # chain_getBlock Retrieves complete block information from Asset Hub, including the block header, extrinsics, and justifications. > **Why Asset Hub?** Build on Polkadot's system parachain managing $4.5B+ in DOT tokens, native USDC/USDT, and NFTs with 50-90% lower fees than Relay Chain, fee payment in any supported asset, 1.5M+ accounts migrated, and trustless Ethereum bridge access. ## Use Cases The `chain_getBlock` method is essential for: - **Block explorers** - Display complete block information - **Chain analysis** - Analyze block production patterns - **Transaction verification** - Confirm extrinsic inclusion for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Data indexing** - Build historical blockchain databases ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Hex-encoded block hash. If omitted, returns latest block | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getBlock", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `block` | `Object` | Complete block data | | `block.header` | `Object` | Block header information | | `block.header.parentHash` | `String` | Hash of the parent block | | `block.header.number` | `String` | Block number (hex-encoded) | | `block.header.stateRoot` | `String` | Root of the state trie | | `block.header.extrinsicsRoot` | `String` | Root of the extrinsics trie | | `block.extrinsics` | `Array` | Array of extrinsics in the block | | `justifications` | `Array` | Block justifications (if available) | ## Code Examples ```bash # Get latest block curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": [], "id": 1 }' # Get specific block curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get latest block const latestHash = await api.rpc.chain.getBlockHash(); const latestBlock = await api.rpc.chain.getBlock(latestHash); console.log('Latest block:', { number: latestBlock.block.header.number.toNumber(), hash: latestHash.toHex(), extrinsicsCount: latestBlock.block.extrinsics.length }); // Get specific block const blockHash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'; const block = await api.rpc.chain.getBlock(blockHash); console.log('Block extrinsics:', block.block.extrinsics.length); await api.disconnect(); ``` ```python def get_block(block_hash=None): url = 'https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY' params = [block_hash] if block_hash else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getBlock', 'params': params, 'id': 1 } response = requests.post(url, json=payload) data = response.json() if 'error' in data: raise Exception(f"RPC Error: {data['error']}") return data['result'] # Get latest block latest_block = get_block() block_number = int(latest_block['block']['header']['number'], 16) print(f'Latest block number: {block_number}') # Get specific block specific_block = get_block('0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3') print(f"Extrinsics count: {len(specific_block['block']['extrinsics'])}") ``` ## Related Methods - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number - [`chain_getHeader`](./chain_getHeader) - Get block header only - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get finalized block hash --- ## chain_getBlockHash - Asset Hub RPC Method # chain_getBlockHash Returns the block hash for a given block number on Asset Hub. ## Use Cases - **Historical queries** - Convert block numbers to hashes - **Block navigation** - Navigate blockchain history for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Data indexing** - Build block number to hash mappings ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `Number` | No | Block number. If omitted, returns latest block hash | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getBlockHash", "params": [1000000], "id": 1 } ``` ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlockHash", "params": [1000000], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get hash for specific block number const blockNumber = 1000000; const blockHash = await api.rpc.chain.getBlockHash(blockNumber); console.log(`Block ${blockNumber} hash:`, blockHash.toHex()); await api.disconnect(); ``` ```python def get_block_hash(block_number=None): url = 'https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY' params = [block_number] if block_number is not None else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getBlockHash', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] block_hash = get_block_hash(1000000) print(f'Block hash: {block_hash}') ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get block by hash - [`chain_getHeader`](./chain_getHeader) - Get block header --- ## chain_getFinalizedHead - Asset Hub RPC Method # chain_getFinalizedHead Returns the hash of the last finalized block on Asset Hub. ## Use Cases - **Confirmed state** - Query state that cannot be reverted - **Transaction confirmation** - Verify transaction finality for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Safe checkpoints** - Use finalized blocks for critical operations ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const finalizedHash = await api.rpc.chain.getFinalizedHead(); console.log('Finalized block hash:', finalizedHash.toHex()); // Get finalized block details const block = await api.rpc.chain.getBlock(finalizedHash); console.log('Finalized block number:', block.block.header.number.toNumber()); await api.disconnect(); ``` ```python def get_finalized_head(): url = 'https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'chain_getFinalizedHead', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] finalized_hash = get_finalized_head() print(f'Finalized block hash: {finalized_hash}') ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get block by hash - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number --- ## chain_getHeader - Asset Hub RPC Method # chain_getHeader Returns the block header for a given hash on Asset Hub. ## Use Cases - **Lightweight queries** - Get header without full block data - **Chain synchronization** - Track block production for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Parent chain navigation** - Follow parentHash links ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash. If omitted, returns latest header | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getHeader", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 } ``` ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getHeader", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get latest header const header = await api.rpc.chain.getHeader(); console.log('Block number:', header.number.toNumber()); console.log('Parent hash:', header.parentHash.toHex()); await api.disconnect(); ``` ```python def get_header(block_hash=None): url = 'https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY' params = [block_hash] if block_hash else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getHeader', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] header = get_header() print(f"Block number: {int(header['number'], 16)}") ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get full block with extrinsics - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number --- ## chain_subscribeFinalizedHeads - Asset Hub RPC Method # chain_subscribeFinalizedHeads Subscribe to receive notifications when blocks are finalized on Asset Hub. Finalized blocks are guaranteed to never be reverted, making this essential for applications requiring strong consistency. ## Use Cases - **Exchange deposits** - Only credit funds after finalization for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Bridge operations** - Wait for finality before cross-chain transfers - **Critical state changes** - Ensure irreversibility for important transactions ## Parameters This method takes no parameters. ## Returns Returns a subscription ID. The subscription emits `Header` objects for each finalized block: | Field | Type | Description | |-------|------|-------------| | `parentHash` | `Hash` | Parent block hash | | `number` | `BlockNumber` | Block number | | `stateRoot` | `Hash` | State trie root hash | | `extrinsicsRoot` | `Hash` | Extrinsics trie root hash | | `digest` | `Digest` | Block digest with consensus logs | ## Code Examples ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Subscribe to finalized heads const unsubscribe = await api.rpc.chain.subscribeFinalizedHeads((header) => { console.log(`Finalized block #${header.number}`); console.log(` Hash: ${header.hash.toHex()}`); // Safe to consider this block permanent processConfirmedBlock(header); }); // Later: unsubscribe() ``` ```python async def subscribe_finalized(): uri = 'wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'chain_subscribeFinalizedHeads', 'params': [], 'id': 1 })) response = json.loads(await ws.recv()) sub_id = response['result'] print(f'Subscribed to finalized heads: {sub_id}') while True: message = json.loads(await ws.recv()) if 'params' in message: header = message['params']['result'] block_num = int(header['number'], 16) print(f"Finalized: #{block_num}") asyncio.run(subscribe_finalized()) ``` ## Finality Lag Finalized blocks typically lag behind the best block by a few blocks due to GRANDPA consensus requirements. This is normal and ensures Byzantine fault tolerance. ## Related Methods - [`chain_subscribeNewHeads`](./chain_subscribeNewHeads) - Subscribe to all new blocks (not just finalized) - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get current finalized block hash - [`grandpa_roundState`](./grandpa_roundState) - Monitor GRANDPA consensus progress --- ## chain_subscribeNewHeads - Asset Hub RPC Method # chain_subscribeNewHeads Subscribe to receive notifications when new block headers are produced on Asset Hub. This WebSocket subscription provides real-time updates for each new block. ## Use Cases - **Block monitoring** - Track new blocks in real-time for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Event indexing** - Trigger processing when new blocks arrive - **Chain synchronization** - Keep external systems in sync with the chain ## Parameters This method takes no parameters. ## Returns Returns a subscription ID. The subscription emits `Header` objects for each new block: | Field | Type | Description | |-------|------|-------------| | `parentHash` | `Hash` | Parent block hash | | `number` | `BlockNumber` | Block number | | `stateRoot` | `Hash` | State trie root hash | | `extrinsicsRoot` | `Hash` | Extrinsics trie root hash | | `digest` | `Digest` | Block digest with consensus logs | ## Code Examples ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Subscribe to new heads const unsubscribe = await api.rpc.chain.subscribeNewHeads((header) => { console.log(`New block #${header.number}`); console.log(` Hash: ${header.hash.toHex()}`); console.log(` Parent: ${header.parentHash.toHex()}`); console.log(` State root: ${header.stateRoot.toHex()}`); }); // Later: unsubscribe() ``` ```python async def subscribe_new_heads(): uri = 'wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: # Subscribe to new heads await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'chain_subscribeNewHeads', 'params': [], 'id': 1 })) # Get subscription ID response = json.loads(await ws.recv()) sub_id = response['result'] print(f'Subscribed with ID: {sub_id}') # Listen for new headers while True: message = json.loads(await ws.recv()) if 'params' in message: header = message['params']['result'] print(f"Block #{int(header['number'], 16)}") print(f" Hash: {header['parentHash']}") asyncio.run(subscribe_new_heads()) ``` ## Subscription vs Polling | Approach | Latency | Resource Usage | Use Case | |----------|---------|----------------|----------| | `subscribeNewHeads` | Immediate | Low (push-based) | Real-time monitoring | | Polling `getHeader` | Block time + poll interval | Higher (repeated requests) | Simple integrations | ## Related Methods - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks only - [`chain_getHeader`](./chain_getHeader) - Get a specific block header - [`chain_getBlock`](./chain_getBlock) - Get full block with extrinsics --- ## grandpa_roundState - Asset Hub RPC Method # grandpa_roundState Returns the state of the current GRANDPA finality round on Asset Hub. GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) is the finality gadget used by Substrate chains. ## Use Cases - **Finality monitoring** - Track consensus progress for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Validator analysis** - Monitor prevote/precommit participation - **Chain health checks** - Detect finality delays or stalls ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `setId` | `u64` | Current authority set ID | | `best` | `RoundState` | Best round state | | `background` | `Vec` | Background rounds | ### RoundState Structure | Field | Type | Description | |-------|------|-------------| | `round` | `u64` | Round number | | `totalWeight` | `u64` | Total validator weight | | `thresholdWeight` | `u64` | Weight needed for supermajority | | `prevotes` | `Prevotes` | Prevote information | | `precommits` | `Precommits` | Precommit information | ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "grandpa_roundState", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const roundState = await api.rpc.grandpa.roundState(); console.log('Set ID:', roundState.setId.toString()); console.log('Best round:', roundState.best.round.toString()); console.log('Total weight:', roundState.best.totalWeight.toString()); console.log('Threshold:', roundState.best.thresholdWeight.toString()); await api.disconnect(); ``` ```python url = 'https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'grandpa_roundState', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json()['result'] print(f"Set ID: {result['setId']}") print(f"Round: {result['best']['round']}") print(f"Total weight: {result['best']['totalWeight']}") ``` ## Understanding GRANDPA Rounds 1. **Prevote phase** - Validators vote on best block they've seen 2. **Precommit phase** - Validators commit to finalize if supermajority prevoted 3. **Finalization** - Block is finalized when 2/3+ weight precommits ## Related Methods - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get current finalized hash - [`beefy_getFinalizedHead`](./beefy_getFinalizedHead) - BEEFY finality (if enabled) --- ## Asset Hub - Polkadot Asset Management # Asset Hub - Polkadot's Native Asset Management Parachain ## Why Build on Asset Hub? Asset Hub is Polkadot's native system parachain designed for efficient asset creation, management, and transfers. As a core infrastructure parachain, Asset Hub provides low-cost asset operations and seamless integration with the broader Polkadot ecosystem. ### 🏦 **Native Asset Management** - **Asset creation** - Mint fungible and non-fungible tokens natively - **Low transaction costs** - Optimized for high-frequency asset operations - **Cross-chain transfers** - Seamless XCM integration with all parachains - **DOT integration** - Native support for Polkadot's main token ### 🌐 **Multi-Network Support** - **Polkadot Asset Hub** - Main network for production applications - **Kusama Asset Hub** - Canary network for testing and experimentation - **Westend Asset Hub** - Test network for development and staging - **Paseo Asset Hub** - Community-operated testnet tracking Polkadot releases - **Polkadot Sidecar** - Managed Sidecar API surface for REST-friendly data access ### ⚡ **Performance & Efficiency** - **Fast finality** - ~6 second block times with instant finality - **Minimal fees** - Optimized for micro-transactions and asset operations - **Substrate runtime** - Built on battle-tested Polkadot technology - **XCM native** - First-class cross-chain messaging support ## Quick Start with Asset Hub Connect to Asset Hub networks with Dwellir's reliable endpoints: :::info Multi-Network Support Dwellir serves Asset Hub across every public Polkadot environment: - **Asset Hub Polkadot** – `wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY` - **Asset Hub Kusama** – `wss://api-asset-hub-kusama.n.dwellir.com/YOUR_API_KEY` - **Asset Hub Westend** – `https://api-asset-hub-westend.n.dwellir.com/YOUR_API_KEY` - **Asset Hub Paseo** – `https://api-asset-hub-paseo.n.dwellir.com/YOUR_API_KEY` - **Polkadot Sidecar** – `https://api-asset-hub-polkadot-sidecar.n.dwellir.com/YOUR_API_KEY` ::: The Sidecar tab exposes a managed Polkadot Sidecar deployment so you can issue REST requests (for example `/accounts` or `/blocks`) without running additional infrastructure. ### Installation & Setup ```bash # Get chain information curl -X POST https://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 }' # Get latest finalized block curl -X POST https://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 }' # Query account balance curl -X POST https://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getStorage", "params": ["0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9"], "id": 1 }' ``` ```typescript // Connect to Asset Hub Polkadot const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Verify connection const chain = await api.rpc.system.chain(); const version = await api.rpc.system.version(); console.log(`Connected to ${chain} v${version}`); // Get the latest block const hash = await api.rpc.chain.getFinalizedHead(); const block = await api.rpc.chain.getBlock(hash); console.log(`Latest block: #${block.block.header.number}`); // Query account balance const account = 'ACCOUNT_ADDRESS'; const balance = await api.query.system.account(account); console.log(`Free balance: ${balance.data.free.toString()}`); ``` ```typescript // Connect to Asset Hub const client = createClient({ chainSpec: { genesisHash: '0x68d56f15f85d3136970ec16946040bc1752654e906147f7e43e9d539d7c3de2f', rpcUrls: ['https://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'] } }); // Query chain information const chainInfo = await client.getChainHead(); console.log('Current head:', chainInfo.hash); // Get asset information const assetId = 1000; // USDT on Asset Hub const assetDetails = await client.query({ type: 'assets', method: 'asset', args: [assetId] }); ``` ```python from substrateinterface import SubstrateInterface # Connect to Asset Hub Polkadot substrate = SubstrateInterface( url="wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY" ) # Get chain information chain_name = substrate.rpc_request("system_chain", []) print(f"Connected to: {chain_name['result']}") # Query account balance account_info = substrate.query( module='System', storage_function='Account', params=['ACCOUNT_ADDRESS'] ) print(f"Free balance: {account_info['data']['free']}") # Query asset details asset_id = 1000 # USDT asset_details = substrate.query( module='Assets', storage_function='Asset', params=[asset_id] ) if asset_details: print(f"Asset name: {asset_details['name']}") print(f"Asset symbol: {asset_details['symbol']}") print(f"Decimals: {asset_details['decimals']}") ``` ## Network Information Genesis Hash 0x68d56f15... Polkadot Asset Hub Block Time 6 seconds Instant finality Native Token DOT Polkadot token Parachain ID 1000 System parachain :::info Network Details - **Polkadot Asset Hub Parachain ID**: 1000 - **Kusama Asset Hub Parachain ID**: 1000 - **Westend Asset Hub Parachain ID**: 1000 - **Native Token**: DOT (Polkadot), KSM (Kusama), WND (Westend) - **Consensus**: Nominated Proof of Stake (via Relay Chain) - **Finality**: Instant (via GRANDPA finality gadget) ::: ## Core Features ### 🪙 **Asset Management** Create and manage fungible assets with native support: ```typescript // Create a new asset const createAsset = async (api, signer, assetId, admin, minBalance) => { const tx = api.tx.assets.create(assetId, admin, minBalance); const hash = await tx.signAndSend(signer); return hash; }; // Set asset metadata const setMetadata = async (api, signer, assetId, name, symbol, decimals) => { const tx = api.tx.assets.setMetadata(assetId, name, symbol, decimals); const hash = await tx.signAndSend(signer); return hash; }; // Mint assets const mintAsset = async (api, signer, assetId, beneficiary, amount) => { const tx = api.tx.assets.mint(assetId, beneficiary, amount); const hash = await tx.signAndSend(signer); return hash; }; ``` ### 🎨 **NFT Support** Work with non-fungible tokens using the Uniques pallet: ```typescript // Create an NFT collection const createCollection = async (api, signer, collectionId, admin) => { const tx = api.tx.uniques.create(collectionId, admin); const hash = await tx.signAndSend(signer); return hash; }; // Mint an NFT const mintNFT = async (api, signer, collectionId, itemId, owner) => { const tx = api.tx.uniques.mint(collectionId, itemId, owner); const hash = await tx.signAndSend(signer); return hash; }; // Set NFT metadata const setNFTMetadata = async (api, signer, collectionId, itemId, data) => { const tx = api.tx.uniques.setMetadata(collectionId, itemId, data, false); const hash = await tx.signAndSend(signer); return hash; }; ``` ### 🌉 **Cross-Chain Transfers (XCM)** Send assets across the Polkadot ecosystem: ```typescript // Transfer DOT to another parachain const xcmTransfer = async (api, signer, dest, beneficiary, amount) => { const destination = { V3: { parents: 1, interior: { X1: { Parachain: dest // Destination parachain ID } } } }; const account = { V3: { parents: 0, interior: { X1: { AccountId32: { network: null, id: beneficiary } } } } }; const assets = { V3: [ { id: { Concrete: { parents: 1, interior: 'Here' } }, fun: { Fungible: amount } } ] }; const tx = api.tx.polkadotXcm.limitedReserveTransferAssets( destination, account, assets, 0, 'Unlimited' ); const hash = await tx.signAndSend(signer); return hash; }; ``` ## Common Integration Patterns ### 🔄 **Multi-Asset Wallet** Build wallets supporting multiple Asset Hub tokens: ```typescript class AssetHubWallet { constructor(api, address) { this.api = api; this.address = address; } async getAllBalances() { const balances = {}; // Get DOT balance const account = await this.api.query.system.account(this.address); balances.DOT = { free: account.data.free.toString(), reserved: account.data.reserved.toString(), symbol: 'DOT', decimals: 10 }; // Get asset balances const assets = await this.api.query.assets.account.entries(this.address); for (const [key, balance] of assets) { const assetId = key.args[0].toString(); const metadata = await this.api.query.assets.metadata(assetId); balances[metadata.symbol.toString()] = { free: balance.unwrap().balance.toString(), assetId, symbol: metadata.symbol.toString(), decimals: metadata.decimals.toNumber() }; } return balances; } async transferAsset(assetId, recipient, amount) { let tx; if (assetId === 'DOT') { // Native DOT transfer tx = this.api.tx.balances.transferKeepAlive(recipient, amount); } else { // Asset transfer tx = this.api.tx.assets.transferKeepAlive(assetId, recipient, amount); } return tx; } } ``` ### 📊 **Asset Analytics** Track asset metrics and usage: ```typescript class AssetAnalytics { constructor(api) { this.api = api; } async getAssetInfo(assetId) { const [details, metadata] = await Promise.all([ this.api.query.assets.asset(assetId), this.api.query.assets.metadata(assetId) ]); if (details.isNone) { throw new Error(`Asset ${assetId} not found`); } const assetDetails = details.unwrap(); return { id: assetId, name: metadata.name.toString(), symbol: metadata.symbol.toString(), decimals: metadata.decimals.toNumber(), supply: assetDetails.supply.toString(), accounts: assetDetails.accounts.toNumber(), sufficients: assetDetails.sufficients.toNumber(), owner: assetDetails.owner.toString(), issuer: assetDetails.issuer.toString(), admin: assetDetails.admin.toString(), freezer: assetDetails.freezer.toString(), minBalance: assetDetails.minBalance.toString(), isSufficient: assetDetails.isSufficient.toBoolean() }; } async getTopAssets(limit = 10) { const assets = []; // Get all assets const assetEntries = await this.api.query.assets.asset.entries(); for (const [key, details] of assetEntries) { const assetId = key.args[0].toString(); const metadata = await this.api.query.assets.metadata(assetId); assets.push({ id: assetId, symbol: metadata.symbol.toString(), supply: details.unwrap().supply.toString(), accounts: details.unwrap().accounts.toNumber() }); } // Sort by number of accounts (popularity) return assets .sort((a, b) => b.accounts - a.accounts) .slice(0, limit); } } ``` ### 🔍 **NFT Marketplace Integration** Integrate with NFT collections: ```typescript class NFTCollection { constructor(api, collectionId) { this.api = api; this.collectionId = collectionId; } async getCollectionInfo() { const [details, metadata] = await Promise.all([ this.api.query.uniques.class(this.collectionId), this.api.query.uniques.classMetadataOf(this.collectionId) ]); return { id: this.collectionId, owner: details.unwrap().owner.toString(), issuer: details.unwrap().issuer.toString(), admin: details.unwrap().admin.toString(), freezer: details.unwrap().freezer.toString(), totalDeposit: details.unwrap().totalDeposit.toString(), freeHolding: details.unwrap().freeHolding.toBoolean(), instances: details.unwrap().instances.toNumber(), instanceMetadatas: details.unwrap().instanceMetadatas.toNumber(), attributes: details.unwrap().attributes.toNumber(), isFrozen: details.unwrap().isFrozen.toBoolean(), metadata: metadata.isSome ? metadata.unwrap().data.toString() : null }; } async getAllItems() { const items = []; const itemEntries = await this.api.query.uniques.asset.entries(); for (const [key, details] of itemEntries) { const [collectionId, itemId] = key.args; if (collectionId.toString() === this.collectionId.toString()) { const metadata = await this.api.query.uniques.instanceMetadataOf( collectionId, itemId ); items.push({ collectionId: collectionId.toString(), itemId: itemId.toString(), owner: details.unwrap().owner.toString(), approved: details.unwrap().approved.isSome ? details.unwrap().approved.unwrap().toString() : null, isFrozen: details.unwrap().isFrozen.toBoolean(), deposit: details.unwrap().deposit.toString(), metadata: metadata.isSome ? metadata.unwrap().data.toString() : null }); } } return items; } } ``` ## Performance Optimization ### 1. **Efficient State Queries** Batch multiple queries for better performance: ```typescript async function batchQueries(api, queries) { const results = await Promise.all(queries.map(query => { if (query.type === 'storage') { return api.query[query.module][query.method](...query.args); } else if (query.type === 'rpc') { return api.rpc[query.module][query.method](...query.args); } })); return results; } // Example usage const queries = [ { type: 'storage', module: 'system', method: 'account', args: [address] }, { type: 'storage', module: 'assets', method: 'asset', args: [1000] }, { type: 'rpc', module: 'chain', method: 'getFinalizedHead', args: [] } ]; const [account, asset, head] = await batchQueries(api, queries); ``` ### 2. **Event Subscription** Monitor blockchain events efficiently: ```typescript async function subscribeToAssetEvents(api, callback) { const unsubscribe = await api.query.system.events((events) => { events.forEach((record) => { const { event } = record; if (api.events.assets.Transferred.is(event)) { const [assetId, from, to, amount] = event.data; callback({ type: 'AssetTransferred', assetId: assetId.toString(), from: from.toString(), to: to.toString(), amount: amount.toString() }); } else if (api.events.assets.Created.is(event)) { const [assetId, creator, owner] = event.data; callback({ type: 'AssetCreated', assetId: assetId.toString(), creator: creator.toString(), owner: owner.toString() }); } }); }); return unsubscribe; } ``` ## Developer Resources ### 🔗 **Official Resources** - [Polkadot Developer Docs](https://docs.polkadot.com/polkadot-protocol/architecture/system-chains/asset-hub/) - [Asset Hub Wiki](https://wiki.polkadot.com/learn/learn-assets/) - [Substrate Documentation](https://docs.substrate.io/) ### 🛠 **Developer Tools** - [Polkadot.js Apps](https://polkadot.js.org/apps/) - Web interface for Asset Hub - [Polkadot.js API](https://polkadot.js.org/docs/) - JavaScript SDK - [Subxt](https://github.com/paritytech/subxt) - Rust SDK for Substrate chains - [py-substrate-interface](https://github.com/polkascan/py-substrate-interface) - Python SDK ### 🌐 **Block Explorers** - [Polkadot.js Apps Explorer](https://polkadot.js.org/apps/#/explorer) - [Subscan Asset Hub](https://assethub-polkadot.subscan.io/) ### 💡 **Example Projects** - [Asset Transfer Tools](https://github.com/paritytech/asset-transfer-api) - [XCM Tools](https://docs.polkadot.com/develop/toolkit/interoperability/xcm-tools/) - [Asset Hub Examples](https://github.com/bee344/asset-hub-examples) ### Need Help? - 📧 **Email**: support@dwellir.com - 📚 **Polkadot Wiki**: [wiki.polkadot.network](https://wiki.polkadot.network) - 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com) - 💬 **Community**: [Polkadot Discord](https://discord.gg/polkadot) --- *Build the future of cross-chain asset management on Asset Hub with Dwellir's reliable infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)* --- ## payment_queryFeeDetails - Asset Hub RPC Method # payment_queryFeeDetails Returns a detailed breakdown of fees for a given extrinsic on Asset Hub. Unlike `payment_queryInfo` which returns the total fee, this method separates the fee into its component parts. ## Use Cases - **Fee analysis** - Understand fee composition for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Optimization** - Identify which fee component dominates costs - **Debugging** - Diagnose unexpected fee amounts ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `Bytes` | Yes | SCALE-encoded extrinsic (signed or unsigned) | | `blockHash` | `Hash` | No | Block hash for fee calculation context | ## Returns | Field | Type | Description | |-------|------|-------------| | `inclusionFee` | `Option` | Fee details (null for unsigned extrinsics) | ### InclusionFee Structure | Field | Type | Description | |-------|------|-------------| | `baseFee` | `Balance` | Fixed base fee per extrinsic | | `lenFee` | `Balance` | Fee based on encoded extrinsic length | | `adjustedWeightFee` | `Balance` | Fee based on execution weight | ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "payment_queryFeeDetails", "params": ["0x...encodedExtrinsic"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Create a sample transfer const tx = api.tx.balances.transferKeepAlive( '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 1000000000000n ); // Get fee details const feeDetails = await api.rpc.payment.queryFeeDetails(tx.toHex()); if (feeDetails.inclusionFee.isSome) { const fee = feeDetails.inclusionFee.unwrap(); console.log('Base fee:', fee.baseFee.toString()); console.log('Length fee:', fee.lenFee.toString()); console.log('Weight fee:', fee.adjustedWeightFee.toString()); } await api.disconnect(); ``` ```python url = 'https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY' # Replace with actual encoded extrinsic encoded_extrinsic = '0x...' payload = { 'jsonrpc': '2.0', 'method': 'payment_queryFeeDetails', 'params': [encoded_extrinsic], 'id': 1 } response = requests.post(url, json=payload) result = response.json()['result'] if result['inclusionFee']: fee = result['inclusionFee'] print(f"Base fee: {fee['baseFee']}") print(f"Length fee: {fee['lenFee']}") print(f"Weight fee: {fee['adjustedWeightFee']}") ``` ## Fee Components Explained | Component | Calculation | Optimization | |-----------|-------------|--------------| | **Base fee** | Fixed per extrinsic | Batch calls to share base fee | | **Length fee** | `length * lengthToFee` | Minimize call data size | | **Weight fee** | `weight * weightToFee` | Choose efficient operations | ## Related Methods - [`payment_queryInfo`](./payment_queryInfo) - Get total fee estimate - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction - [`state_call`](./state_call) - Call TransactionPaymentApi directly --- ## payment_queryInfo - Asset Hub RPC Method # payment_queryInfo Estimates the fee for an extrinsic on Asset Hub. ## Use Cases - **Fee estimation** - Calculate transaction costs before sending - **UI display** - Show fees to users for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Transaction planning** - Ensure sufficient funds ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `String` | Yes | Hex-encoded unsigned extrinsic | | `blockHash` | `String` | No | Block hash for fee calculation | ## Request ```json { "jsonrpc": "2.0", "method": "payment_queryInfo", "params": ["0x..."], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `weight` | `Object` | Transaction weight | | `class` | `String` | Dispatch class | | `partialFee` | `String` | Estimated fee | ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "payment_queryInfo", "params": ["0x..."], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Create transfer (unsigned for estimation) const transfer = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000); const info = await transfer.paymentInfo('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'); console.log('Partial fee:', info.partialFee.toHuman()); await api.disconnect(); ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction --- ## rpc_methods - Asset Hub RPC Method # rpc_methods Returns a list of all RPC methods available on Asset Hub. ## Use Cases - **API discovery** - List all available methods - **Compatibility checking** - Verify method availability for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Documentation** - Auto-generate method lists ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const methods = await api.rpc.rpc.methods(); console.log('Available methods:', methods.methods.length); await api.disconnect(); ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## state_call - Asset Hub RPC Method # state_call Calls a runtime API method on Asset Hub. ## Use Cases - **Runtime computations** - Execute runtime logic without transactions - **Account queries** - Use AccountNonceApi for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Fee estimation** - Use TransactionPaymentApi ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `method` | `String` | Yes | Runtime API method name | | `data` | `String` | Yes | SCALE-encoded call data | | `blockHash` | `String` | No | Block hash for historical call | ## Request ```json { "jsonrpc": "2.0", "method": "state_call", "params": ["AccountNonceApi_account_nonce", "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"], "id": 1 } ``` ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_call", "params": ["AccountNonceApi_account_nonce", "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get account nonce via runtime API const account = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const result = await api.call.accountNonceApi.accountNonce(account); console.log('Account nonce:', result.toNumber()); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Query storage - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## state_getKeys - JSON-RPC Method ## Description Returns storage keys that match a given prefix. This JSON-RPC method is useful for discovering all storage entries under a specific module or querying multiple related storage items. Be cautious with broad prefixes as they may return large result sets. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `prefix` | string | Yes | Hex-encoded storage key prefix to match | | `blockHash` | string | No | Block hash to query at. If omitted, uses the latest block | ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | array | Array of hex-encoded storage keys matching the prefix | ## Request Example ```json { "jsonrpc": "2.0", "method": "state_getKeys", "params": [ "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9" ], "id": 1 } ``` ## Response Example ```json { "jsonrpc": "2.0", "result": [ "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9de1e86a9a8c739864cf3cc5ec2bea59fd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d", "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da94f9aea1afa791265fae359272badc1cf8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48" ], "id": 1 } ``` ## Code Examples ```python from substrateinterface import SubstrateInterface def get_storage_keys(prefix, block_hash=None): url = "https://api-asset-hub-polkadot.n.dwellir.com" headers = { "Content-Type": "application/json" } params = [prefix, block_hash] if block_hash else [prefix] payload = { "jsonrpc": "2.0", "method": "state_getKeys", "params": params, "id": 1 } response = requests.post(url, headers=headers, data=json.dumps(payload)) return response.json()["result"] # Example: Get all validator preferences keys def get_validator_keys(): # Staking.Validators storage prefix prefix = "0x5f3e4907f716ac89b6347d15ececedca9320c2dc4f5d7af5b320b04e2d1a3ff3" keys = get_storage_keys(prefix) print(f"Found {len(keys)} validator preference entries") for key in keys: # Extract validator account from key validator_account = key[-64:] print(f"Validator: 0x{validator_account}") return keys # Example: Query all keys under a module def get_module_keys(module_prefix): keys = get_storage_keys(module_prefix) # Group keys by storage item storage_items = {} for key in keys: # Storage keys typically have a fixed prefix per item item_prefix = key[:66] # First 33 bytes (66 hex chars) if item_prefix not in storage_items: storage_items[item_prefix] = [] storage_items[item_prefix].append(key) return storage_items ``` ```javascript const getStorageKeys = async (prefix, blockHash = null) => { const params = blockHash ? [prefix, blockHash] : [prefix]; const response = await fetch('https://api-asset-hub-polkadot.n.dwellir.com', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'state_getKeys', params: params, id: 1 }) }); const data = await response.json(); return data.result; }; // Get all account keys (System.Account storage) const accountPrefix = '0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9'; const accountKeys = await getStorageKeys(accountPrefix); console.log(`Found ${accountKeys.length} accounts`); // Extract account addresses from keys accountKeys.forEach(key => { // The account address is the last 32 bytes of the key const addressHex = key.slice(-64); console.log('Account key:', key); console.log('Address portion:', addressHex); }); ``` ```typescript async function queryStorageKeys() { const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com'); const api = await ApiPromise.create({ provider }); // Method 1: Using high-level API to get keys const accountKeys = await api.query.system.account.keys(); console.log('Account addresses:', accountKeys.map(k => k.toHuman())); // Method 2: Using low-level RPC for custom prefixes const prefix = api.query.system.account.keyPrefix(); const keys = await api.rpc.state.getKeys(prefix); console.log(`Found ${keys.length} account storage keys`); // Method 3: Get keys for a specific map entry const validatorKeys = await api.query.staking.validators.keys(); console.log('Active validators:', validatorKeys.length); // Process keys to extract data for (const key of keys) { // Decode the storage key const keyHex = key.toHex(); console.log('Storage key:', keyHex); // Get the value for this key const value = await api.rpc.state.getStorage(key); console.log('Storage value:', value.toHex()); } await api.disconnect(); } // Advanced: Query keys with pagination async function getKeysPagedExample() { const api = await ApiPromise.create({ provider: new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com') }); const prefix = api.query.system.account.keyPrefix(); const pageSize = 100; let startKey = prefix; let allKeys = []; while (true) { // Note: state_getKeysPaged is used for pagination const keys = await api.rpc.state.getKeysPaged(prefix, pageSize, startKey); if (keys.length === 0) break; allKeys = allKeys.concat(keys); startKey = keys[keys.length - 1]; console.log(`Fetched ${keys.length} keys, total: ${allKeys.length}`); if (keys.length < pageSize) break; } console.log(`Total keys found: ${allKeys.length}`); await api.disconnect(); } ``` ## Common Storage Prefixes | Module | Storage Item | Prefix (example) | |--------|--------------|------------------| | System | Account | `0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9` | | Balances | TotalIssuance | `0xc2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80` | | Staking | Validators | `0x5f3e4907f716ac89b6347d15ececedca9320c2dc4f5d7af5b320b04e2d1a3ff3` | | Session | NextKeys | `0xcec5070d609dd3497f72bde07fc96ba0e0cdd062e6eaf24295ad4ccfc41d4609` | ## Batch Query Example ```javascript // Efficiently query multiple storage values async function batchQueryStorage(api, keys) { // Get all values in a single call const values = await api.rpc.state.queryStorageAt(keys); const results = {}; keys.forEach((key, index) => { results[key.toString()] = values[index]; }); return results; } // Example usage const keys = await getStorageKeys(accountPrefix); const values = await batchQueryStorage(api, keys.slice(0, 10)); console.log('Batch query results:', values); ``` ## Use Cases 1. **Account Discovery**: Find all accounts with balances 2. **Validator Enumeration**: List all validators in the network 3. **Storage Analysis**: Analyze storage usage by module 4. **Migration Scripts**: Iterate over storage for upgrades 5. **Indexing**: Build indexes of on-chain data ## Notes - Large prefixes may return many keys - use pagination when available - Keys are returned in lexicographical order - The prefix must be hex-encoded - Consider using `state_getKeysPaged` for large datasets - Storage keys include both the storage prefix and the key data ## Related Methods - [`state_getKeysPaged`](./state_getKeysPaged) - Get keys with pagination - [`state_getStorage`](./state_getStorage) - Get storage value - [`state_getMetadata`](./state_getMetadata) - Get metadata to decode keys --- ## state_getKeysPaged - Asset Hub RPC Method # state_getKeysPaged Returns storage keys with pagination on Asset Hub. ## Use Cases - **Storage iteration** - Enumerate storage map entries - **Data export** - Bulk export chain data for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Account enumeration** - List all accounts ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `prefix` | `String` | Yes | Storage key prefix | | `count` | `Number` | Yes | Maximum keys to return | | `startKey` | `String` | No | Key to start after | | `blockHash` | `String` | No | Block hash for historical query | ## Request ```json { "jsonrpc": "2.0", "method": "state_getKeysPaged", "params": ["0x...", 100], "id": 1 } ``` ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getKeysPaged", "params": ["0x26aa394eea5630e07c48ae0c9558cef7", 100], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get all accounts (paginated) const keys = await api.rpc.state.getKeysPaged( api.query.system.account.keyPrefix(), 100 ); console.log('Found accounts:', keys.length); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Get storage value - [`state_queryStorageAt`](./state_queryStorageAt) - Batch storage query --- ## state_getMetadata - Asset Hub RPC Method # state_getMetadata Returns the runtime metadata on Asset Hub. ## Use Cases - **Runtime introspection** - Discover available pallets and calls - **Extrinsic building** - Get call and type information for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Storage key generation** - Build storage keys from metadata - **Client generation** - Auto-generate typed APIs ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash for historical metadata | ## Request ```json { "jsonrpc": "2.0", "method": "state_getMetadata", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getMetadata", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get runtime metadata const metadata = await api.rpc.state.getMetadata(); // List available pallets const pallets = metadata.asLatest.pallets.map(p => p.name.toString()); console.log('Available pallets:', pallets); // Get specific pallet info const systemPallet = metadata.asLatest.pallets.find(p => p.name.toString() === 'System'); console.log('System pallet calls:', systemPallet.calls.isSome ? 'Available' : 'None'); await api.disconnect(); ``` ```python def get_metadata(): url = 'https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'state_getMetadata', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] metadata_hex = get_metadata() print(f'Metadata length: {len(metadata_hex)} bytes') ``` ## Related Methods - [`state_getRuntimeVersion`](./state_getRuntimeVersion) - Get runtime version - [`state_getStorage`](./state_getStorage) - Query storage --- ## state_getRuntimeVersion - Asset Hub RPC Method # state_getRuntimeVersion Returns the runtime version on Asset Hub. ## Use Cases - **Version checking** - Verify runtime compatibility - **Upgrade detection** - Monitor for runtime upgrades on native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Client compatibility** - Ensure API compatibility ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash for historical version | ## Request ```json { "jsonrpc": "2.0", "method": "state_getRuntimeVersion", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getRuntimeVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const version = await api.rpc.state.getRuntimeVersion(); console.log('Spec name:', version.specName.toString()); console.log('Spec version:', version.specVersion.toNumber()); console.log('Impl version:', version.implVersion.toNumber()); await api.disconnect(); ``` ```python def get_runtime_version(): url = 'https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'state_getRuntimeVersion', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] version = get_runtime_version() print(f"Spec: {version['specName']} v{version['specVersion']}") ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata - [`system_version`](./system_version) - Get node version --- ## state_getStorage - Asset Hub RPC Method # state_getStorage Returns a storage entry at a specific key on Asset Hub. > **Why Asset Hub?** Build on Polkadot's system parachain managing $4.5B+ in DOT tokens, native USDC/USDT, and NFTs with 50-90% lower fees than Relay Chain, fee payment in any supported asset, 1.5M+ accounts migrated, and trustless Ethereum bridge access. ## Use Cases - **State queries** - Read on-chain storage values - **Account balances** - Query account data for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Pallet storage** - Access runtime storage items - **Historical state** - Query state at specific blocks ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `key` | `String` | Yes | Storage key (hex-encoded) | | `blockHash` | `String` | No | Block hash for historical query | ## Request ```json { "jsonrpc": "2.0", "method": "state_getStorage", "params": [""], "id": 1 } ``` ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getStorage", "params": [""], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query account balance const account = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const accountInfo = await api.query.system.account(account); console.log('Free balance:', accountInfo.data.free.toString()); // Query at specific block const blockHash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'; const historicalBalance = await api.query.system.account.at(blockHash, account); console.log('Historical balance:', historicalBalance.data.free.toString()); await api.disconnect(); ``` ```python def get_storage(key, block_hash=None): url = 'https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY' params = [key] if block_hash is None else [key, block_hash] payload = { 'jsonrpc': '2.0', 'method': 'state_getStorage', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] # Query :code storage (runtime wasm) storage_key = '' value = get_storage(storage_key) print(f'Storage value: {value[:66]}...' if value else 'None') ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata - [`state_getKeysPaged`](./state_getKeysPaged) - Enumerate storage keys --- ## state_queryStorageAt - Asset Hub RPC Method # state_queryStorageAt Query multiple storage keys at a specific block on Asset Hub. ## Use Cases - **Batch queries** - Efficiently query multiple storage items - **Snapshot state** - Get consistent multi-key state for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Data analysis** - Compare storage across blocks ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `keys` | `Array` | Yes | Array of storage keys | | `blockHash` | `String` | No | Block hash for query | ## Request ```json { "jsonrpc": "2.0", "method": "state_queryStorageAt", "params": [[""]], "id": 1 } ``` ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_queryStorageAt", "params": [[""]], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query multiple accounts at once const accounts = ['5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY']; const entries = await api.query.system.account.multi(accounts); entries.forEach((info, idx) => { console.log(`Account ${idx}: ${info.data.free.toString()}`); }); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Single storage query - [`state_getKeysPaged`](./state_getKeysPaged) - Enumerate keys --- ## system_chain - Asset Hub RPC Method # system_chain Returns the chain name on Asset Hub. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const chain = await api.rpc.system.chain(); console.log('Chain:', chain.toString()); await api.disconnect(); ``` ## Related Methods - [`system_name`](./system_name) - Get node implementation name - [`system_version`](./system_version) - Get node version --- ## system_health - Asset Hub RPC Method # system_health Returns the health status of the Asset Hub node. ## Use Cases - **Health checks** - Monitor node availability - **Load balancing** - Route traffic based on health for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **Sync status** - Verify node is synced ## Parameters This method accepts no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `peers` | `Number` | Connected peer count | | `isSyncing` | `Boolean` | Whether node is syncing | | `shouldHavePeers` | `Boolean` | Whether node should have peers | ## Request ```json { "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const health = await api.rpc.system.health(); console.log('Peers:', health.peers.toNumber()); console.log('Is syncing:', health.isSyncing.isTrue); await api.disconnect(); ``` ```python def get_health(): url = 'https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'system_health', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] health = get_health() print(f"Peers: {health['peers']}") print(f"Syncing: {health['isSyncing']}") ``` ## Related Methods - [`system_version`](./system_version) - Get node version - [`system_chain`](./system_chain) - Get chain name --- ## system_name - Asset Hub RPC Method # system_name Returns the node implementation name on Asset Hub. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_name", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_name", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const name = await api.rpc.system.name(); console.log('Node name:', name.toString()); await api.disconnect(); ``` ## Related Methods - [`system_version`](./system_version) - Get node version - [`system_chain`](./system_chain) - Get chain name --- ## system_properties - Asset Hub RPC Method # system_properties Returns chain properties including token symbol and decimals on Asset Hub. ## Use Cases - **Token formatting** - Get decimals and symbol for native stablecoin transfers (USDC, USDT), DOT staking and governance, and cross-chain asset management via XCM - **UI configuration** - Configure wallets and dApps - **Address formatting** - Get SS58 prefix ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_properties", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_properties", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const props = await api.rpc.system.properties(); console.log('Token symbol:', props.tokenSymbol.toString()); console.log('Token decimals:', props.tokenDecimals.toString()); console.log('SS58 prefix:', props.ss58Format.toString()); await api.disconnect(); ``` ## Related Methods - [`system_chain`](./system_chain) - Get chain name - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## system_version - Asset Hub RPC Method # system_version Returns the node implementation version on Asset Hub. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_version", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-asset-hub-polkadot.n.dwellir.com//YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_version", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-asset-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const version = await api.rpc.system.version(); console.log('Version:', version.toString()); await api.disconnect(); ``` ## Related Methods - [`system_chain`](./system_chain) - Get chain name - [`state_getRuntimeVersion`](./state_getRuntimeVersion) - Get runtime version --- ## author_pendingExtrinsics - Astar RPC Method # author_pendingExtrinsics Returns all pending extrinsics in the transaction pool on Astar. ## Use Cases - **Mempool monitoring** - Track pending transactions - **Transaction status** - Check if your transaction is pending for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Pool analysis** - Monitor network activity ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "author_pendingExtrinsics", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_pendingExtrinsics", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const pending = await api.rpc.author.pendingExtrinsics(); console.log('Pending extrinsics:', pending.length); pending.forEach((ext, idx) => { console.log(`${idx}: ${ext.method.section}.${ext.method.method}`); }); await api.disconnect(); ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction --- ## author_rotateKeys - Astar RPC Method # author_rotateKeys Generate a new set of session keys on Astar. This method creates fresh cryptographic keys for validator operations and stores them in the node's keystore. The returned keys must be registered on-chain via `session.setKeys`. ## Use Cases - **Validator setup** - Generate initial session keys for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Key rotation** - Periodically rotate keys for security best practices - **Recovery** - Generate new keys after potential key compromise ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | `Bytes` | Concatenated SCALE-encoded public keys for all session key types | ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_rotateKeys", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Generate new session keys const keys = await api.rpc.author.rotateKeys(); console.log('New session keys:', keys.toHex()); // These keys need to be registered on-chain: // api.tx.session.setKeys(keys, proof) await api.disconnect(); ``` ```python url = 'https://api-astar.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'author_rotateKeys', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json() if 'result' in result: session_keys = result['result'] print(f'New session keys: {session_keys}') print('Register these keys using session.setKeys extrinsic') else: print(f"Error: {result.get('error')}") ``` ## Validator Setup Workflow 1. **Generate keys** - Call `author_rotateKeys` on your validator node 2. **Register on-chain** - Submit `session.setKeys(keys, proof)` extrinsic 3. **Wait for session** - Keys become active in the next session 4. **Verify** - Check `session.nextKeys` storage ## Security Considerations - Only call this method on your own validator node - Session keys are stored in the node's keystore - Rotate keys periodically and after any security incident - Never expose this RPC method publicly ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit setKeys transaction - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - View pending transactions --- ## author_submitAndWatchExtrinsic - Astar RPC Method # author_submitAndWatchExtrinsic Submit a signed extrinsic to and subscribe to status updates. This WebSocket method provides real-time feedback on transaction progress from submission through finalization. ## Use Cases - **Transaction tracking** - Monitor extrinsic lifecycle for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **UI feedback** - Show users real-time transaction status - **Confirmation workflows** - Wait for specific finality level before proceeding ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `Bytes` | Yes | SCALE-encoded signed extrinsic | ## Returns Returns a subscription that emits `ExtrinsicStatus` updates: | Status | Description | |--------|-------------| | `future` | In future queue (nonce too high) | | `ready` | In ready queue, waiting for block | | `broadcast` | Broadcast to peers | | `inBlock` | Included in block (hash provided) | | `retracted` | Block retracted (reorg) | | `finalityTimeout` | Finality timeout | | `finalized` | Finalized in block (hash provided) | | `usurped` | Replaced by another extrinsic | | `dropped` | Dropped from pool | | `invalid` | Invalid extrinsic | ## Code Examples ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const keyring = new Keyring({ type: 'sr25519' }); // Create and sign a transfer const sender = keyring.addFromUri('//Alice'); const transfer = api.tx.balances.transferKeepAlive( '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 1000000000000n ); // Submit and watch const unsub = await transfer.signAndSend(sender, ({ status, events }) => { console.log(`Status: ${status.type}`); if (status.isInBlock) { console.log(`Included in block: ${status.asInBlock.toHex()}`); } if (status.isFinalized) { console.log(`Finalized in block: ${status.asFinalized.toHex()}`); unsub(); } }); ``` ```python async def submit_and_watch(signed_extrinsic_hex): uri = 'wss://api-astar.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: # Submit and subscribe await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'author_submitAndWatchExtrinsic', 'params': [signed_extrinsic_hex], 'id': 1 })) # Get subscription ID response = json.loads(await ws.recv()) if 'error' in response: print(f"Error: {response['error']}") return sub_id = response['result'] print(f'Watching with subscription: {sub_id}') # Listen for status updates while True: message = json.loads(await ws.recv()) if 'params' in message: status = message['params']['result'] print(f"Status: {status}") # Check for finalization if isinstance(status, dict) and 'finalized' in status: print(f"Finalized in: {status['finalized']}") break # asyncio.run(submit_and_watch('0x...')) ``` ## Status Flow ``` ready → broadcast → inBlock → finalized ↘ retracted (if reorg) ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit without watching (fire-and-forget) - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - View transaction pool - [`payment_queryInfo`](./payment_queryInfo) - Estimate fees before submission --- ## author_submitExtrinsic - Astar RPC Method # author_submitExtrinsic Submit a signed extrinsic to Astar for inclusion in a block. ## Use Cases - **Transaction submission** - Broadcast signed transactions - **dApp interactions** - Execute on-chain operations for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Automated systems** - Submit programmatic transactions ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `String` | Yes | Hex-encoded signed extrinsic | ## Request ```json { "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": ["0x..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Transaction hash | ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": ["0x..."], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const keyring = new Keyring({ type: 'sr25519' }); const sender = keyring.addFromUri('//Alice'); // Build and sign transaction const transfer = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000); const hash = await transfer.signAndSend(sender); console.log('Transaction hash:', hash.toHex()); await api.disconnect(); ``` ## Related Methods - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - Get pending transactions - [`payment_queryInfo`](./payment_queryInfo) - Estimate fees --- ## beefy_getFinalizedHead - Astar RPC Method # beefy_getFinalizedHead Returns the block hash of the latest BEEFY-finalized block on Astar. BEEFY (Bridge Efficiency Enabling Finality Yielder) provides additional finality proofs optimized for light clients and bridges. ## Use Cases - **Cross-chain bridges** - Verify finality proofs for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Light clients** - Efficient finality verification without full GRANDPA proofs - **Trustless bridges** - Generate compact finality proofs for external chains ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | `Hash` | Block hash of the latest BEEFY-finalized block | ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "beefy_getFinalizedHead", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get BEEFY finalized head const beefyHead = await api.rpc.beefy.getFinalizedHead(); console.log('BEEFY finalized:', beefyHead.toHex()); // Compare with GRANDPA finalized const grandpaHead = await api.rpc.chain.getFinalizedHead(); console.log('GRANDPA finalized:', grandpaHead.toHex()); await api.disconnect(); ``` ```python url = 'https://api-astar.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'beefy_getFinalizedHead', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json() if 'result' in result: print(f"BEEFY finalized: {result['result']}") else: print(f"Error: {result.get('error')}") ``` ## BEEFY vs GRANDPA Finality | Aspect | GRANDPA | BEEFY | |--------|---------|-------| | **Purpose** | Primary finality | Bridge-optimized finality | | **Proof size** | Larger (full validator set) | Compact (aggregated signatures) | | **Latency** | Immediate | Slightly delayed | | **Use case** | On-chain finality | Cross-chain bridges | ## Availability BEEFY is enabled on relay chains and some parachains. If BEEFY is not enabled, this method will return an error. ## Related Methods - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - GRANDPA finalized head - [`grandpa_roundState`](./grandpa_roundState) - GRANDPA consensus state - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks --- ## chain_getBlock - Astar RPC Method # chain_getBlock Retrieves complete block information from Astar, including the block header, extrinsics, and justifications. > **Why Astar?** Build on Polkadot's leading dApp hub supporting EVM, WASM, and upcoming PolkaVM environments with EVM + WASM + PolkaVM support, Build2Earn developer rewards, dApp Staking, and Soneium cross-layer integration. ## Use Cases The `chain_getBlock` method is essential for: - **Block explorers** - Display complete block information - **Chain analysis** - Analyze block production patterns - **Transaction verification** - Confirm extrinsic inclusion for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Data indexing** - Build historical blockchain databases ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Hex-encoded block hash. If omitted, returns latest block | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getBlock", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `block` | `Object` | Complete block data | | `block.header` | `Object` | Block header information | | `block.header.parentHash` | `String` | Hash of the parent block | | `block.header.number` | `String` | Block number (hex-encoded) | | `block.header.stateRoot` | `String` | Root of the state trie | | `block.header.extrinsicsRoot` | `String` | Root of the extrinsics trie | | `block.extrinsics` | `Array` | Array of extrinsics in the block | | `justifications` | `Array` | Block justifications (if available) | ## Code Examples ```bash # Get latest block curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": [], "id": 1 }' # Get specific block curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get latest block const latestHash = await api.rpc.chain.getBlockHash(); const latestBlock = await api.rpc.chain.getBlock(latestHash); console.log('Latest block:', { number: latestBlock.block.header.number.toNumber(), hash: latestHash.toHex(), extrinsicsCount: latestBlock.block.extrinsics.length }); // Get specific block const blockHash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'; const block = await api.rpc.chain.getBlock(blockHash); console.log('Block extrinsics:', block.block.extrinsics.length); await api.disconnect(); ``` ```python def get_block(block_hash=None): url = 'https://api-astar.n.dwellir.com/YOUR_API_KEY' params = [block_hash] if block_hash else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getBlock', 'params': params, 'id': 1 } response = requests.post(url, json=payload) data = response.json() if 'error' in data: raise Exception(f"RPC Error: {data['error']}") return data['result'] # Get latest block latest_block = get_block() block_number = int(latest_block['block']['header']['number'], 16) print(f'Latest block number: {block_number}') # Get specific block specific_block = get_block('0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3') print(f"Extrinsics count: {len(specific_block['block']['extrinsics'])}") ``` ## Related Methods - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number - [`chain_getHeader`](./chain_getHeader) - Get block header only - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get finalized block hash --- ## chain_getBlockHash - Astar RPC Method # chain_getBlockHash Returns the block hash for a given block number on Astar. ## Use Cases - **Historical queries** - Convert block numbers to hashes - **Block navigation** - Navigate blockchain history for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Data indexing** - Build block number to hash mappings ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `Number` | No | Block number. If omitted, returns latest block hash | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getBlockHash", "params": [1000000], "id": 1 } ``` ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlockHash", "params": [1000000], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get hash for specific block number const blockNumber = 1000000; const blockHash = await api.rpc.chain.getBlockHash(blockNumber); console.log(`Block ${blockNumber} hash:`, blockHash.toHex()); await api.disconnect(); ``` ```python def get_block_hash(block_number=None): url = 'https://api-astar.n.dwellir.com/YOUR_API_KEY' params = [block_number] if block_number is not None else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getBlockHash', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] block_hash = get_block_hash(1000000) print(f'Block hash: {block_hash}') ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get block by hash - [`chain_getHeader`](./chain_getHeader) - Get block header --- ## chain_getFinalizedHead - Astar RPC Method # chain_getFinalizedHead Returns the hash of the last finalized block on Astar. ## Use Cases - **Confirmed state** - Query state that cannot be reverted - **Transaction confirmation** - Verify transaction finality for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Safe checkpoints** - Use finalized blocks for critical operations ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const finalizedHash = await api.rpc.chain.getFinalizedHead(); console.log('Finalized block hash:', finalizedHash.toHex()); // Get finalized block details const block = await api.rpc.chain.getBlock(finalizedHash); console.log('Finalized block number:', block.block.header.number.toNumber()); await api.disconnect(); ``` ```python def get_finalized_head(): url = 'https://api-astar.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'chain_getFinalizedHead', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] finalized_hash = get_finalized_head() print(f'Finalized block hash: {finalized_hash}') ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get block by hash - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number --- ## chain_getHeader - Astar RPC Method # chain_getHeader Returns the block header for a given hash on Astar. ## Use Cases - **Lightweight queries** - Get header without full block data - **Chain synchronization** - Track block production for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Parent chain navigation** - Follow parentHash links ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash. If omitted, returns latest header | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getHeader", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 } ``` ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getHeader", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get latest header const header = await api.rpc.chain.getHeader(); console.log('Block number:', header.number.toNumber()); console.log('Parent hash:', header.parentHash.toHex()); await api.disconnect(); ``` ```python def get_header(block_hash=None): url = 'https://api-astar.n.dwellir.com/YOUR_API_KEY' params = [block_hash] if block_hash else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getHeader', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] header = get_header() print(f"Block number: {int(header['number'], 16)}") ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get full block with extrinsics - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number --- ## chain_subscribeFinalizedHeads - Astar RPC Method # chain_subscribeFinalizedHeads Subscribe to receive notifications when blocks are finalized on Astar. Finalized blocks are guaranteed to never be reverted, making this essential for applications requiring strong consistency. ## Use Cases - **Exchange deposits** - Only credit funds after finalization for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Bridge operations** - Wait for finality before cross-chain transfers - **Critical state changes** - Ensure irreversibility for important transactions ## Parameters This method takes no parameters. ## Returns Returns a subscription ID. The subscription emits `Header` objects for each finalized block: | Field | Type | Description | |-------|------|-------------| | `parentHash` | `Hash` | Parent block hash | | `number` | `BlockNumber` | Block number | | `stateRoot` | `Hash` | State trie root hash | | `extrinsicsRoot` | `Hash` | Extrinsics trie root hash | | `digest` | `Digest` | Block digest with consensus logs | ## Code Examples ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Subscribe to finalized heads const unsubscribe = await api.rpc.chain.subscribeFinalizedHeads((header) => { console.log(`Finalized block #${header.number}`); console.log(` Hash: ${header.hash.toHex()}`); // Safe to consider this block permanent processConfirmedBlock(header); }); // Later: unsubscribe() ``` ```python async def subscribe_finalized(): uri = 'wss://api-astar.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'chain_subscribeFinalizedHeads', 'params': [], 'id': 1 })) response = json.loads(await ws.recv()) sub_id = response['result'] print(f'Subscribed to finalized heads: {sub_id}') while True: message = json.loads(await ws.recv()) if 'params' in message: header = message['params']['result'] block_num = int(header['number'], 16) print(f"Finalized: #{block_num}") asyncio.run(subscribe_finalized()) ``` ## Finality Lag Finalized blocks typically lag behind the best block by a few blocks due to GRANDPA consensus requirements. This is normal and ensures Byzantine fault tolerance. ## Related Methods - [`chain_subscribeNewHeads`](./chain_subscribeNewHeads) - Subscribe to all new blocks (not just finalized) - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get current finalized block hash - [`grandpa_roundState`](./grandpa_roundState) - Monitor GRANDPA consensus progress --- ## chain_subscribeNewHeads - Astar RPC Method # chain_subscribeNewHeads Subscribe to receive notifications when new block headers are produced on Astar. This WebSocket subscription provides real-time updates for each new block. ## Use Cases - **Block monitoring** - Track new blocks in real-time for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Event indexing** - Trigger processing when new blocks arrive - **Chain synchronization** - Keep external systems in sync with the chain ## Parameters This method takes no parameters. ## Returns Returns a subscription ID. The subscription emits `Header` objects for each new block: | Field | Type | Description | |-------|------|-------------| | `parentHash` | `Hash` | Parent block hash | | `number` | `BlockNumber` | Block number | | `stateRoot` | `Hash` | State trie root hash | | `extrinsicsRoot` | `Hash` | Extrinsics trie root hash | | `digest` | `Digest` | Block digest with consensus logs | ## Code Examples ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Subscribe to new heads const unsubscribe = await api.rpc.chain.subscribeNewHeads((header) => { console.log(`New block #${header.number}`); console.log(` Hash: ${header.hash.toHex()}`); console.log(` Parent: ${header.parentHash.toHex()}`); console.log(` State root: ${header.stateRoot.toHex()}`); }); // Later: unsubscribe() ``` ```python async def subscribe_new_heads(): uri = 'wss://api-astar.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: # Subscribe to new heads await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'chain_subscribeNewHeads', 'params': [], 'id': 1 })) # Get subscription ID response = json.loads(await ws.recv()) sub_id = response['result'] print(f'Subscribed with ID: {sub_id}') # Listen for new headers while True: message = json.loads(await ws.recv()) if 'params' in message: header = message['params']['result'] print(f"Block #{int(header['number'], 16)}") print(f" Hash: {header['parentHash']}") asyncio.run(subscribe_new_heads()) ``` ## Subscription vs Polling | Approach | Latency | Resource Usage | Use Case | |----------|---------|----------------|----------| | `subscribeNewHeads` | Immediate | Low (push-based) | Real-time monitoring | | Polling `getHeader` | Block time + poll interval | Higher (repeated requests) | Simple integrations | ## Related Methods - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks only - [`chain_getHeader`](./chain_getHeader) - Get a specific block header - [`chain_getBlock`](./chain_getBlock) - Get full block with extrinsics --- ## eth_accounts - Astar RPC Method # eth_accounts Returns a list of addresses owned by the client on Astar. > **Why Astar?** Build on Polkadot's leading dApp hub supporting EVM, WASM, and upcoming PolkaVM environments with EVM + WASM + PolkaVM support, Build2Earn developer rewards, dApp Staking, and Soneium cross-layer integration. ## Important Note On public RPC endpoints like Dwellir, `eth_accounts` returns an empty array because the node does not hold any private keys. This method is primarily useful for: - Local development nodes (Ganache, Hardhat, Anvil) - Private nodes with managed accounts - Wallet provider connections (MetaMask injects accounts) ## When to Use This Method `eth_accounts` is relevant for multi-chain dApp developers, DeFi builders, and teams leveraging Polkadot + Ethereum ecosystems in specific scenarios: - **Development Testing** — Retrieve test accounts from local nodes - **Wallet Detection** — Check if a wallet provider has connected accounts - **Client Verification** — Confirm node account access capabilities ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `Array` | List of 20-byte account addresses owned by the client | **Return format**: Array of `0x` prefixed hexadecimal addresses (typically empty for public nodes) ## Request ```json { "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 } ``` ## Response ### Successful Response (Public Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [] } ``` ### Successful Response (Local Development Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [ "0x407d73d8a49eeb85d32cf465507dd71d507100c1", "0x85d32cf465507dd71d507100c1407d73d8a49eeb" ] } ``` ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-astar.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_accounts', params: [], id: 1 }) }); const { result } = await response.json(); console.log('Accounts:', result); // Using ethers.js const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const accounts = await provider.listAccounts(); console.log('Accounts:', accounts); ``` ```python def get_accounts(): response = requests.post( 'https://api-astar.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_accounts', 'params': [], 'id': 1 } ) return response.json()['result'] accounts = get_accounts() print(f'Accounts: {accounts}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY')) print(f'Accounts: {w3.eth.accounts}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/rpc" ) func main() { client, err := rpc.Dial("https://api-astar.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } var accounts []string err = client.CallContext(context.Background(), &accounts, "eth_accounts") if err != nil { log.Fatal(err) } fmt.Printf("Accounts: %v\n", accounts) } ``` ## Common Use Cases ### 1. Development Environment Detection Check if running against a development node with test accounts: ```javascript async function isDevEnvironment(provider) { const accounts = await provider.listAccounts(); return accounts.length > 0; } const isDev = await isDevEnvironment(provider); if (isDev) { console.log('Development environment detected'); } ``` ### 2. Wallet Connection Check Verify wallet provider has connected accounts: ```javascript async function checkWalletConnection() { if (typeof window.ethereum === 'undefined') { return { connected: false, reason: 'No wallet detected' }; } const accounts = await window.ethereum.request({ method: 'eth_accounts' }); return { connected: accounts.length > 0, accounts: accounts }; } ``` ### 3. Fallback Account Selection Use first available account or request connection: ```javascript async function getActiveAccount() { // Check existing connections let accounts = await window.ethereum.request({ method: 'eth_accounts' }); // Request connection if no accounts if (accounts.length === 0) { accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); } return accounts[0] || null; } ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32601 | Method not found | Node may not support this method | | -32603 | Internal error | Retry with exponential backoff | ```javascript async function safeGetAccounts(provider) { try { const accounts = await provider.listAccounts(); return { success: true, accounts }; } catch (error) { if (error.code === -32601) { console.warn('eth_accounts not supported on this node'); return { success: false, accounts: [], reason: 'unsupported' }; } throw error; } } ``` ## Related Methods - [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102) — Request wallet connection (browser wallets) - [`eth_getBalance`](./eth_getBalance) — Get account balance - [`eth_getTransactionCount`](./eth_getTransactionCount) — Get account nonce --- ## eth_blockNumber - Astar RPC Method # eth_blockNumber Returns the number of the most recent block on Astar. > **Why Astar?** Build on Polkadot's leading dApp hub supporting EVM, WASM, and upcoming PolkaVM environments with EVM + WASM + PolkaVM support, Build2Earn developer rewards, dApp Staking, and Soneium cross-layer integration. ## When to Use This Method `eth_blockNumber` is fundamental for multi-chain dApp developers, DeFi builders, and teams leveraging Polkadot + Ethereum ecosystems: - **Syncing Applications** — Keep your dApp in sync with the latest Astar blockchain state - **Transaction Monitoring** — Verify confirmations by comparing block numbers - **Event Filtering** — Set the correct block range for querying logs on cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Health Checks** — Monitor node connectivity and sync status ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `QUANTITY` | Hexadecimal string representing the current block number | **Return format**: `0x` prefixed hexadecimal (e.g., `0x5BAD55` = 6,008,149 in decimal) ## Request ```json { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } ``` ## Response ### Successful Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5BAD55" } ``` ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error" } } ``` ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-astar.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }) }); const { result } = await response.json(); const blockNumber = parseInt(result, 16); console.log('Astar block:', blockNumber); // Using ethers.js const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const blockNumber = await provider.getBlockNumber(); console.log('Astar block:', blockNumber); ``` ```python def get_block_number(): response = requests.post( 'https://api-astar.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_blockNumber', 'params': [], 'id': 1 } ) result = response.json()['result'] return int(result, 16) block_number = get_block_number() print(f'Astar block: {block_number}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY')) print(f'Astar block: {w3.eth.block_number}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-astar.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockNumber, err := client.BlockNumber(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Astar block: %d\n", blockNumber) } ``` ## Common Use Cases ### 1. Block Confirmation Counter Monitor transaction confirmations on Astar: ```javascript async function getConfirmations(provider, txHash) { const tx = await provider.getTransaction(txHash); if (!tx || !tx.blockNumber) return 0; const currentBlock = await provider.getBlockNumber(); return currentBlock - tx.blockNumber + 1; } // Wait for specific confirmations async function waitForConfirmations(provider, txHash, confirmations = 6) { let currentConfirmations = 0; while (currentConfirmations < confirmations) { currentConfirmations = await getConfirmations(provider, txHash); console.log(`Confirmations: ${currentConfirmations}/${confirmations}`); await new Promise(r => setTimeout(r, 2000)); } return true; } ``` ### 2. Event Log Filtering Query events from recent blocks on Astar: ```javascript async function getRecentEvents(provider, contract, eventName, blockRange = 100) { const currentBlock = await provider.getBlockNumber(); const fromBlock = currentBlock - blockRange; const filter = contract.filters[eventName](); const events = await contract.queryFilter(filter, fromBlock, currentBlock); return events; } ``` ### 3. Node Health Monitoring Check if your Astar node is synced: ```javascript async function checkNodeHealth(provider) { try { const blockNumber = await provider.getBlockNumber(); const block = await provider.getBlock(blockNumber); const now = Date.now() / 1000; const blockAge = now - block.timestamp; if (blockAge > 60) { console.warn(`Node may be behind. Last block was ${blockAge}s ago`); return false; } console.log(`Node healthy. Latest block: ${blockNumber}`); return true; } catch (error) { console.error('Node unreachable:', error); return false; } } ``` ## Performance Optimization ### Caching Strategy Cache block numbers to reduce API calls: ```javascript class BlockNumberCache { constructor(ttl = 2000) { this.cache = null; this.timestamp = 0; this.ttl = ttl; } async get(provider) { const now = Date.now(); if (this.cache && (now - this.timestamp) < this.ttl) { return this.cache; } this.cache = await provider.getBlockNumber(); this.timestamp = now; return this.cache; } invalidate() { this.cache = null; this.timestamp = 0; } } const blockCache = new BlockNumberCache(); ``` ### Batch Requests Combine with other calls for efficiency: ```javascript const batch = [ { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }, { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 }, { jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 } ]; const response = await fetch('https://api-astar.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await response.json(); ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32603 | Internal error | Retry with exponential backoff | | -32005 | Rate limit exceeded | Implement rate limiting client-side | | -32000 | Execution reverted | Check node sync status | ```javascript async function safeGetBlockNumber(provider, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await provider.getBlockNumber(); } catch (error) { if (error.code === -32005) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } else if (i === maxRetries - 1) { throw error; } } } } ``` ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) — Get full block details by number - [`eth_getBlockByHash`](./eth_getBlockByHash) — Get block details by hash - [`eth_syncing`](./eth_syncing) — Check if node is still syncing --- ## eth_call - Astar RPC Method # eth_call Executes a new message call immediately without creating a transaction on Astar. Used for reading smart contract state. > **Why Astar?** Build on Polkadot's leading dApp hub supporting EVM, WASM, and upcoming PolkaVM environments with EVM + WASM + PolkaVM support, Build2Earn developer rewards, dApp Staking, and Soneium cross-layer integration. ## Use Cases The `eth_call` method is essential for: - **Reading contract state** - Query view/pure functions - **Simulating transactions** - Test execution without gas costs - **DeFi integrations** - Check prices, balances, allowances for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Complex queries** - Execute multi-step contract logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | 20-byte address executing the call | | `to` | `DATA` | Yes | 20-byte contract address | | `gas` | `QUANTITY` | No | Gas limit for the call | | `gasPrice` | `QUANTITY` | No | Gas price in wei | | `value` | `QUANTITY` | No | Value to send in wei | | `data` | `DATA` | Yes | Encoded function call data | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_call", "params": [ { "to": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "data": "0x70a08231000000000000000000000000" }, "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | The return value of the executed contract function | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000" } ``` ## Code Examples ```bash # Call ERC20 balanceOf function curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{ "to": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "data": "0x70a08231000000000000000000000000" }, "latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); // ERC20 ABI for common functions const ERC20_ABI = [ "function balanceOf(address owner) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function totalSupply() view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)" ]; // Read ERC20 token balance async function getTokenBalance(tokenAddress, walletAddress) { const contract = new Contract(tokenAddress, ERC20_ABI, provider); const balance = await contract.balanceOf(walletAddress); const decimals = await contract.decimals(); const symbol = await contract.symbol(); return { raw: balance.toString(), formatted: (Number(balance) / Math.pow(10, decimals)).toFixed(4), symbol: symbol }; } // Direct eth_call async function directCall(to, data) { const result = await provider.call({ to, data }); return result; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY')) def get_erc20_balance(token_address, wallet_address): # balanceOf(address) selector function_signature = "balanceOf(address)" function_selector = w3.keccak(text=function_signature)[:4].hex() # Encode address parameter encoded_address = wallet_address[2:].lower().zfill(64) data = function_selector + encoded_address # Make the call result = w3.eth.call({ 'to': token_address, 'data': data }) return int(result.hex(), 16) balance = get_erc20_balance( '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY' ) print(f'Balance: {balance}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-astar.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY") data := common.FromHex("0x70a08231000000000000000000000000") msg := ethereum.CallMsg{ To: &contractAddress, Data: data, } result, err := client.CallContract(context.Background(), msg, nil) if err != nil { log.Fatal(err) } fmt.Printf("Result: 0x%x\n", result) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Contract function reverted | | -32602 | Invalid parameters | Invalid data encoding | | -32015 | VM execution error | Contract logic error | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas for transaction - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send actual transaction --- ## eth_chainId - Astar RPC Method # eth_chainId Returns the chain ID used for transaction signing on Astar. > **Why Astar?** Build on Polkadot's leading dApp hub supporting EVM, WASM, and upcoming PolkaVM environments with EVM + WASM + PolkaVM support, Build2Earn developer rewards, dApp Staking, and Soneium cross-layer integration. ## Use Cases The `eth_chainId` method is essential for: - **Transaction signing** - Ensure transactions are signed for the correct network - **Network verification** - Confirm connection to the expected chain - **Multi-chain apps** - Handle different networks programmatically - **Wallet integration** - Validate network before transactions ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Chain ID in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1" } ``` ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const network = await provider.getNetwork(); console.log('Chain ID:', network.chainId); // Verify network before transaction async function verifyNetwork(expectedChainId) { const network = await provider.getNetwork(); if (network.chainId !== BigInt(expectedChainId)) { throw new Error(`Wrong network. Expected ${expectedChainId}, got ${network.chainId}`); } return true; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY')) chain_id = w3.eth.chain_id print(f'Chain ID: {chain_id}') # Verify network def verify_network(expected_chain_id): chain_id = w3.eth.chain_id if chain_id != expected_chain_id: raise ValueError(f'Wrong network. Expected {expected_chain_id}, got {chain_id}') return True ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-astar.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } chainID, err := client.ChainID(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Chain ID: %d\n", chainID) } ``` ## Related Methods - [`net_version`](./net_version) - Get network version - [`eth_syncing`](./eth_syncing) - Check sync status --- ## eth_estimateGas - Astar RPC Method # eth_estimateGas Estimates the gas necessary to execute a transaction on Astar. > **Why Astar?** Build on Polkadot's leading dApp hub supporting EVM, WASM, and upcoming PolkaVM environments with EVM + WASM + PolkaVM support, Build2Earn developer rewards, dApp Staking, and Soneium cross-layer integration. ## Use Cases The `eth_estimateGas` method is essential for: - **Transaction preparation** - Set appropriate gas limits - **Cost estimation** - Calculate transaction costs before sending - **Error detection** - Identify reverts before spending gas - **DeFi operations** - Estimate costs for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | Sender address | | `to` | `DATA` | No | Recipient address | | `gas` | `QUANTITY` | No | Gas limit | | `gasPrice` | `QUANTITY` | No | Gas price | | `value` | `QUANTITY` | No | Value in wei | | `data` | `DATA` | No | Transaction data | ## Request ```json { "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "to": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "value": "0x1" }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Estimated gas amount in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5208" } ``` **Note**: `0x5208` = 21000 gas (standard ETH transfer) ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "to": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "value": "0x1" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); // Estimate simple transfer async function estimateTransfer(to, value) { const gasEstimate = await provider.estimateGas({ to: to, value: parseEther(value) }); console.log('Estimated gas:', gasEstimate.toString()); return gasEstimate; } // Estimate contract call async function estimateContractCall(contract, method, args) { const gasEstimate = await contract[method].estimateGas(...args); console.log('Estimated gas:', gasEstimate.toString()); // Add 20% buffer for safety return gasEstimate * 120n / 100n; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY')) def estimate_transfer(to, value_in_ether): gas_estimate = w3.eth.estimate_gas({ 'to': to, 'value': w3.to_wei(value_in_ether, 'ether') }) print(f'Estimated gas: {gas_estimate}') return gas_estimate def estimate_contract_call(contract, method, args): func = getattr(contract.functions, method) gas_estimate = func(*args).estimate_gas() # Add 20% buffer return int(gas_estimate * 1.2) # Estimate simple transfer gas = estimate_transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 0.1) ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-astar.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } toAddress := common.HexToAddress("5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY") msg := ethereum.CallMsg{ To: &toAddress, Value: big.NewInt(1000000000000000000), } gasLimit, err := client.EstimateGas(context.Background(), msg) if err != nil { log.Fatal(err) } fmt.Printf("Estimated gas: %d\n", gasLimit) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Transaction would fail | | -32602 | Invalid params | Invalid transaction parameters | **Tip**: If estimation fails, the transaction would likely revert if sent. ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_feeHistory - Astar RPC Method # eth_feeHistory Returns historical gas information on Astar for fee estimation. ## Use Cases - **Fee prediction** - Estimate future gas prices based on history - **Gas analytics** - Analyze fee trends over time - **Optimal timing** - Find best times for transactions on cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockCount` | `QUANTITY` | Yes | Number of blocks in the range | | `newestBlock` | `QUANTITY\|TAG` | Yes | Highest block of the range | | `rewardPercentiles` | `Array` | Yes | Percentiles to sample for priority fees | ## Request ```json { "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const feeHistory = await provider.send('eth_feeHistory', ['0xa', 'latest', [25, 50, 75]]); console.log('Base fees:', feeHistory.baseFeePerGas.map(f => formatUnits(f, 'gwei'))); console.log('Reward (25th percentile):', feeHistory.reward.map(r => formatUnits(r[0], 'gwei'))); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY')) fee_history = w3.eth.fee_history(10, 'latest', [25, 50, 75]) print(f'Base fees: {[w3.from_wei(f, "gwei") for f in fee_history["baseFeePerGas"]]}') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee --- ## eth_gasPrice - Astar RPC Method # eth_gasPrice Returns the current gas price on Astar in wei. > **Why Astar?** Build on Polkadot's leading dApp hub supporting EVM, WASM, and upcoming PolkaVM environments with EVM + WASM + PolkaVM support, Build2Earn developer rewards, dApp Staking, and Soneium cross-layer integration. ## Use Cases The `eth_gasPrice` method is essential for: - **Transaction pricing** - Set appropriate gas prices - **Cost estimation** - Calculate transaction costs before sending - **Gas monitoring** - Track network congestion - **DeFi operations** - Optimize costs for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Current gas price in wei (hexadecimal) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x3b9aca00" } ``` **Note**: `0x3b9aca00` = 1 Gwei (1,000,000,000 wei) ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); const gasPrice = feeData.gasPrice; console.log('Gas Price:', formatUnits(gasPrice, 'gwei'), 'Gwei'); // Calculate transaction cost async function estimateTransactionCost(gasLimit) { const feeData = await provider.getFeeData(); const cost = feeData.gasPrice * BigInt(gasLimit); return formatUnits(cost, 'ether'); } const cost = await estimateTransactionCost(21000); console.log('Transfer cost:', cost, 'ETH'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY')) gas_price = w3.eth.gas_price print(f'Gas Price: {w3.from_wei(gas_price, "gwei")} Gwei') # Calculate transaction cost def estimate_transaction_cost(gas_limit): gas_price = w3.eth.gas_price cost = gas_price * gas_limit return w3.from_wei(cost, 'ether') cost = estimate_transaction_cost(21000) print(f'Transfer cost: {cost} ETH') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-astar.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } gasPrice, err := client.SuggestGasPrice(context.Background()) if err != nil { log.Fatal(err) } // Convert to Gwei gwei := new(big.Float).Quo( new(big.Float).SetInt(gasPrice), big.NewFloat(1e9), ) fmt.Printf("Gas Price: %f Gwei\n", gwei) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32603 | Internal error | Node error | ## Related Methods - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee (EIP-1559) - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas needed --- ## eth_getBalance - Astar RPC Method # eth_getBalance Returns the balance of a given address on Astar. > **Why Astar?** Build on Polkadot's leading dApp hub supporting EVM, WASM, and upcoming PolkaVM environments with EVM + WASM + PolkaVM support, Build2Earn developer rewards, dApp Staking, and Soneium cross-layer integration. ## Use Cases The `eth_getBalance` method is essential for: - **Wallet applications** - Display user balances - **Transaction validation** - Check if account has sufficient funds - **DeFi applications** - Monitor collateral and liquidity for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Account monitoring** - Track balance changes over time ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address to check balance for | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Integer of the current balance in wei (hexadecimal) | **Note**: 1 native token = 10^18 wei. Convert using `balance / 10^18`. ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1a055690d9db80000" } ``` ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const balanceWei = await provider.getBalance(address); const balance = formatEther(balanceWei); console.log(`Balance: ${balance}`); // Get balance at specific block const historicalBalance = await provider.getBalance(address, 1000000); console.log(`Historical balance: ${formatEther(historicalBalance)}`); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY')) address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY' balance_wei = w3.eth.get_balance(address) balance = w3.from_wei(balance_wei, 'ether') print(f'Balance: {balance}') # Get balance at specific block historical_balance = w3.eth.get_balance(address, block_identifier=1000000) print(f'Historical balance: {w3.from_wei(historical_balance, "ether")}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-astar.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY") balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } // Convert to ether fbalance := new(big.Float).SetInt(balance) ethValue := new(big.Float).Quo(fbalance, big.NewFloat(1e18)) fmt.Printf("Balance: %f\n", ethValue) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid address format or block parameter | | -32000 | Execution error | Node execution error | ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_getTransactionCount`](./eth_getTransactionCount) - Get account nonce --- ## eth_getBlockByHash - Astar RPC Method # eth_getBlockByHash Returns information about a block by hash on Astar. > **Why Astar?** Build on Polkadot's leading dApp hub supporting EVM, WASM, and upcoming PolkaVM environments with EVM + WASM + PolkaVM support, Build2Earn developer rewards, dApp Staking, and Soneium cross-layer integration. ## Use Cases The `eth_getBlockByHash` method is essential for: - **Block verification** - Verify block data using its unique hash - **Chain reorganization handling** - Track blocks during reorgs - **Cross-chain bridges** - Verify block finality for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Deterministic queries** - Get consistent block data regardless of chain state ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3", false ], "id": 1 } ``` ## Returns Returns the same block object as `eth_getBlockByNumber`, or `null` if no block is found. | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used | | `transactions` | `Array` | Transaction objects or hashes | ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3", false ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'; const block = await provider.getBlock(blockHash); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY')) block_hash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3' block = w3.eth.get_block(block_hash) print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-astar.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockHash := common.HexToHash("0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3") block, err := client.BlockByHash(context.Background(), blockHash) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block hash format | | -32000 | Block not found | Block with this hash does not exist | ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) - Get block by number - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number --- ## eth_getBlockByNumber - Astar RPC Method # eth_getBlockByNumber Returns information about a block by block number on Astar. > **Why Astar?** Build on Polkadot's leading dApp hub supporting EVM, WASM, and upcoming PolkaVM environments with EVM + WASM + PolkaVM support, Build2Earn developer rewards, dApp Staking, and Soneium cross-layer integration. ## Use Cases The `eth_getBlockByNumber` method is essential for: - **Block explorers** - Display complete block information - **Transaction indexers** - Process all transactions in a block - **Analytics platforms** - Analyze blockchain data for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Timestamp verification** - Get block timestamps for time-based logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used by all transactions | | `gasLimit` | `QUANTITY` | Maximum gas allowed in block | | `transactions` | `Array` | Array of transaction objects or hashes | | `baseFeePerGas` | `QUANTITY` | Base fee per gas (EIP-1559) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": { "number": "0x5BAD55", "hash": "0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3", "parentHash": "0x...", "timestamp": "0x64d8f6d0", "gasUsed": "0x1234", "gasLimit": "0x1c9c380", "transactions": [], "baseFeePerGas": "0x5f5e100" } } ``` ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); // Get latest block const block = await provider.getBlock('latest'); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); console.log('Transactions:', block.transactions.length); // Get block with full transactions const blockWithTxs = await provider.getBlock('latest', true); for (const tx of blockWithTxs.prefetchedTransactions) { console.log('Transaction:', tx.hash); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY')) # Get latest block block = w3.eth.get_block('latest') print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') print(f'Transactions: {len(block.transactions)}') # Get block with full transactions block_full = w3.eth.get_block('latest', full_transactions=True) for tx in block_full.transactions: print(f'Transaction: {tx.hash.hex()}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-astar.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } // Get latest block block, err := client.BlockByNumber(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) fmt.Printf("Timestamp: %d\n", block.Time()) fmt.Printf("Transactions: %d\n", len(block.Transactions())) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block number or parameter format | | -32000 | Block not found | Block does not exist | ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number - [`eth_getBlockByHash`](./eth_getBlockByHash) - Get block by hash - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_getCode - Astar RPC Method # eth_getCode Returns the bytecode at a given address on Astar. > **Why Astar?** Build on Polkadot's leading dApp hub supporting EVM, WASM, and upcoming PolkaVM environments with EVM + WASM + PolkaVM support, Build2Earn developer rewards, dApp Staking, and Soneium cross-layer integration. ## Use Cases The `eth_getCode` method is essential for: - **Contract verification** - Check if address is a contract - **Security analysis** - Verify deployed bytecode matches expected - **DeFi integrations** - Validate contracts before interactions - **Protocol analysis** - Analyze contract deployments for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Contract bytecode or `0x` if EOA | ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const code = await provider.getCode(address); if (code === '0x') { console.log('Address is an EOA (externally owned account)'); } else { console.log('Address is a contract'); console.log('Bytecode length:', code.length); } // Check if address is a contract async function isContract(address) { const code = await provider.getCode(address); return code !== '0x'; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY')) address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY' code = w3.eth.get_code(address) if code == b'': print('Address is an EOA') else: print('Address is a contract') print(f'Bytecode length: {len(code.hex())}') # Check if address is a contract def is_contract(address): code = w3.eth.get_code(address) return code != b'' ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-astar.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY") code, err := client.CodeAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } if len(code) == 0 { fmt.Println("Address is an EOA") } else { fmt.Printf("Contract bytecode length: %d\n", len(code)) } } ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_getStorageAt`](./eth_getStorageAt) - Get contract storage --- ## eth_getFilterChanges - Astar RPC Method # eth_getFilterChanges Polling method for a filter on Astar, returns an array of logs since last poll. ## Use Cases - **Event streaming** - Get new events incrementally - **Real-time monitoring** - Track contract activity for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Efficient indexing** - Process only new events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); // Poll loop async function pollFilter(filterId, interval = 2000) { while (true) { const changes = await provider.send('eth_getFilterChanges', [filterId]); if (changes.length > 0) { console.log('New events:', changes); } await new Promise(r => setTimeout(r, interval)); } } ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter --- ## eth_getFilterLogs - Astar RPC Method # eth_getFilterLogs Returns an array of all logs matching filter with given ID on Astar. ## Use Cases - **Historical queries** - Get all matching logs for a filter - **Full event history** - Retrieve complete event data for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const logs = await provider.send('eth_getFilterLogs', [filterId]); console.log('All matching logs:', logs.length); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_getLogs - Astar RPC Method # eth_getLogs Returns an array of all logs matching a given filter object on Astar. > **Why Astar?** Build on Polkadot's leading dApp hub supporting EVM, WASM, and upcoming PolkaVM environments with EVM + WASM + PolkaVM support, Build2Earn developer rewards, dApp Staking, and Soneium cross-layer integration. ## Use Cases The `eth_getLogs` method is essential for: - **Event indexing** - Track contract events for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Token transfers** - Monitor ERC20/ERC721 transfers - **DeFi analytics** - Track swaps, liquidity events, and more - **Notification systems** - Alert on specific on-chain events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block (default: `"latest"`) | | `toBlock` | `QUANTITY\|TAG` | No | Ending block (default: `"latest"`) | | `address` | `DATA\|Array` | No | Contract address(es) to filter | | `topics` | `Array` | No | Array of topic filters | | `blockHash` | `DATA` | No | Filter single block by hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "topics": [""] }], "id": 1 } ``` ## Returns Array of log objects: | Field | Type | Description | |-------|------|-------------| | `address` | `DATA` | Contract that emitted the log | | `topics` | `Array` | Array of indexed topics | | `data` | `DATA` | Non-indexed log data | | `blockNumber` | `QUANTITY` | Block number | | `transactionHash` | `DATA` | Transaction hash | | `logIndex` | `QUANTITY` | Log index in block | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": [{ "address": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "topics": ["", "0x...", "0x..."], "data": "0x...", "blockNumber": "0x5BAD55", "transactionHash": "0x...", "logIndex": "0x0" }] } ``` ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "topics": [""] }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); // Get Transfer events const TRANSFER_TOPIC = ''; async function getTransferEvents(tokenAddress, fromBlock, toBlock) { const logs = await provider.getLogs({ address: tokenAddress, topics: [TRANSFER_TOPIC], fromBlock: fromBlock, toBlock: toBlock }); return logs.map(log => ({ from: '0x' + log.topics[1].slice(26), to: '0x' + log.topics[2].slice(26), blockNumber: log.blockNumber, transactionHash: log.transactionHash })); } const events = await getTransferEvents( '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 'latest', 'latest' ); console.log('Transfer events:', events); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY')) TRANSFER_TOPIC = '' def get_transfer_events(token_address, from_block, to_block): logs = w3.eth.get_logs({ 'address': token_address, 'topics': [TRANSFER_TOPIC], 'fromBlock': from_block, 'toBlock': to_block }) events = [] for log in logs: events.append({ 'from': '0x' + log['topics'][1].hex()[26:], 'to': '0x' + log['topics'][2].hex()[26:], 'block': log['blockNumber'], 'tx': log['transactionHash'].hex() }) return events events = get_transfer_events( '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 'latest', 'latest' ) print(f'Found {len(events)} transfer events') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-astar.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY") transferTopic := common.HexToHash("") query := ethereum.FilterQuery{ FromBlock: big.NewInt(0), ToBlock: nil, Addresses: []common.Address{contractAddress}, Topics: [][]common.Hash, } logs, err := client.FilterLogs(context.Background(), query) if err != nil { log.Fatal(err) } fmt.Printf("Found %d events\n", len(logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32005 | Query returned more than 10000 results | Reduce block range | | -32602 | Invalid params | Invalid filter parameters | ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create a filter for logs - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for new logs --- ## eth_getStorageAt - Astar RPC Method # eth_getStorageAt Returns the value from a storage position at a given address on Astar. ## Use Cases - **Contract analysis** - Read raw storage values - **State verification** - Verify contract state - **Security auditing** - Analyze storage layout for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Protocol monitoring** - Track state changes ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte contract address | | `position` | `QUANTITY` | Yes | Storage slot position | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "0x0", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "0x0", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const slot = 0; const storage = await provider.getStorage(address, slot); console.log('Storage at slot 0:', storage); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY')) address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY' storage = w3.eth.get_storage_at(address, 0) print(f'Storage at slot 0: {storage.hex()}') ``` ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_call`](./eth_call) - Call contract functions --- ## eth_getTransactionByHash - Astar RPC Method # eth_getTransactionByHash Returns the information about a transaction by transaction hash on Astar. > **Why Astar?** Build on Polkadot's leading dApp hub supporting EVM, WASM, and upcoming PolkaVM environments with EVM + WASM + PolkaVM support, Build2Earn developer rewards, dApp Staking, and Soneium cross-layer integration. ## Use Cases The `eth_getTransactionByHash` method is essential for: - **Transaction tracking** - Get details of pending or confirmed transactions - **Payment verification** - Verify transaction parameters - **Debugging** - Analyze transaction data for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Block explorers** - Display transaction information ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": [""], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `hash` | `DATA` | Transaction hash | | `from` | `DATA` | Sender address | | `to` | `DATA` | Recipient address | | `value` | `QUANTITY` | Value in wei | | `gas` | `QUANTITY` | Gas provided | | `gasPrice` | `QUANTITY` | Gas price in wei | | `input` | `DATA` | Transaction input data | | `nonce` | `QUANTITY` | Sender's nonce | | `blockHash` | `DATA` | Block hash (null if pending) | | `blockNumber` | `QUANTITY` | Block number (null if pending) | ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": [""], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const txHash = ''; const tx = await provider.getTransaction(txHash); if (tx) { console.log('From:', tx.from); console.log('To:', tx.to); console.log('Value:', formatEther(tx.value)); console.log('Block:', tx.blockNumber); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY')) tx_hash = '' tx = w3.eth.get_transaction(tx_hash) if tx: print(f'From: {tx["from"]}') print(f'To: {tx["to"]}') print(f'Value: {w3.from_wei(tx["value"], "ether")}') print(f'Block: {tx["blockNumber"]}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-astar.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("") tx, isPending, err := client.TransactionByHash(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Pending: %v\n", isPending) fmt.Printf("Value: %s\n", tx.Value().String()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash format | ## Related Methods - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction receipt - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionCount - Astar RPC Method # eth_getTransactionCount Returns the number of transactions sent from an address on Astar (the nonce). ## Use Cases - **Transaction building** - Get correct nonce for new transactions - **Account analysis** - Count total outgoing transactions - **Nonce management** - Handle pending transaction queues - **Wallet operations** - Prepare transactions for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag (`pending` for next nonce) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const nonce = await provider.getTransactionCount(address); console.log('Nonce:', nonce); // Get pending nonce for new transaction const pendingNonce = await provider.getTransactionCount(address, 'pending'); console.log('Next nonce:', pendingNonce); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY')) address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY' nonce = w3.eth.get_transaction_count(address) print(f'Nonce: {nonce}') # Get pending nonce pending_nonce = w3.eth.get_transaction_count(address, 'pending') print(f'Next nonce: {pending_nonce}') ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionReceipt - Astar RPC Method # eth_getTransactionReceipt Returns the receipt of a transaction by transaction hash on Astar. Receipt is only available for mined transactions. > **Why Astar?** Build on Polkadot's leading dApp hub supporting EVM, WASM, and upcoming PolkaVM environments with EVM + WASM + PolkaVM support, Build2Earn developer rewards, dApp Staking, and Soneium cross-layer integration. ## Use Cases The `eth_getTransactionReceipt` method is essential for: - **Transaction confirmation** - Verify transaction was mined successfully - **Gas analysis** - Check actual gas used vs estimated - **Event parsing** - Read emitted events from logs - **Status verification** - Confirm success/failure for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": [""], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `status` | `QUANTITY` | `1` (success) or `0` (failure) | | `transactionHash` | `DATA` | Transaction hash | | `blockHash` | `DATA` | Block hash | | `blockNumber` | `QUANTITY` | Block number | | `gasUsed` | `QUANTITY` | Gas used by this transaction | | `cumulativeGasUsed` | `QUANTITY` | Total gas used in block up to this tx | | `logs` | `Array` | Array of log objects | | `contractAddress` | `DATA` | Created contract address (if deployment) | ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": [""], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const txHash = ''; const receipt = await provider.getTransactionReceipt(txHash); if (receipt) { console.log('Status:', receipt.status === 1 ? 'Success' : 'Failed'); console.log('Gas Used:', receipt.gasUsed.toString()); console.log('Block:', receipt.blockNumber); console.log('Logs:', receipt.logs.length); // Parse specific events for (const log of receipt.logs) { console.log('Event from:', log.address); } } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY')) tx_hash = '' receipt = w3.eth.get_transaction_receipt(tx_hash) if receipt: status = 'Success' if receipt['status'] == 1 else 'Failed' print(f'Status: {status}') print(f'Gas Used: {receipt["gasUsed"]}') print(f'Block: {receipt["blockNumber"]}') print(f'Logs: {len(receipt["logs"])}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-astar.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("") receipt, err := client.TransactionReceipt(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Status: %d\n", receipt.Status) fmt.Printf("Gas Used: %d\n", receipt.GasUsed) fmt.Printf("Logs: %d\n", len(receipt.Logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash | **Note**: Returns `null` if transaction is not yet mined. ## Related Methods - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details - [`eth_getLogs`](./eth_getLogs) - Query logs by filter --- ## eth_maxPriorityFeePerGas - Astar RPC Method # eth_maxPriorityFeePerGas Returns the current recommended priority fee per gas on Astar for EIP-1559 transactions. ## Use Cases - **EIP-1559 transactions** - Set appropriate priority fees - **Transaction acceleration** - Calculate tips for faster inclusion - **Gas optimization** - Balance speed vs cost for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); console.log('Max Priority Fee:', formatUnits(feeData.maxPriorityFeePerGas, 'gwei'), 'Gwei'); console.log('Max Fee Per Gas:', formatUnits(feeData.maxFeePerGas, 'gwei'), 'Gwei'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY')) priority_fee = w3.eth.max_priority_fee print(f'Max Priority Fee: {w3.from_wei(priority_fee, "gwei")} Gwei') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get legacy gas price - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data --- ## eth_newBlockFilter - Astar RPC Method # eth_newBlockFilter Creates a filter on Astar to notify when a new block arrives. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newBlockFilter', []); // Poll for new blocks const newBlocks = await provider.send('eth_getFilterChanges', [filterId]); console.log('New block hashes:', newBlocks); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_blockNumber`](./eth_blockNumber) - Get current block --- ## eth_newFilter - Astar RPC Method # eth_newFilter Creates a filter object on Astar to notify when state changes (logs). ## Use Cases - **Event monitoring** - Subscribe to contract events - **Real-time updates** - Track events for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Indexing** - Build event indexes incrementally ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block | | `toBlock` | `QUANTITY\|TAG` | No | Ending block | | `address` | `DATA\|Array` | No | Contract address(es) | | `topics` | `Array` | No | Topic filters | ## Request ```json { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "topics": [""] }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); // Create filter const filterId = await provider.send('eth_newFilter', [{ fromBlock: 'latest', address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', topics: [''] }]); // Poll for changes const changes = await provider.send('eth_getFilterChanges', [filterId]); console.log('New events:', changes); // Cleanup await provider.send('eth_uninstallFilter', [filterId]); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for changes - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_newPendingTransactionFilter - Astar RPC Method # eth_newPendingTransactionFilter Creates a filter on Astar to notify when new pending transactions arrive. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newPendingTransactionFilter', []); // Poll for pending transactions const pendingTxs = await provider.send('eth_getFilterChanges', [filterId]); console.log('Pending transaction hashes:', pendingTxs); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_sendRawTransaction - Astar RPC Method # eth_sendRawTransaction Submits a pre-signed transaction for broadcast to Astar. > **Why Astar?** Build on Polkadot's leading dApp hub supporting EVM, WASM, and upcoming PolkaVM environments with EVM + WASM + PolkaVM support, Build2Earn developer rewards, dApp Staking, and Soneium cross-layer integration. ## Use Cases The `eth_sendRawTransaction` method is essential for: - **Broadcasting transactions** - Submit signed transactions to the network - **Wallet operations** - Send native tokens and interact with contracts - **DeFi operations** - Execute swaps, provide liquidity for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Batch operations** - Submit multiple transactions efficiently ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `signedTransactionData` | `DATA` | Yes | The signed transaction data (RLP encoded) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | 32-byte transaction hash | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c808504a817c80082520894..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const wallet = new Wallet('YOUR_PRIVATE_KEY', provider); // Send native tokens async function sendTransaction(to, value) { const tx = await wallet.sendTransaction({ to: to, value: parseEther(value) }); console.log('Transaction hash:', tx.hash); // Wait for confirmation const receipt = await tx.wait(); console.log('Confirmed in block:', receipt.blockNumber); return receipt; } // Send to contract async function sendContractTransaction(contract, method, args, value = '0') { const tx = await contract[method](...args, { value: parseEther(value) }); return await tx.wait(); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY')) def send_transaction(private_key, to, value_in_ether): account = w3.eth.account.from_key(private_key) # Build transaction tx = { 'nonce': w3.eth.get_transaction_count(account.address), 'to': to, 'value': w3.to_wei(value_in_ether, 'ether'), 'gas': 21000, 'gasPrice': w3.eth.gas_price, 'chainId': w3.eth.chain_id } # Sign transaction signed_tx = account.sign_transaction(tx) # Send transaction tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) print(f'Transaction hash: {tx_hash.hex()}') # Wait for confirmation receipt = w3.eth.wait_for_transaction_receipt(tx_hash) print(f'Confirmed in block: {receipt["blockNumber"]}') return receipt ``` ```go package main "context" "crypto/ecdsa" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-astar.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY") if err != nil { log.Fatal(err) } publicKey := privateKey.Public() publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey) fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA) nonce, _ := client.PendingNonceAt(context.Background(), fromAddress) value := big.NewInt(1000000000000000000) gasLimit := uint64(21000) gasPrice, _ := client.SuggestGasPrice(context.Background()) toAddress := common.HexToAddress("5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY") tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil) chainID, _ := client.NetworkID(context.Background()) signedTx, _ := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey) err = client.SendTransaction(context.Background(), signedTx) if err != nil { log.Fatal(err) } fmt.Printf("Transaction hash: %s\n", signedTx.Hash().Hex()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Nonce too low | Transaction nonce already used | | -32000 | Insufficient funds | Account has insufficient balance | | -32000 | Gas too low | Gas limit insufficient | | -32000 | Replacement underpriced | Gas price too low for replacement | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas required - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction result --- ## eth_syncing - Astar RPC Method # eth_syncing Returns syncing status of Astar node. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 } ``` ## Returns Returns `false` if not syncing, or an object with sync status. ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const syncing = await provider.send('eth_syncing', []); if (syncing === false) { console.log('Node is fully synced'); } else { console.log('Syncing:', syncing); } ``` ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get current block - [`net_peerCount`](./net_peerCount) - Get peer count --- ## eth_uninstallFilter - Astar RPC Method # eth_uninstallFilter Uninstalls a filter on Astar. Should be called when no longer needed. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID to uninstall | ## Request ```json { "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if filter was found and uninstalled | ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const success = await provider.send('eth_uninstallFilter', [filterId]); console.log('Filter removed:', success); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter --- ## grandpa_roundState - Astar RPC Method # grandpa_roundState Returns the state of the current GRANDPA finality round on Astar. GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) is the finality gadget used by Substrate chains. ## Use Cases - **Finality monitoring** - Track consensus progress for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Validator analysis** - Monitor prevote/precommit participation - **Chain health checks** - Detect finality delays or stalls ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `setId` | `u64` | Current authority set ID | | `best` | `RoundState` | Best round state | | `background` | `Vec` | Background rounds | ### RoundState Structure | Field | Type | Description | |-------|------|-------------| | `round` | `u64` | Round number | | `totalWeight` | `u64` | Total validator weight | | `thresholdWeight` | `u64` | Weight needed for supermajority | | `prevotes` | `Prevotes` | Prevote information | | `precommits` | `Precommits` | Precommit information | ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "grandpa_roundState", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const roundState = await api.rpc.grandpa.roundState(); console.log('Set ID:', roundState.setId.toString()); console.log('Best round:', roundState.best.round.toString()); console.log('Total weight:', roundState.best.totalWeight.toString()); console.log('Threshold:', roundState.best.thresholdWeight.toString()); await api.disconnect(); ``` ```python url = 'https://api-astar.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'grandpa_roundState', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json()['result'] print(f"Set ID: {result['setId']}") print(f"Round: {result['best']['round']}") print(f"Total weight: {result['best']['totalWeight']}") ``` ## Understanding GRANDPA Rounds 1. **Prevote phase** - Validators vote on best block they've seen 2. **Precommit phase** - Validators commit to finalize if supermajority prevoted 3. **Finalization** - Block is finalized when 2/3+ weight precommits ## Related Methods - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get current finalized hash - [`beefy_getFinalizedHead`](./beefy_getFinalizedHead) - BEEFY finality (if enabled) --- ## Astar RPC Guide ## Why Build on Astar? ### 🚀 Multichain smart-contract hub - Dual EVM + WASM runtimes let teams deploy Solidity and ink! contracts side by side while inheriting Polkadot relay-chain security ([Astar build docs](https://docs.astar.network/docs/build)). - Build2Earn dApp staking shares block rewards with developers who attract stakers, turning usage into sustainable funding ([Astar dApp staking guide](https://docs.astar.network/docs/learn/dapp-staking/)). ### ⚙️ Optimized for Polkadot 2.0 - Astar adopted Agile Coretime so parachain capacity scales with demand instead of multi-year lease slots, reducing operating costs for long-lived apps ([Polkadot Ecosystem update, Aug 13 2025](https://polkadotecosystem.com/pt/dapps/smart-contracts/astar-network/)). - Asynchronous Backing on mainnet brings ~6-second block production with larger block weight limits for latency-sensitive DeFi and gaming flows ([Astar mainnet upgrade announcement](https://astar.network/blog/astar-network-integrates-the-new-polkadot-generic-ledger-app-53)). ### 🧑‍💻 Enterprise-ready infrastructure - Dwellir, Chainstack, and other managed providers expose archive-grade RPC endpoints so teams can launch without running collators on day one ([Dwellir Astar network page](https://www.dwellir.com/networks/astar), [Chainstack support announcement](https://chainstack.com/chainstack-introduces-support-for-astar/)). ## Quick Start with Astar Connect to Astar, Shibuya testnet, or Shiden canary through Dwellir-managed endpoints. :::info Get your API key Sign up with [Dwellir](https://dashboard.dwellir.com/register) or your preferred infrastructure partner to replace `YOUR_API_KEY` before sending requests. ::: ### Installation & Setup ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "chain_getHeader", "params": [] }' ``` **Sample response (2025-10-03 10:13 UTC):** ```json { "jsonrpc": "2.0", "result": { "number": "0x9fbc28", "parentHash": "0x3f484429ad05365b32f643a9e825794961c1e6f92cde48a2c73935d7773dd5e1", "stateRoot": "0x1b983c37356b175bcf38dc1afcc8e31fa893e561f605fcad473697a68ac92169", "extrinsicsRoot": "0x783e75691edc604a3f13e1b5c558dd3ca5870ac07ce799c781713219a4a56224", "digest": { "logs": [ "0x066175726120159b7a1100000000", "0x0452505352902bb51614ab3779fc4f4892aa8e21582a05a3162aef145209312f48c3b37fc7909618af06", "0x0466726f6e88015cd52a32691b3d44a3cef762382d728668dbee8c4509c697efe25708d5e6ffd400", "0x05617572610101809dd98345fce7c411d130f73a50b2e37d73efe027964dd63ce064275257cc1afb3192c7885ec1813c89350463bce9cd8b4f183b6e8cd779643ff4c476795e83" ] } }, "id": 1 } ``` ``` ```typescript async function main() { const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const [chain, nodeName, nodeVersion, runtime] = await Promise.all([ api.rpc.system.chain(), api.rpc.system.name(), api.rpc.system.version(), api.rpc.state.getRuntimeVersion() ]); console.log(`Connected to ${chain.toString()} via ${nodeName} ${nodeVersion}`); console.log(`specVersion=${runtime.specVersion.toString()}, transactionVersion=${runtime.transactionVersion}`); const header = await api.rpc.chain.getHeader(); console.log(`Latest block #${header.number} (${header.hash.toHex()})`); await api.disconnect(); } main().catch(console.error); ``` ```rust use subxt::{config::substrate::SubstrateConfig, OnlineClient}; #[tokio::main] async fn main() -> Result<(), Box> { let api = OnlineClient::::from_url( "wss://api-astar.n.dwellir.com/YOUR_API_KEY" ).await?; let block_hash = api.rpc().finalized_head().await?; let header = api.rpc().header(Some(block_hash)).await?.expect("header"); println!("Finalized block #{:?}", header.number); println!("State root {:?}", header.state_root); Ok(()) } ``` ```python from substrateinterface import SubstrateInterface api = SubstrateInterface( url="wss://api-astar.n.dwellir.com/YOUR_API_KEY", ss58_format=5, type_registry_preset="substrate-node-template" ) runtime = api.get_runtime_version() print("specVersion", runtime['specVersion'], "transactionVersion", runtime['transactionVersion']) account = api.query( module='System', storage_function='Account', params=['ZEyDXf6563rc78ibEtYQAkHTSKLzMES1m2BrPNdLcma57Tg'] ) print("Free balance", account.value['data']['free']) ``` ## Network Information | Parameter | Astar Mainnet | Shiden Canary | Shibuya Testnet | |-----------|---------------|---------------|-----------------| | Relay chain | Polkadot | Kusama | Tokyo (Astar-managed) | | Parachain ID | 2006 | 2007 | 1000 | | Genesis hash | `0x9eb76c5184c4ab8679d2d5d819fdf90b9c001403e9e17da2e14b6d8aec4029c6` | `—` | `—` | | Runtime (2025-10-03) | specVersion `1700`, transactionVersion `3` | specVersion `1700` | specVersion `1700` | | Unit symbol | ASTR | SDN | SBY | | Decimals | 18 | 18 | 18 | | SS58 prefix | 5 | 5 | 5 | | Explorer | astar.subscan.io | shiden.subscan.io | shibuya.subscan.io | - Genesis hash recorded via `chain_getBlockHash(0)` on 2025-10-03. - Shiden (Kusama canary) and Shibuya (public testnet) provide staging environments for runtime upgrades before they reach mainnet ([Astar network overview](https://docs.astar.network/docs/learn/networks/)). ## Available JSON-RPC Methods Astar exposes the full Substrate RPC surface, plus Frontier EVM methods. Core namespaces documented in this section: | Group | Purpose | Key Methods | |-------|---------|-------------| | `system_*` | Node health, metadata, peer info | [`system_health`](/astar/system_health), [`system_version`](/astar/system_version), [`system_chain`](/astar/system_chain) | | `chain_*` | Blocks, headers, finality, subscriptions | [`chain_getHeader`](/astar/chain_getHeader), [`chain_getBlock`](/astar/chain_getBlock), [`chain_subscribeFinalizedHeads`](/astar/chain_subscribeFinalizedHeads) | | `state_*` | Storage queries, metadata, runtime data | [`state_getStorage`](/astar/state_getStorage), [`state_getRuntimeVersion`](/astar/state_getRuntimeVersion), [`state_getKeysPaged`](/astar/state_getKeysPaged) | | `author_*` | Extrinsic submission and queue inspection | [`author_submitExtrinsic`](/astar/author_submitExtrinsic), [`author_pendingExtrinsics`](/astar/author_pendingExtrinsics) | | `payment_*` | Fee estimation for Substrate extrinsics | [`payment_queryInfo`](/astar/payment_queryInfo), [`payment_queryFeeDetails`](/astar/payment_queryFeeDetails) | | `rpc_methods` | Enumerate RPC namespaces exposed by the node | [`rpc_methods`](/astar/rpc_methods) | Frontier also enables Ethereum-compatible `eth_*`, `net_*`, and `web3_*` endpoints for EVM wallets. ## Common Integration Patterns ### Subscribe to new heads for live indexing ```typescript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); api.rpc.chain.subscribeNewHeads((header) => { console.log(`Astar block #${header.number.toString()} => ${header.hash.toHex()}`); }); ``` ### Fetch native balances via raw storage key ```bash # System.Account for 5-digit treasury account curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getStorage", "params": [ "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9e3a5c81a65b0e6ba8e72e48e58704482922ee694ea772dc63a575845fa57a0c5ea93dfdc2a93ec631d9e426962f1e311" ], "id": 42 }' ``` Decode the SCALE-encoded result with polkadot.js or `py-substrate-interface` to access `data.free`, `data.reserved`, and staking locks. ### Pre-flight fees before submitting extrinsics ```typescript const api = await ApiPromise.create({ provider: new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY') }); const tx = api.tx.balances.transferKeepAlive( '5DAAnrj7VHTz5xy1mJQp7vR8J33ePZ8WqWnVfHfV9bPp7PPV', 1_000_000_000_000 ); const info = await api.rpc.payment.queryInfo(tx.toHex()); console.log(info.toHuman()); ``` ## Performance Best Practices - Prefer WebSocket connections for subscriptions and batched queries; fall back to HTTPS for stateless workloads. - Cache runtime metadata keyed by the latest `specVersion` to avoid re-fetching on every request. - Use `state_getKeysPaged` or `state_getStoragePaged` with bounded page sizes when crawling large maps such as staking ledgers. - Track upgrade announcements on the [Astar forum](https://forum.astar.network/) and rehearse changes on Shiden before promoting them to mainnet. - Implement exponential backoff around `author_submitExtrinsic`; Frontier queues may temporarily reject payloads when Ethereum traffic spikes. ## Troubleshooting | Symptom | Likely Cause | Resolution | |---------|--------------|------------| | `API key does not exist` errors | Misconfigured Dwellir endpoint or expired key | Re-issue the key via the [Dwellir dashboard](https://dashboard.dwellir.com/register) and update environment variables. | | WebSocket disconnects on idle workloads | Provider closes idle connections | Enable heartbeat pings or reconnect logic every 30 seconds. ## Smoke Tests Run these checks before promoting to production: 1. **system_health** — expect `isSyncing: false` and peer count > 8. 2. **chain_getHeader** — confirm block numbers advance every ~6 seconds. 3. **state_getStorage(System.Account)** — verify SCALE decoding of balances for a known treasury or team account. 4. **payment_queryInfo** on a signed extrinsic — validate fee model before broadcasting from CI/CD. ## Resources & Tools - [Astar Documentation](https://docs.astar.network/) — network architecture, node operations, and dApp staking guides. - [Astar GitHub Releases](https://github.com/AstarNetwork/Astar/releases) — runtime and client binaries. - [Dwellir Astar Network Page](https://www.dwellir.com/networks/astar) — managed endpoints and quick-start snippets. - [Astar Subscan Explorer](https://astar.subscan.io) — block, extrinsic, and account analytics for monitoring deployments. Ready to deploy? Spin up a staging environment on Shibuya, soak test on Shiden, then cut over to Astar mainnet with confidence. --- ## net_listening - Astar RPC Method # net_listening Returns `true` if client is actively listening for network connections on Astar. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if listening | ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const listening = await provider.send('net_listening', []); console.log('Node listening:', listening); ``` ## Related Methods - [`net_peerCount`](./net_peerCount) - Get peer count --- ## net_peerCount - Astar RPC Method # net_peerCount Returns number of peers currently connected to Astar client. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Number of connected peers (hexadecimal) | ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const peerCount = await provider.send('net_peerCount', []); console.log('Peer count:', parseInt(peerCount, 16)); ``` ## Related Methods - [`net_listening`](./net_listening) - Check if listening --- ## net_version - Astar RPC Method # net_version Returns the current network ID on Astar. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Network ID as a string | ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const networkId = await provider.send('net_version', []); console.log('Network ID:', networkId); ``` ## Related Methods - [`eth_chainId`](./eth_chainId) - Get chain ID --- ## payment_queryFeeDetails - Astar RPC Method # payment_queryFeeDetails Returns a detailed breakdown of fees for a given extrinsic on Astar. Unlike `payment_queryInfo` which returns the total fee, this method separates the fee into its component parts. ## Use Cases - **Fee analysis** - Understand fee composition for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Optimization** - Identify which fee component dominates costs - **Debugging** - Diagnose unexpected fee amounts ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `Bytes` | Yes | SCALE-encoded extrinsic (signed or unsigned) | | `blockHash` | `Hash` | No | Block hash for fee calculation context | ## Returns | Field | Type | Description | |-------|------|-------------| | `inclusionFee` | `Option` | Fee details (null for unsigned extrinsics) | ### InclusionFee Structure | Field | Type | Description | |-------|------|-------------| | `baseFee` | `Balance` | Fixed base fee per extrinsic | | `lenFee` | `Balance` | Fee based on encoded extrinsic length | | `adjustedWeightFee` | `Balance` | Fee based on execution weight | ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "payment_queryFeeDetails", "params": ["0x...encodedExtrinsic"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Create a sample transfer const tx = api.tx.balances.transferKeepAlive( '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 1000000000000n ); // Get fee details const feeDetails = await api.rpc.payment.queryFeeDetails(tx.toHex()); if (feeDetails.inclusionFee.isSome) { const fee = feeDetails.inclusionFee.unwrap(); console.log('Base fee:', fee.baseFee.toString()); console.log('Length fee:', fee.lenFee.toString()); console.log('Weight fee:', fee.adjustedWeightFee.toString()); } await api.disconnect(); ``` ```python url = 'https://api-astar.n.dwellir.com/YOUR_API_KEY' # Replace with actual encoded extrinsic encoded_extrinsic = '0x...' payload = { 'jsonrpc': '2.0', 'method': 'payment_queryFeeDetails', 'params': [encoded_extrinsic], 'id': 1 } response = requests.post(url, json=payload) result = response.json()['result'] if result['inclusionFee']: fee = result['inclusionFee'] print(f"Base fee: {fee['baseFee']}") print(f"Length fee: {fee['lenFee']}") print(f"Weight fee: {fee['adjustedWeightFee']}") ``` ## Fee Components Explained | Component | Calculation | Optimization | |-----------|-------------|--------------| | **Base fee** | Fixed per extrinsic | Batch calls to share base fee | | **Length fee** | `length * lengthToFee` | Minimize call data size | | **Weight fee** | `weight * weightToFee` | Choose efficient operations | ## Related Methods - [`payment_queryInfo`](./payment_queryInfo) - Get total fee estimate - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction - [`state_call`](./state_call) - Call TransactionPaymentApi directly --- ## payment_queryInfo - Astar RPC Method # payment_queryInfo Estimates the fee for an extrinsic on Astar. ## Use Cases - **Fee estimation** - Calculate transaction costs before sending - **UI display** - Show fees to users for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Transaction planning** - Ensure sufficient funds ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `String` | Yes | Hex-encoded unsigned extrinsic | | `blockHash` | `String` | No | Block hash for fee calculation | ## Request ```json { "jsonrpc": "2.0", "method": "payment_queryInfo", "params": ["0x..."], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `weight` | `Object` | Transaction weight | | `class` | `String` | Dispatch class | | `partialFee` | `String` | Estimated fee | ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "payment_queryInfo", "params": ["0x..."], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Create transfer (unsigned for estimation) const transfer = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000); const info = await transfer.paymentInfo('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'); console.log('Partial fee:', info.partialFee.toHuman()); await api.disconnect(); ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction --- ## rpc_methods - Astar RPC Method # rpc_methods Returns a list of all RPC methods available on Astar. ## Use Cases - **API discovery** - List all available methods - **Compatibility checking** - Verify method availability for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Documentation** - Auto-generate method lists ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const methods = await api.rpc.rpc.methods(); console.log('Available methods:', methods.methods.length); await api.disconnect(); ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## state_call - Astar RPC Method # state_call Calls a runtime API method on Astar. ## Use Cases - **Runtime computations** - Execute runtime logic without transactions - **Account queries** - Use AccountNonceApi for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Fee estimation** - Use TransactionPaymentApi ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `method` | `String` | Yes | Runtime API method name | | `data` | `String` | Yes | SCALE-encoded call data | | `blockHash` | `String` | No | Block hash for historical call | ## Request ```json { "jsonrpc": "2.0", "method": "state_call", "params": ["AccountNonceApi_account_nonce", "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"], "id": 1 } ``` ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_call", "params": ["AccountNonceApi_account_nonce", "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get account nonce via runtime API const account = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const result = await api.call.accountNonceApi.accountNonce(account); console.log('Account nonce:', result.toNumber()); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Query storage - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## state_getKeys ## Description Returns storage keys with a given prefix. Because Astar staking maps can be large, use this method sparingly and follow with `state_getKeysPaged` for controlled pagination. ## Parameters | Position | Type | Description | |----------|------|-------------| | 0 | string | Storage key prefix in hex | | 1 *(optional)* | string | Block hash | | 2 *(optional)* | number | Result limit (ignored on some node versions) | ## Request Example Get collator session keys by prefixing `Session.NextKeys` (no account parameter). ```json { "jsonrpc": "2.0", "method": "state_getKeys", "params": [ "0xcec5070d609dd3497f72bde07fc96ba04c014e6bf8b8c2c011e7290b85696bb3", null, 5 ], "id": 7 } ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 7, "result": [ "0xcec5070d609dd3497f72bde07fc96ba04c014e6bf8b8c2c011e7290b85696bb30165c612f75544f29a2b2224d8a6944df8f70196c856ae141ecf1aeb3de10d54461317f2fdeae21b", "0xcec5070d609dd3497f72bde07fc96ba04c014e6bf8b8c2c011e7290b85696bb302a1a4c9e333badf063b6446a3e6b0781d73ea137f9c74f59918312cb7938a1f234287ea08418633", "…" ] } ``` If a node returns `Response is too big`, switch to `state_getKeysPaged` with smaller page sizes. ## Code Examples ```python substrate = SubstrateInterface(url="wss://api-astar.n.dwellir.com/YOUR_API_KEY", ss58_format=5) prefix = substrate.generate_storage_hash('Session', 'NextKeys') keys = substrate.rpc_request('state_getKeys', [prefix, None, 5])['result'] print(keys[:3]) ``` ```typescript const prefix = api.query.session.nextKeys.keyPrefix(); const keys = await api.rpc.state.getKeys(prefix.toHex()); console.log(`Returned ${keys.length} keys`); ``` --- ## state_getKeysPaged - Astar RPC Method # state_getKeysPaged Returns storage keys with pagination on Astar. ## Use Cases - **Storage iteration** - Enumerate storage map entries - **Data export** - Bulk export chain data for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Account enumeration** - List all accounts ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `prefix` | `String` | Yes | Storage key prefix | | `count` | `Number` | Yes | Maximum keys to return | | `startKey` | `String` | No | Key to start after | | `blockHash` | `String` | No | Block hash for historical query | ## Request ```json { "jsonrpc": "2.0", "method": "state_getKeysPaged", "params": ["0x...", 100], "id": 1 } ``` ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getKeysPaged", "params": ["0x26aa394eea5630e07c48ae0c9558cef7", 100], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get all accounts (paginated) const keys = await api.rpc.state.getKeysPaged( api.query.system.account.keyPrefix(), 100 ); console.log('Found accounts:', keys.length); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Get storage value - [`state_queryStorageAt`](./state_queryStorageAt) - Batch storage query --- ## state_getMetadata - Astar RPC Method # state_getMetadata Returns the runtime metadata on Astar. ## Use Cases - **Runtime introspection** - Discover available pallets and calls - **Extrinsic building** - Get call and type information for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Storage key generation** - Build storage keys from metadata - **Client generation** - Auto-generate typed APIs ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash for historical metadata | ## Request ```json { "jsonrpc": "2.0", "method": "state_getMetadata", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getMetadata", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get runtime metadata const metadata = await api.rpc.state.getMetadata(); // List available pallets const pallets = metadata.asLatest.pallets.map(p => p.name.toString()); console.log('Available pallets:', pallets); // Get specific pallet info const systemPallet = metadata.asLatest.pallets.find(p => p.name.toString() === 'System'); console.log('System pallet calls:', systemPallet.calls.isSome ? 'Available' : 'None'); await api.disconnect(); ``` ```python def get_metadata(): url = 'https://api-astar.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'state_getMetadata', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] metadata_hex = get_metadata() print(f'Metadata length: {len(metadata_hex)} bytes') ``` ## Related Methods - [`state_getRuntimeVersion`](./state_getRuntimeVersion) - Get runtime version - [`state_getStorage`](./state_getStorage) - Query storage --- ## state_getRuntimeVersion - Astar RPC Method # state_getRuntimeVersion Returns the runtime version on Astar. ## Use Cases - **Version checking** - Verify runtime compatibility - **Upgrade detection** - Monitor for runtime upgrades on cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Client compatibility** - Ensure API compatibility ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash for historical version | ## Request ```json { "jsonrpc": "2.0", "method": "state_getRuntimeVersion", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getRuntimeVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const version = await api.rpc.state.getRuntimeVersion(); console.log('Spec name:', version.specName.toString()); console.log('Spec version:', version.specVersion.toNumber()); console.log('Impl version:', version.implVersion.toNumber()); await api.disconnect(); ``` ```python def get_runtime_version(): url = 'https://api-astar.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'state_getRuntimeVersion', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] version = get_runtime_version() print(f"Spec: {version['specName']} v{version['specVersion']}") ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata - [`system_version`](./system_version) - Get node version --- ## state_getStorage - Astar RPC Method # state_getStorage Returns a storage entry at a specific key on Astar. > **Why Astar?** Build on Polkadot's leading dApp hub supporting EVM, WASM, and upcoming PolkaVM environments with EVM + WASM + PolkaVM support, Build2Earn developer rewards, dApp Staking, and Soneium cross-layer integration. ## Use Cases - **State queries** - Read on-chain storage values - **Account balances** - Query account data for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Pallet storage** - Access runtime storage items - **Historical state** - Query state at specific blocks ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `key` | `String` | Yes | Storage key (hex-encoded) | | `blockHash` | `String` | No | Block hash for historical query | ## Request ```json { "jsonrpc": "2.0", "method": "state_getStorage", "params": [""], "id": 1 } ``` ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getStorage", "params": [""], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query account balance const account = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const accountInfo = await api.query.system.account(account); console.log('Free balance:', accountInfo.data.free.toString()); // Query at specific block const blockHash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'; const historicalBalance = await api.query.system.account.at(blockHash, account); console.log('Historical balance:', historicalBalance.data.free.toString()); await api.disconnect(); ``` ```python def get_storage(key, block_hash=None): url = 'https://api-astar.n.dwellir.com/YOUR_API_KEY' params = [key] if block_hash is None else [key, block_hash] payload = { 'jsonrpc': '2.0', 'method': 'state_getStorage', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] # Query :code storage (runtime wasm) storage_key = '' value = get_storage(storage_key) print(f'Storage value: {value[:66]}...' if value else 'None') ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata - [`state_getKeysPaged`](./state_getKeysPaged) - Enumerate storage keys --- ## state_queryStorageAt - Astar RPC Method # state_queryStorageAt Query multiple storage keys at a specific block on Astar. ## Use Cases - **Batch queries** - Efficiently query multiple storage items - **Snapshot state** - Get consistent multi-key state for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Data analysis** - Compare storage across blocks ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `keys` | `Array` | Yes | Array of storage keys | | `blockHash` | `String` | No | Block hash for query | ## Request ```json { "jsonrpc": "2.0", "method": "state_queryStorageAt", "params": [[""]], "id": 1 } ``` ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_queryStorageAt", "params": [[""]], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query multiple accounts at once const accounts = ['5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY']; const entries = await api.query.system.account.multi(accounts); entries.forEach((info, idx) => { console.log(`Account ${idx}: ${info.data.free.toString()}`); }); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Single storage query - [`state_getKeysPaged`](./state_getKeysPaged) - Enumerate keys --- ## system_chain - Astar RPC Method # system_chain Returns the chain name on Astar. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const chain = await api.rpc.system.chain(); console.log('Chain:', chain.toString()); await api.disconnect(); ``` ## Related Methods - [`system_name`](./system_name) - Get node implementation name - [`system_version`](./system_version) - Get node version --- ## system_health - Astar RPC Method # system_health Returns the health status of the Astar node. ## Use Cases - **Health checks** - Monitor node availability - **Load balancing** - Route traffic based on health for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **Sync status** - Verify node is synced ## Parameters This method accepts no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `peers` | `Number` | Connected peer count | | `isSyncing` | `Boolean` | Whether node is syncing | | `shouldHavePeers` | `Boolean` | Whether node should have peers | ## Request ```json { "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const health = await api.rpc.system.health(); console.log('Peers:', health.peers.toNumber()); console.log('Is syncing:', health.isSyncing.isTrue); await api.disconnect(); ``` ```python def get_health(): url = 'https://api-astar.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'system_health', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] health = get_health() print(f"Peers: {health['peers']}") print(f"Syncing: {health['isSyncing']}") ``` ## Related Methods - [`system_version`](./system_version) - Get node version - [`system_chain`](./system_chain) - Get chain name --- ## system_name - Astar RPC Method # system_name Returns the node implementation name on Astar. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_name", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_name", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const name = await api.rpc.system.name(); console.log('Node name:', name.toString()); await api.disconnect(); ``` ## Related Methods - [`system_version`](./system_version) - Get node version - [`system_chain`](./system_chain) - Get chain name --- ## system_properties - Astar RPC Method # system_properties Returns chain properties including token symbol and decimals on Astar. ## Use Cases - **Token formatting** - Get decimals and symbol for cross-chain DeFi, multi-VM smart contracts, and XCM-enabled interoperability with Ethereum and Cosmos - **UI configuration** - Configure wallets and dApps - **Address formatting** - Get SS58 prefix ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_properties", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_properties", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const props = await api.rpc.system.properties(); console.log('Token symbol:', props.tokenSymbol.toString()); console.log('Token decimals:', props.tokenDecimals.toString()); console.log('SS58 prefix:', props.ss58Format.toString()); await api.disconnect(); ``` ## Related Methods - [`system_chain`](./system_chain) - Get chain name - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## system_version - Astar RPC Method # system_version Returns the node implementation version on Astar. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_version", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-astar.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_version", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-astar.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const version = await api.rpc.system.version(); console.log('Version:', version.toString()); await api.disconnect(); ``` ## Related Methods - [`system_chain`](./system_chain) - Get chain name - [`state_getRuntimeVersion`](./state_getRuntimeVersion) - Get runtime version --- ## web3_clientVersion - Astar RPC Method # web3_clientVersion Returns the current client version on Astar. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Client version string | ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); const version = await provider.send('web3_clientVersion', []); console.log('Client version:', version); ``` --- ## web3_sha3 - Astar RPC Method # web3_sha3 Returns Keccak-256 (not standard SHA3-256) of the given data on Astar. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `data` | `DATA` | Yes | Data to hash | ## Request ```json { "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Keccak-256 hash of the data | ## Code Examples ```bash curl -X POST https://api-astar.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-astar.n.dwellir.com/YOUR_API_KEY'); // Using RPC const hash = await provider.send('web3_sha3', ['0x68656c6c6f']); console.log('Hash:', hash); // Using ethers directly (faster) const localHash = keccak256(toUtf8Bytes('hello')); console.log('Local hash:', localHash); ``` --- ## debug_traceBlock - Avalanche RPC Method # debug_traceBlock Traces all transactions in a block on Avalanche by block RLP. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Analyze transaction execution step-by-step - **Smart contract analysis** - Debug contract interactions - **Security auditing** - Trace internal calls for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockRlp` | `DATA` | Yes | RLP-encoded block data | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); // Use debug_traceBlockByNumber instead (more practical) const traces = await provider.send('debug_traceBlockByNumber', ['latest', {}]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by block number - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by block hash --- ## debug_traceBlockByHash - Avalanche RPC Method # debug_traceBlockByHash Traces all transactions in a block on Avalanche by block hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0xb40d80aebafa6c7598ca8bc978354fa1c44f34b08c3f328882b714cb533615bb", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0xb40d80aebafa6c7598ca8bc978354fa1c44f34b08c3f328882b714cb533615bb", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const blockHash = '0xb40d80aebafa6c7598ca8bc978354fa1c44f34b08c3f328882b714cb533615bb'; const traces = await provider.send('debug_traceBlockByHash', [blockHash, { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by number - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceBlockByNumber - Avalanche RPC Method # debug_traceBlockByNumber Traces all transactions in a block on Avalanche by block number. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const traces = await provider.send('debug_traceBlockByNumber', ['latest', { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by hash - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceCall - Avalanche RPC Method # debug_traceCall Traces a call without creating a transaction on Avalanche. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction simulation** - Debug before sending - **Gas analysis** - Analyze gas usage per opcode - **Contract debugging** - Step through execution for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `call` | `Object` | Yes | Call object (same as eth_call) | | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ { "to": "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "data": "0x70a0823100000000000000000000000009383137c1eee3e1a8bc781228e4199f6b4a9bbf" }, "latest", {} ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ {"to": "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "data": "0x70a0823100000000000000000000000009383137c1eee3e1a8bc781228e4199f6b4a9bbf"}, "latest", {"tracer": "callTracer"} ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const trace = await provider.send('debug_traceCall', [ { to: '0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf', data: '0x70a0823100000000000000000000000009383137c1eee3e1a8bc781228e4199f6b4a9bbf' }, 'latest', { tracer: 'callTracer' } ]); console.log('Trace:', trace); ``` ## Related Methods - [`eth_call`](./eth_call) - Execute call without trace - [`debug_traceTransaction`](./debug_traceTransaction) - Trace actual transaction --- ## debug_traceTransaction - Avalanche RPC Method # debug_traceTransaction Traces a transaction execution on Avalanche by transaction hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Understand exactly what happened - **Failure analysis** - Find where and why a transaction reverted - **Gas optimization** - Analyze gas usage for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Tracer Options - `{}` - Default opcode tracer (verbose) - `{ tracer: "callTracer" }` - Call tree tracer - `{ tracer: "prestateTracer" }` - Pre-state tracer ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0xfe055919188f8e2360bead9ecd97ffa782c610730e9084c6533f799bafafa7e4", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0xfe055919188f8e2360bead9ecd97ffa782c610730e9084c6533f799bafafa7e4", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const txHash = '0xfe055919188f8e2360bead9ecd97ffa782c610730e9084c6533f799bafafa7e4'; // Call tracer - shows internal calls const callTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'callTracer' } ]); console.log('Type:', callTrace.type); console.log('From:', callTrace.from); console.log('To:', callTrace.to); console.log('Gas used:', parseInt(callTrace.gasUsed, 16)); // Prestate tracer - shows state before execution const prestateTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'prestateTracer' } ]); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) tx_hash = '0xfe055919188f8e2360bead9ecd97ffa782c610730e9084c6533f799bafafa7e4' # Call tracer trace = w3.provider.make_request('debug_traceTransaction', [ tx_hash, {'tracer': 'callTracer'} ]) print(f'Trace type: {trace["result"]["type"]}') print(f'Gas used: {int(trace["result"]["gasUsed"], 16)}') ``` ## Related Methods - [`debug_traceCall`](./debug_traceCall) - Trace without executing - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace entire block --- ## eth_accounts - Avalanche RPC Method # eth_accounts Returns a list of addresses owned by the client on Avalanche. > **Why Avalanche?** Build on the fastest smart contract platform with sub-second finality and customizable L1 subnets with sub-second finality, Evergreen subnets for institutions, and partnerships with Franklin Templeton, VanEck, and Bergen County. ## Important Note On public RPC endpoints like Dwellir, `eth_accounts` returns an empty array because the node does not hold any private keys. This method is primarily useful for: - Local development nodes (Ganache, Hardhat, Anvil) - Private nodes with managed accounts - Wallet provider connections (MetaMask injects accounts) ## When to Use This Method `eth_accounts` is relevant for enterprise developers, RWA tokenizers, and teams building custom blockchain networks in specific scenarios: - **Development Testing** — Retrieve test accounts from local nodes - **Wallet Detection** — Check if a wallet provider has connected accounts - **Client Verification** — Confirm node account access capabilities ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `Array` | List of 20-byte account addresses owned by the client | **Return format**: Array of `0x` prefixed hexadecimal addresses (typically empty for public nodes) ## Request ```json { "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 } ``` ## Response ### Successful Response (Public Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [] } ``` ### Successful Response (Local Development Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [ "0x407d73d8a49eeb85d32cf465507dd71d507100c1", "0x85d32cf465507dd71d507100c1407d73d8a49eeb" ] } ``` ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_accounts', params: [], id: 1 }) }); const { result } = await response.json(); console.log('Accounts:', result); // Using ethers.js const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const accounts = await provider.listAccounts(); console.log('Accounts:', accounts); ``` ```python def get_accounts(): response = requests.post( 'https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc', json={ 'jsonrpc': '2.0', 'method': 'eth_accounts', 'params': [], 'id': 1 } ) return response.json()['result'] accounts = get_accounts() print(f'Accounts: {accounts}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) print(f'Accounts: {w3.eth.accounts}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/rpc" ) func main() { client, err := rpc.Dial("https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc") if err != nil { log.Fatal(err) } var accounts []string err = client.CallContext(context.Background(), &accounts, "eth_accounts") if err != nil { log.Fatal(err) } fmt.Printf("Accounts: %v\n", accounts) } ``` ## Common Use Cases ### 1. Development Environment Detection Check if running against a development node with test accounts: ```javascript async function isDevEnvironment(provider) { const accounts = await provider.listAccounts(); return accounts.length > 0; } const isDev = await isDevEnvironment(provider); if (isDev) { console.log('Development environment detected'); } ``` ### 2. Wallet Connection Check Verify wallet provider has connected accounts: ```javascript async function checkWalletConnection() { if (typeof window.ethereum === 'undefined') { return { connected: false, reason: 'No wallet detected' }; } const accounts = await window.ethereum.request({ method: 'eth_accounts' }); return { connected: accounts.length > 0, accounts: accounts }; } ``` ### 3. Fallback Account Selection Use first available account or request connection: ```javascript async function getActiveAccount() { // Check existing connections let accounts = await window.ethereum.request({ method: 'eth_accounts' }); // Request connection if no accounts if (accounts.length === 0) { accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); } return accounts[0] || null; } ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32601 | Method not found | Node may not support this method | | -32603 | Internal error | Retry with exponential backoff | ```javascript async function safeGetAccounts(provider) { try { const accounts = await provider.listAccounts(); return { success: true, accounts }; } catch (error) { if (error.code === -32601) { console.warn('eth_accounts not supported on this node'); return { success: false, accounts: [], reason: 'unsupported' }; } throw error; } } ``` ## Related Methods - [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102) — Request wallet connection (browser wallets) - [`eth_getBalance`](./eth_getBalance) — Get account balance - [`eth_getTransactionCount`](./eth_getTransactionCount) — Get account nonce --- ## eth_blockNumber - Avalanche RPC Method # eth_blockNumber Returns the number of the most recent block on Avalanche. > **Why Avalanche?** Build on the fastest smart contract platform with sub-second finality and customizable L1 subnets with sub-second finality, Evergreen subnets for institutions, and partnerships with Franklin Templeton, VanEck, and Bergen County. ## When to Use This Method `eth_blockNumber` is fundamental for enterprise developers, RWA tokenizers, and teams building custom blockchain networks: - **Syncing Applications** — Keep your dApp in sync with the latest Avalanche blockchain state - **Transaction Monitoring** — Verify confirmations by comparing block numbers - **Event Filtering** — Set the correct block range for querying logs on institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains - **Health Checks** — Monitor node connectivity and sync status ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `QUANTITY` | Hexadecimal string representing the current block number | **Return format**: `0x` prefixed hexadecimal (e.g., `0x5BAD55` = 6,008,149 in decimal) ## Request ```json { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } ``` ## Response ### Successful Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5BAD55" } ``` ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error" } } ``` ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }) }); const { result } = await response.json(); const blockNumber = parseInt(result, 16); console.log('Avalanche block:', blockNumber); // Using ethers.js const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const blockNumber = await provider.getBlockNumber(); console.log('Avalanche block:', blockNumber); ``` ```python def get_block_number(): response = requests.post( 'https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc', json={ 'jsonrpc': '2.0', 'method': 'eth_blockNumber', 'params': [], 'id': 1 } ) result = response.json()['result'] return int(result, 16) block_number = get_block_number() print(f'Avalanche block: {block_number}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) print(f'Avalanche block: {w3.eth.block_number}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc") if err != nil { log.Fatal(err) } blockNumber, err := client.BlockNumber(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Avalanche block: %d\n", blockNumber) } ``` ## Common Use Cases ### 1. Block Confirmation Counter Monitor transaction confirmations on Avalanche: ```javascript async function getConfirmations(provider, txHash) { const tx = await provider.getTransaction(txHash); if (!tx || !tx.blockNumber) return 0; const currentBlock = await provider.getBlockNumber(); return currentBlock - tx.blockNumber + 1; } // Wait for specific confirmations async function waitForConfirmations(provider, txHash, confirmations = 6) { let currentConfirmations = 0; while (currentConfirmations < confirmations) { currentConfirmations = await getConfirmations(provider, txHash); console.log(`Confirmations: ${currentConfirmations}/${confirmations}`); await new Promise(r => setTimeout(r, 2000)); } return true; } ``` ### 2. Event Log Filtering Query events from recent blocks on Avalanche: ```javascript async function getRecentEvents(provider, contract, eventName, blockRange = 100) { const currentBlock = await provider.getBlockNumber(); const fromBlock = currentBlock - blockRange; const filter = contract.filters[eventName](); const events = await contract.queryFilter(filter, fromBlock, currentBlock); return events; } ``` ### 3. Node Health Monitoring Check if your Avalanche node is synced: ```javascript async function checkNodeHealth(provider) { try { const blockNumber = await provider.getBlockNumber(); const block = await provider.getBlock(blockNumber); const now = Date.now() / 1000; const blockAge = now - block.timestamp; if (blockAge > 60) { console.warn(`Node may be behind. Last block was ${blockAge}s ago`); return false; } console.log(`Node healthy. Latest block: ${blockNumber}`); return true; } catch (error) { console.error('Node unreachable:', error); return false; } } ``` ## Performance Optimization ### Caching Strategy Cache block numbers to reduce API calls: ```javascript class BlockNumberCache { constructor(ttl = 2000) { this.cache = null; this.timestamp = 0; this.ttl = ttl; } async get(provider) { const now = Date.now(); if (this.cache && (now - this.timestamp) < this.ttl) { return this.cache; } this.cache = await provider.getBlockNumber(); this.timestamp = now; return this.cache; } invalidate() { this.cache = null; this.timestamp = 0; } } const blockCache = new BlockNumberCache(); ``` ### Batch Requests Combine with other calls for efficiency: ```javascript const batch = [ { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }, { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 }, { jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 } ]; const response = await fetch('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await response.json(); ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32603 | Internal error | Retry with exponential backoff | | -32005 | Rate limit exceeded | Implement rate limiting client-side | | -32000 | Execution reverted | Check node sync status | ```javascript async function safeGetBlockNumber(provider, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await provider.getBlockNumber(); } catch (error) { if (error.code === -32005) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } else if (i === maxRetries - 1) { throw error; } } } } ``` ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) — Get full block details by number - [`eth_getBlockByHash`](./eth_getBlockByHash) — Get block details by hash - [`eth_syncing`](./eth_syncing) — Check if node is still syncing --- ## eth_call - Avalanche RPC Method # eth_call Executes a new message call immediately without creating a transaction on Avalanche. Used for reading smart contract state. > **Why Avalanche?** Build on the fastest smart contract platform with sub-second finality and customizable L1 subnets with sub-second finality, Evergreen subnets for institutions, and partnerships with Franklin Templeton, VanEck, and Bergen County. ## Use Cases The `eth_call` method is essential for: - **Reading contract state** - Query view/pure functions - **Simulating transactions** - Test execution without gas costs - **DeFi integrations** - Check prices, balances, allowances for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains - **Complex queries** - Execute multi-step contract logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | 20-byte address executing the call | | `to` | `DATA` | Yes | 20-byte contract address | | `gas` | `QUANTITY` | No | Gas limit for the call | | `gasPrice` | `QUANTITY` | No | Gas price in wei | | `value` | `QUANTITY` | No | Value to send in wei | | `data` | `DATA` | Yes | Encoded function call data | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_call", "params": [ { "to": "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "data": "0x70a0823100000000000000000000000009383137c1eee3e1a8bc781228e4199f6b4a9bbf" }, "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | The return value of the executed contract function | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000" } ``` ## Code Examples ```bash # Call ERC20 balanceOf function curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{ "to": "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "data": "0x70a0823100000000000000000000000009383137c1eee3e1a8bc781228e4199f6b4a9bbf" }, "latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); // ERC20 ABI for common functions const ERC20_ABI = [ "function balanceOf(address owner) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function totalSupply() view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)" ]; // Read ERC20 token balance async function getTokenBalance(tokenAddress, walletAddress) { const contract = new Contract(tokenAddress, ERC20_ABI, provider); const balance = await contract.balanceOf(walletAddress); const decimals = await contract.decimals(); const symbol = await contract.symbol(); return { raw: balance.toString(), formatted: (Number(balance) / Math.pow(10, decimals)).toFixed(4), symbol: symbol }; } // Direct eth_call async function directCall(to, data) { const result = await provider.call({ to, data }); return result; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) def get_erc20_balance(token_address, wallet_address): # balanceOf(address) selector function_signature = "balanceOf(address)" function_selector = w3.keccak(text=function_signature)[:4].hex() # Encode address parameter encoded_address = wallet_address[2:].lower().zfill(64) data = function_selector + encoded_address # Make the call result = w3.eth.call({ 'to': token_address, 'data': data }) return int(result.hex(), 16) balance = get_erc20_balance( '0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf', '0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf' ) print(f'Balance: {balance}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf") data := common.FromHex("0x70a0823100000000000000000000000009383137c1eee3e1a8bc781228e4199f6b4a9bbf") msg := ethereum.CallMsg{ To: &contractAddress, Data: data, } result, err := client.CallContract(context.Background(), msg, nil) if err != nil { log.Fatal(err) } fmt.Printf("Result: 0x%x\n", result) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Contract function reverted | | -32602 | Invalid parameters | Invalid data encoding | | -32015 | VM execution error | Contract logic error | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas for transaction - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send actual transaction --- ## eth_chainId - Avalanche RPC Method # eth_chainId Returns the chain ID used for transaction signing on Avalanche. > **Why Avalanche?** Build on the fastest smart contract platform with sub-second finality and customizable L1 subnets with sub-second finality, Evergreen subnets for institutions, and partnerships with Franklin Templeton, VanEck, and Bergen County. ## Use Cases The `eth_chainId` method is essential for: - **Transaction signing** - Ensure transactions are signed for the correct network - **Network verification** - Confirm connection to the expected chain - **Multi-chain apps** - Handle different networks programmatically - **Wallet integration** - Validate network before transactions ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Chain ID in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1" } ``` ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const network = await provider.getNetwork(); console.log('Chain ID:', network.chainId); // Verify network before transaction async function verifyNetwork(expectedChainId) { const network = await provider.getNetwork(); if (network.chainId !== BigInt(expectedChainId)) { throw new Error(`Wrong network. Expected ${expectedChainId}, got ${network.chainId}`); } return true; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) chain_id = w3.eth.chain_id print(f'Chain ID: {chain_id}') # Verify network def verify_network(expected_chain_id): chain_id = w3.eth.chain_id if chain_id != expected_chain_id: raise ValueError(f'Wrong network. Expected {expected_chain_id}, got {chain_id}') return True ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc") if err != nil { log.Fatal(err) } chainID, err := client.ChainID(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Chain ID: %d\n", chainID) } ``` ## Related Methods - [`net_version`](./net_version) - Get network version - [`eth_syncing`](./eth_syncing) - Check sync status --- ## eth_coinbase - Get Coinbase Address(Avalanche) # eth_coinbase Returns the client coinbase address on Avalanche C-Chain. ## Parameters This method accepts no parameters. ```json { "jsonrpc": "2.0", "method": "eth_coinbase", "params": [], "id": 64 } ``` ## Returns `DATA`, 20 bytes - the current coinbase address. ## Implementation Example ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_coinbase", "params": [], "id": 64 }' ``` ```javascript const response = await fetch('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_coinbase', params: [], id: 64 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "id": 64, "jsonrpc": "2.0", "result": "0x407d73d8a49eeb85d32cf465507dd71d507100c1" } ``` **Note:** On Avalanche C-Chain, this method may return null or a default address as traditional PoW mining doesn't apply. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Avalanche documentation](/docs/avalanche).* --- ## eth_estimateGas - Avalanche RPC Method # eth_estimateGas Estimates the gas necessary to execute a transaction on Avalanche. > **Why Avalanche?** Build on the fastest smart contract platform with sub-second finality and customizable L1 subnets with sub-second finality, Evergreen subnets for institutions, and partnerships with Franklin Templeton, VanEck, and Bergen County. ## Use Cases The `eth_estimateGas` method is essential for: - **Transaction preparation** - Set appropriate gas limits - **Cost estimation** - Calculate transaction costs before sending - **Error detection** - Identify reverts before spending gas - **DeFi operations** - Estimate costs for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | Sender address | | `to` | `DATA` | No | Recipient address | | `gas` | `QUANTITY` | No | Gas limit | | `gasPrice` | `QUANTITY` | No | Gas price | | `value` | `QUANTITY` | No | Value in wei | | `data` | `DATA` | No | Transaction data | ## Request ```json { "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "to": "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "value": "0x1" }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Estimated gas amount in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5208" } ``` **Note**: `0x5208` = 21000 gas (standard ETH transfer) ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "to": "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "value": "0x1" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); // Estimate simple transfer async function estimateTransfer(to, value) { const gasEstimate = await provider.estimateGas({ to: to, value: parseEther(value) }); console.log('Estimated gas:', gasEstimate.toString()); return gasEstimate; } // Estimate contract call async function estimateContractCall(contract, method, args) { const gasEstimate = await contract[method].estimateGas(...args); console.log('Estimated gas:', gasEstimate.toString()); // Add 20% buffer for safety return gasEstimate * 120n / 100n; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) def estimate_transfer(to, value_in_ether): gas_estimate = w3.eth.estimate_gas({ 'to': to, 'value': w3.to_wei(value_in_ether, 'ether') }) print(f'Estimated gas: {gas_estimate}') return gas_estimate def estimate_contract_call(contract, method, args): func = getattr(contract.functions, method) gas_estimate = func(*args).estimate_gas() # Add 20% buffer return int(gas_estimate * 1.2) # Estimate simple transfer gas = estimate_transfer('0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf', 0.1) ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc") if err != nil { log.Fatal(err) } toAddress := common.HexToAddress("0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf") msg := ethereum.CallMsg{ To: &toAddress, Value: big.NewInt(1000000000000000000), } gasLimit, err := client.EstimateGas(context.Background(), msg) if err != nil { log.Fatal(err) } fmt.Printf("Estimated gas: %d\n", gasLimit) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Transaction would fail | | -32602 | Invalid params | Invalid transaction parameters | **Tip**: If estimation fails, the transaction would likely revert if sent. ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_feeHistory - Avalanche RPC Method # eth_feeHistory Returns historical gas information on Avalanche for fee estimation. ## Use Cases - **Fee prediction** - Estimate future gas prices based on history - **Gas analytics** - Analyze fee trends over time - **Optimal timing** - Find best times for transactions on institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockCount` | `QUANTITY` | Yes | Number of blocks in the range | | `newestBlock` | `QUANTITY\|TAG` | Yes | Highest block of the range | | `rewardPercentiles` | `Array` | Yes | Percentiles to sample for priority fees | ## Request ```json { "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const feeHistory = await provider.send('eth_feeHistory', ['0xa', 'latest', [25, 50, 75]]); console.log('Base fees:', feeHistory.baseFeePerGas.map(f => formatUnits(f, 'gwei'))); console.log('Reward (25th percentile):', feeHistory.reward.map(r => formatUnits(r[0], 'gwei'))); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) fee_history = w3.eth.fee_history(10, 'latest', [25, 50, 75]) print(f'Base fees: {[w3.from_wei(f, "gwei") for f in fee_history["baseFeePerGas"]]}') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee --- ## eth_gasPrice - Avalanche RPC Method # eth_gasPrice Returns the current gas price on Avalanche in wei. > **Why Avalanche?** Build on the fastest smart contract platform with sub-second finality and customizable L1 subnets with sub-second finality, Evergreen subnets for institutions, and partnerships with Franklin Templeton, VanEck, and Bergen County. ## Use Cases The `eth_gasPrice` method is essential for: - **Transaction pricing** - Set appropriate gas prices - **Cost estimation** - Calculate transaction costs before sending - **Gas monitoring** - Track network congestion - **DeFi operations** - Optimize costs for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Current gas price in wei (hexadecimal) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x3b9aca00" } ``` **Note**: `0x3b9aca00` = 1 Gwei (1,000,000,000 wei) ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const feeData = await provider.getFeeData(); const gasPrice = feeData.gasPrice; console.log('Gas Price:', formatUnits(gasPrice, 'gwei'), 'Gwei'); // Calculate transaction cost async function estimateTransactionCost(gasLimit) { const feeData = await provider.getFeeData(); const cost = feeData.gasPrice * BigInt(gasLimit); return formatUnits(cost, 'ether'); } const cost = await estimateTransactionCost(21000); console.log('Transfer cost:', cost, 'ETH'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) gas_price = w3.eth.gas_price print(f'Gas Price: {w3.from_wei(gas_price, "gwei")} Gwei') # Calculate transaction cost def estimate_transaction_cost(gas_limit): gas_price = w3.eth.gas_price cost = gas_price * gas_limit return w3.from_wei(cost, 'ether') cost = estimate_transaction_cost(21000) print(f'Transfer cost: {cost} ETH') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc") if err != nil { log.Fatal(err) } gasPrice, err := client.SuggestGasPrice(context.Background()) if err != nil { log.Fatal(err) } // Convert to Gwei gwei := new(big.Float).Quo( new(big.Float).SetInt(gasPrice), big.NewFloat(1e9), ) fmt.Printf("Gas Price: %f Gwei\n", gwei) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32603 | Internal error | Node error | ## Related Methods - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee (EIP-1559) - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas needed --- ## eth_getBalance - Avalanche RPC Method # eth_getBalance Returns the balance of a given address on Avalanche. > **Why Avalanche?** Build on the fastest smart contract platform with sub-second finality and customizable L1 subnets with sub-second finality, Evergreen subnets for institutions, and partnerships with Franklin Templeton, VanEck, and Bergen County. ## Use Cases The `eth_getBalance` method is essential for: - **Wallet applications** - Display user balances - **Transaction validation** - Check if account has sufficient funds - **DeFi applications** - Monitor collateral and liquidity for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains - **Account monitoring** - Track balance changes over time ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address to check balance for | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Integer of the current balance in wei (hexadecimal) | **Note**: 1 native token = 10^18 wei. Convert using `balance / 10^18`. ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1a055690d9db80000" } ``` ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const address = '0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf'; const balanceWei = await provider.getBalance(address); const balance = formatEther(balanceWei); console.log(`Balance: ${balance}`); // Get balance at specific block const historicalBalance = await provider.getBalance(address, 1000000); console.log(`Historical balance: ${formatEther(historicalBalance)}`); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) address = '0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf' balance_wei = w3.eth.get_balance(address) balance = w3.from_wei(balance_wei, 'ether') print(f'Balance: {balance}') # Get balance at specific block historical_balance = w3.eth.get_balance(address, block_identifier=1000000) print(f'Historical balance: {w3.from_wei(historical_balance, "ether")}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc") if err != nil { log.Fatal(err) } address := common.HexToAddress("0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf") balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } // Convert to ether fbalance := new(big.Float).SetInt(balance) ethValue := new(big.Float).Quo(fbalance, big.NewFloat(1e18)) fmt.Printf("Balance: %f\n", ethValue) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid address format or block parameter | | -32000 | Execution error | Node execution error | ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_getTransactionCount`](./eth_getTransactionCount) - Get account nonce --- ## eth_getBlockByHash - Avalanche RPC Method # eth_getBlockByHash Returns information about a block by hash on Avalanche. > **Why Avalanche?** Build on the fastest smart contract platform with sub-second finality and customizable L1 subnets with sub-second finality, Evergreen subnets for institutions, and partnerships with Franklin Templeton, VanEck, and Bergen County. ## Use Cases The `eth_getBlockByHash` method is essential for: - **Block verification** - Verify block data using its unique hash - **Chain reorganization handling** - Track blocks during reorgs - **Cross-chain bridges** - Verify block finality for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains - **Deterministic queries** - Get consistent block data regardless of chain state ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0xb40d80aebafa6c7598ca8bc978354fa1c44f34b08c3f328882b714cb533615bb", false ], "id": 1 } ``` ## Returns Returns the same block object as `eth_getBlockByNumber`, or `null` if no block is found. | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used | | `transactions` | `Array` | Transaction objects or hashes | ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0xb40d80aebafa6c7598ca8bc978354fa1c44f34b08c3f328882b714cb533615bb", false ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const blockHash = '0xb40d80aebafa6c7598ca8bc978354fa1c44f34b08c3f328882b714cb533615bb'; const block = await provider.getBlock(blockHash); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) block_hash = '0xb40d80aebafa6c7598ca8bc978354fa1c44f34b08c3f328882b714cb533615bb' block = w3.eth.get_block(block_hash) print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc") if err != nil { log.Fatal(err) } blockHash := common.HexToHash("0xb40d80aebafa6c7598ca8bc978354fa1c44f34b08c3f328882b714cb533615bb") block, err := client.BlockByHash(context.Background(), blockHash) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block hash format | | -32000 | Block not found | Block with this hash does not exist | ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) - Get block by number - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number --- ## eth_getBlockByNumber - Avalanche RPC Method # eth_getBlockByNumber Returns information about a block by block number on Avalanche. > **Why Avalanche?** Build on the fastest smart contract platform with sub-second finality and customizable L1 subnets with sub-second finality, Evergreen subnets for institutions, and partnerships with Franklin Templeton, VanEck, and Bergen County. ## Use Cases The `eth_getBlockByNumber` method is essential for: - **Block explorers** - Display complete block information - **Transaction indexers** - Process all transactions in a block - **Analytics platforms** - Analyze blockchain data for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains - **Timestamp verification** - Get block timestamps for time-based logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used by all transactions | | `gasLimit` | `QUANTITY` | Maximum gas allowed in block | | `transactions` | `Array` | Array of transaction objects or hashes | | `baseFeePerGas` | `QUANTITY` | Base fee per gas (EIP-1559) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": { "number": "0x5BAD55", "hash": "0xb40d80aebafa6c7598ca8bc978354fa1c44f34b08c3f328882b714cb533615bb", "parentHash": "0x...", "timestamp": "0x64d8f6d0", "gasUsed": "0x1234", "gasLimit": "0x1c9c380", "transactions": [], "baseFeePerGas": "0x5f5e100" } } ``` ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); // Get latest block const block = await provider.getBlock('latest'); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); console.log('Transactions:', block.transactions.length); // Get block with full transactions const blockWithTxs = await provider.getBlock('latest', true); for (const tx of blockWithTxs.prefetchedTransactions) { console.log('Transaction:', tx.hash); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) # Get latest block block = w3.eth.get_block('latest') print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') print(f'Transactions: {len(block.transactions)}') # Get block with full transactions block_full = w3.eth.get_block('latest', full_transactions=True) for tx in block_full.transactions: print(f'Transaction: {tx.hash.hex()}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc") if err != nil { log.Fatal(err) } // Get latest block block, err := client.BlockByNumber(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) fmt.Printf("Timestamp: %d\n", block.Time()) fmt.Printf("Transactions: %d\n", len(block.Transactions())) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block number or parameter format | | -32000 | Block not found | Block does not exist | ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number - [`eth_getBlockByHash`](./eth_getBlockByHash) - Get block by hash - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_getCode - Avalanche RPC Method # eth_getCode Returns the bytecode at a given address on Avalanche. > **Why Avalanche?** Build on the fastest smart contract platform with sub-second finality and customizable L1 subnets with sub-second finality, Evergreen subnets for institutions, and partnerships with Franklin Templeton, VanEck, and Bergen County. ## Use Cases The `eth_getCode` method is essential for: - **Contract verification** - Check if address is a contract - **Security analysis** - Verify deployed bytecode matches expected - **DeFi integrations** - Validate contracts before interactions - **Protocol analysis** - Analyze contract deployments for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Contract bytecode or `0x` if EOA | ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const address = '0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf'; const code = await provider.getCode(address); if (code === '0x') { console.log('Address is an EOA (externally owned account)'); } else { console.log('Address is a contract'); console.log('Bytecode length:', code.length); } // Check if address is a contract async function isContract(address) { const code = await provider.getCode(address); return code !== '0x'; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) address = '0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf' code = w3.eth.get_code(address) if code == b'': print('Address is an EOA') else: print('Address is a contract') print(f'Bytecode length: {len(code.hex())}') # Check if address is a contract def is_contract(address): code = w3.eth.get_code(address) return code != b'' ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc") if err != nil { log.Fatal(err) } address := common.HexToAddress("0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf") code, err := client.CodeAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } if len(code) == 0 { fmt.Println("Address is an EOA") } else { fmt.Printf("Contract bytecode length: %d\n", len(code)) } } ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_getStorageAt`](./eth_getStorageAt) - Get contract storage --- ## eth_getFilterChanges - Avalanche RPC Method # eth_getFilterChanges Polling method for a filter on Avalanche, returns an array of logs since last poll. ## Use Cases - **Event streaming** - Get new events incrementally - **Real-time monitoring** - Track contract activity for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains - **Efficient indexing** - Process only new events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); // Poll loop async function pollFilter(filterId, interval = 2000) { while (true) { const changes = await provider.send('eth_getFilterChanges', [filterId]); if (changes.length > 0) { console.log('New events:', changes); } await new Promise(r => setTimeout(r, interval)); } } ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter --- ## eth_getFilterLogs - Avalanche RPC Method # eth_getFilterLogs Returns an array of all logs matching filter with given ID on Avalanche. ## Use Cases - **Historical queries** - Get all matching logs for a filter - **Full event history** - Retrieve complete event data for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const logs = await provider.send('eth_getFilterLogs', [filterId]); console.log('All matching logs:', logs.length); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_getLogs - Avalanche RPC Method # eth_getLogs Returns an array of all logs matching a given filter object on Avalanche. > **Why Avalanche?** Build on the fastest smart contract platform with sub-second finality and customizable L1 subnets with sub-second finality, Evergreen subnets for institutions, and partnerships with Franklin Templeton, VanEck, and Bergen County. ## Use Cases The `eth_getLogs` method is essential for: - **Event indexing** - Track contract events for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains - **Token transfers** - Monitor ERC20/ERC721 transfers - **DeFi analytics** - Track swaps, liquidity events, and more - **Notification systems** - Alert on specific on-chain events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block (default: `"latest"`) | | `toBlock` | `QUANTITY\|TAG` | No | Ending block (default: `"latest"`) | | `address` | `DATA\|Array` | No | Contract address(es) to filter | | `topics` | `Array` | No | Array of topic filters | | `blockHash` | `DATA` | No | Filter single block by hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns Array of log objects: | Field | Type | Description | |-------|------|-------------| | `address` | `DATA` | Contract that emitted the log | | `topics` | `Array` | Array of indexed topics | | `data` | `DATA` | Non-indexed log data | | `blockNumber` | `QUANTITY` | Block number | | `transactionHash` | `DATA` | Transaction hash | | `logIndex` | `QUANTITY` | Log index in block | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": [{ "address": "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."], "data": "0x...", "blockNumber": "0x5BAD55", "transactionHash": "0x...", "logIndex": "0x0" }] } ``` ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); // Get Transfer events const TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'; async function getTransferEvents(tokenAddress, fromBlock, toBlock) { const logs = await provider.getLogs({ address: tokenAddress, topics: [TRANSFER_TOPIC], fromBlock: fromBlock, toBlock: toBlock }); return logs.map(log => ({ from: '0x' + log.topics[1].slice(26), to: '0x' + log.topics[2].slice(26), blockNumber: log.blockNumber, transactionHash: log.transactionHash })); } const events = await getTransferEvents( '0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf', 'latest', 'latest' ); console.log('Transfer events:', events); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' def get_transfer_events(token_address, from_block, to_block): logs = w3.eth.get_logs({ 'address': token_address, 'topics': [TRANSFER_TOPIC], 'fromBlock': from_block, 'toBlock': to_block }) events = [] for log in logs: events.append({ 'from': '0x' + log['topics'][1].hex()[26:], 'to': '0x' + log['topics'][2].hex()[26:], 'block': log['blockNumber'], 'tx': log['transactionHash'].hex() }) return events events = get_transfer_events( '0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf', 'latest', 'latest' ) print(f'Found {len(events)} transfer events') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf") transferTopic := common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef") query := ethereum.FilterQuery{ FromBlock: big.NewInt(0), ToBlock: nil, Addresses: []common.Address{contractAddress}, Topics: [][]common.Hash, } logs, err := client.FilterLogs(context.Background(), query) if err != nil { log.Fatal(err) } fmt.Printf("Found %d events\n", len(logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32005 | Query returned more than 10000 results | Reduce block range | | -32602 | Invalid params | Invalid filter parameters | ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create a filter for logs - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for new logs --- ## eth_getStorageAt - Avalanche RPC Method # eth_getStorageAt Returns the value from a storage position at a given address on Avalanche. ## Use Cases - **Contract analysis** - Read raw storage values - **State verification** - Verify contract state - **Security auditing** - Analyze storage layout for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains - **Protocol monitoring** - Track state changes ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte contract address | | `position` | `QUANTITY` | Yes | Storage slot position | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "0x0", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "0x0", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const address = '0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf'; const slot = 0; const storage = await provider.getStorage(address, slot); console.log('Storage at slot 0:', storage); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) address = '0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf' storage = w3.eth.get_storage_at(address, 0) print(f'Storage at slot 0: {storage.hex()}') ``` ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_call`](./eth_call) - Call contract functions --- ## eth_getTransactionByHash - Avalanche RPC Method # eth_getTransactionByHash Returns the information about a transaction by transaction hash on Avalanche. > **Why Avalanche?** Build on the fastest smart contract platform with sub-second finality and customizable L1 subnets with sub-second finality, Evergreen subnets for institutions, and partnerships with Franklin Templeton, VanEck, and Bergen County. ## Use Cases The `eth_getTransactionByHash` method is essential for: - **Transaction tracking** - Get details of pending or confirmed transactions - **Payment verification** - Verify transaction parameters - **Debugging** - Analyze transaction data for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains - **Block explorers** - Display transaction information ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0xfe055919188f8e2360bead9ecd97ffa782c610730e9084c6533f799bafafa7e4"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `hash` | `DATA` | Transaction hash | | `from` | `DATA` | Sender address | | `to` | `DATA` | Recipient address | | `value` | `QUANTITY` | Value in wei | | `gas` | `QUANTITY` | Gas provided | | `gasPrice` | `QUANTITY` | Gas price in wei | | `input` | `DATA` | Transaction input data | | `nonce` | `QUANTITY` | Sender's nonce | | `blockHash` | `DATA` | Block hash (null if pending) | | `blockNumber` | `QUANTITY` | Block number (null if pending) | ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0xfe055919188f8e2360bead9ecd97ffa782c610730e9084c6533f799bafafa7e4"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const txHash = '0xfe055919188f8e2360bead9ecd97ffa782c610730e9084c6533f799bafafa7e4'; const tx = await provider.getTransaction(txHash); if (tx) { console.log('From:', tx.from); console.log('To:', tx.to); console.log('Value:', formatEther(tx.value)); console.log('Block:', tx.blockNumber); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) tx_hash = '0xfe055919188f8e2360bead9ecd97ffa782c610730e9084c6533f799bafafa7e4' tx = w3.eth.get_transaction(tx_hash) if tx: print(f'From: {tx["from"]}') print(f'To: {tx["to"]}') print(f'Value: {w3.from_wei(tx["value"], "ether")}') print(f'Block: {tx["blockNumber"]}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0xfe055919188f8e2360bead9ecd97ffa782c610730e9084c6533f799bafafa7e4") tx, isPending, err := client.TransactionByHash(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Pending: %v\n", isPending) fmt.Printf("Value: %s\n", tx.Value().String()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash format | ## Related Methods - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction receipt - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionCount - Avalanche RPC Method # eth_getTransactionCount Returns the number of transactions sent from an address on Avalanche (the nonce). ## Use Cases - **Transaction building** - Get correct nonce for new transactions - **Account analysis** - Count total outgoing transactions - **Nonce management** - Handle pending transaction queues - **Wallet operations** - Prepare transactions for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag (`pending` for next nonce) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const address = '0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf'; const nonce = await provider.getTransactionCount(address); console.log('Nonce:', nonce); // Get pending nonce for new transaction const pendingNonce = await provider.getTransactionCount(address, 'pending'); console.log('Next nonce:', pendingNonce); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) address = '0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf' nonce = w3.eth.get_transaction_count(address) print(f'Nonce: {nonce}') # Get pending nonce pending_nonce = w3.eth.get_transaction_count(address, 'pending') print(f'Next nonce: {pending_nonce}') ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionReceipt - Avalanche RPC Method # eth_getTransactionReceipt Returns the receipt of a transaction by transaction hash on Avalanche. Receipt is only available for mined transactions. > **Why Avalanche?** Build on the fastest smart contract platform with sub-second finality and customizable L1 subnets with sub-second finality, Evergreen subnets for institutions, and partnerships with Franklin Templeton, VanEck, and Bergen County. ## Use Cases The `eth_getTransactionReceipt` method is essential for: - **Transaction confirmation** - Verify transaction was mined successfully - **Gas analysis** - Check actual gas used vs estimated - **Event parsing** - Read emitted events from logs - **Status verification** - Confirm success/failure for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0xfe055919188f8e2360bead9ecd97ffa782c610730e9084c6533f799bafafa7e4"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `status` | `QUANTITY` | `1` (success) or `0` (failure) | | `transactionHash` | `DATA` | Transaction hash | | `blockHash` | `DATA` | Block hash | | `blockNumber` | `QUANTITY` | Block number | | `gasUsed` | `QUANTITY` | Gas used by this transaction | | `cumulativeGasUsed` | `QUANTITY` | Total gas used in block up to this tx | | `logs` | `Array` | Array of log objects | | `contractAddress` | `DATA` | Created contract address (if deployment) | ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0xfe055919188f8e2360bead9ecd97ffa782c610730e9084c6533f799bafafa7e4"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const txHash = '0xfe055919188f8e2360bead9ecd97ffa782c610730e9084c6533f799bafafa7e4'; const receipt = await provider.getTransactionReceipt(txHash); if (receipt) { console.log('Status:', receipt.status === 1 ? 'Success' : 'Failed'); console.log('Gas Used:', receipt.gasUsed.toString()); console.log('Block:', receipt.blockNumber); console.log('Logs:', receipt.logs.length); // Parse specific events for (const log of receipt.logs) { console.log('Event from:', log.address); } } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) tx_hash = '0xfe055919188f8e2360bead9ecd97ffa782c610730e9084c6533f799bafafa7e4' receipt = w3.eth.get_transaction_receipt(tx_hash) if receipt: status = 'Success' if receipt['status'] == 1 else 'Failed' print(f'Status: {status}') print(f'Gas Used: {receipt["gasUsed"]}') print(f'Block: {receipt["blockNumber"]}') print(f'Logs: {len(receipt["logs"])}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0xfe055919188f8e2360bead9ecd97ffa782c610730e9084c6533f799bafafa7e4") receipt, err := client.TransactionReceipt(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Status: %d\n", receipt.Status) fmt.Printf("Gas Used: %d\n", receipt.GasUsed) fmt.Printf("Logs: %d\n", len(receipt.Logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash | **Note**: Returns `null` if transaction is not yet mined. ## Related Methods - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details - [`eth_getLogs`](./eth_getLogs) - Query logs by filter --- ## eth_maxPriorityFeePerGas - Avalanche RPC Method # eth_maxPriorityFeePerGas Returns the current recommended priority fee per gas on Avalanche for EIP-1559 transactions. ## Use Cases - **EIP-1559 transactions** - Set appropriate priority fees - **Transaction acceleration** - Calculate tips for faster inclusion - **Gas optimization** - Balance speed vs cost for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const feeData = await provider.getFeeData(); console.log('Max Priority Fee:', formatUnits(feeData.maxPriorityFeePerGas, 'gwei'), 'Gwei'); console.log('Max Fee Per Gas:', formatUnits(feeData.maxFeePerGas, 'gwei'), 'Gwei'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) priority_fee = w3.eth.max_priority_fee print(f'Max Priority Fee: {w3.from_wei(priority_fee, "gwei")} Gwei') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get legacy gas price - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data --- ## eth_newBlockFilter - Avalanche RPC Method # eth_newBlockFilter Creates a filter on Avalanche to notify when a new block arrives. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const filterId = await provider.send('eth_newBlockFilter', []); // Poll for new blocks const newBlocks = await provider.send('eth_getFilterChanges', [filterId]); console.log('New block hashes:', newBlocks); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_blockNumber`](./eth_blockNumber) - Get current block --- ## eth_newFilter - Avalanche RPC Method # eth_newFilter Creates a filter object on Avalanche to notify when state changes (logs). ## Use Cases - **Event monitoring** - Subscribe to contract events - **Real-time updates** - Track events for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains - **Indexing** - Build event indexes incrementally ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block | | `toBlock` | `QUANTITY\|TAG` | No | Ending block | | `address` | `DATA\|Array` | No | Contract address(es) | | `topics` | `Array` | No | Topic filters | ## Request ```json { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); // Create filter const filterId = await provider.send('eth_newFilter', [{ fromBlock: 'latest', address: '0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf', topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'] }]); // Poll for changes const changes = await provider.send('eth_getFilterChanges', [filterId]); console.log('New events:', changes); // Cleanup await provider.send('eth_uninstallFilter', [filterId]); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for changes - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_newPendingTransactionFilter - Avalanche RPC Method # eth_newPendingTransactionFilter Creates a filter on Avalanche to notify when new pending transactions arrive. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const filterId = await provider.send('eth_newPendingTransactionFilter', []); // Poll for pending transactions const pendingTxs = await provider.send('eth_getFilterChanges', [filterId]); console.log('Pending transaction hashes:', pendingTxs); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_sendRawTransaction - Avalanche RPC Method # eth_sendRawTransaction Submits a pre-signed transaction for broadcast to Avalanche. > **Why Avalanche?** Build on the fastest smart contract platform with sub-second finality and customizable L1 subnets with sub-second finality, Evergreen subnets for institutions, and partnerships with Franklin Templeton, VanEck, and Bergen County. ## Use Cases The `eth_sendRawTransaction` method is essential for: - **Broadcasting transactions** - Submit signed transactions to the network - **Wallet operations** - Send native tokens and interact with contracts - **DeFi operations** - Execute swaps, provide liquidity for institutional RWA tokenization ($18B+ transfer volume), gaming subnets, and enterprise blockchains - **Batch operations** - Submit multiple transactions efficiently ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `signedTransactionData` | `DATA` | Yes | The signed transaction data (RLP encoded) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | 32-byte transaction hash | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c808504a817c80082520894..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const wallet = new Wallet('YOUR_PRIVATE_KEY', provider); // Send native tokens async function sendTransaction(to, value) { const tx = await wallet.sendTransaction({ to: to, value: parseEther(value) }); console.log('Transaction hash:', tx.hash); // Wait for confirmation const receipt = await tx.wait(); console.log('Confirmed in block:', receipt.blockNumber); return receipt; } // Send to contract async function sendContractTransaction(contract, method, args, value = '0') { const tx = await contract[method](...args, { value: parseEther(value) }); return await tx.wait(); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc')) def send_transaction(private_key, to, value_in_ether): account = w3.eth.account.from_key(private_key) # Build transaction tx = { 'nonce': w3.eth.get_transaction_count(account.address), 'to': to, 'value': w3.to_wei(value_in_ether, 'ether'), 'gas': 21000, 'gasPrice': w3.eth.gas_price, 'chainId': w3.eth.chain_id } # Sign transaction signed_tx = account.sign_transaction(tx) # Send transaction tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) print(f'Transaction hash: {tx_hash.hex()}') # Wait for confirmation receipt = w3.eth.wait_for_transaction_receipt(tx_hash) print(f'Confirmed in block: {receipt["blockNumber"]}') return receipt ``` ```go package main "context" "crypto/ecdsa" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc") if err != nil { log.Fatal(err) } privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY") if err != nil { log.Fatal(err) } publicKey := privateKey.Public() publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey) fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA) nonce, _ := client.PendingNonceAt(context.Background(), fromAddress) value := big.NewInt(1000000000000000000) gasLimit := uint64(21000) gasPrice, _ := client.SuggestGasPrice(context.Background()) toAddress := common.HexToAddress("0x09383137c1eee3e1a8bc781228e4199f6b4a9bbf") tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil) chainID, _ := client.NetworkID(context.Background()) signedTx, _ := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey) err = client.SendTransaction(context.Background(), signedTx) if err != nil { log.Fatal(err) } fmt.Printf("Transaction hash: %s\n", signedTx.Hash().Hex()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Nonce too low | Transaction nonce already used | | -32000 | Insufficient funds | Account has insufficient balance | | -32000 | Gas too low | Gas limit insufficient | | -32000 | Replacement underpriced | Gas price too low for replacement | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas required - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction result --- ## eth_sendTransaction - Send Transaction # eth_sendTransaction > **Important**: Dwellir's shared Avalanche endpoints do not manage user private keys. JSON-RPC nodes cannot unlock your account, so `eth_sendTransaction` calls will fail. Sign transactions client-side and broadcast them with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Why this method is disabled on shared nodes - [`eth_sendTransaction` requires the node to hold and unlock the `from` account's private key](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction). - Managed infrastructure providers disable it for security reasons rather than storing customer keys on shared servers (for example, [Infura explicitly blocks the method on shared endpoints](https://docs.infura.io/api/networks/ethereum/json-rpc-methods/eth_sendtransaction)). ## Recommended workflow 1. Build the raw transaction locally with your wallet or SDK. 2. Sign the payload client-side (hardware wallet, custodial service, or library). 3. Submit the signed hex string with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Example response from the shared endpoint ```bash curl -s -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"0x0000000000000000000000000000000000000000"}],"id":1}' ``` ```json {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"unknown account"}} ``` Need help? Contact our [support team](mailto:support@dwellir.com) or use the dedicated [`eth_sendRawTransaction`](./eth_sendRawTransaction) guide. --- ## eth_signTransaction - Sign Transaction # eth_signTransaction Signs a transaction that can be submitted to the network at a later time using with eth_sendRawTransaction on Avalanche C-Chain. ## Parameters 1. `Object` - The transaction object - `from`: `DATA`, 20 Bytes - The address the transaction is sent from. - `to`: `DATA`, 20 Bytes - (optional when creating new contract) The address the transaction is directed to. - `gas`: `QUANTITY` - (optional, default: 90000) Integer of the gas provided for the transaction execution. - `gasPrice`: `QUANTITY` - (optional, default: To-Be-Determined) Integer of the gasPrice used for each paid gas. - `value`: `QUANTITY` - (optional) Integer of the value sent with this transaction. - `data`: `DATA` - The compiled code of a contract OR the hash of the invoked method signature and encoded parameters. - `nonce`: `QUANTITY` - (optional) Integer of a nonce. ```json { "jsonrpc": "2.0", "method": "eth_signTransaction", "params": [ { "from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a" } ], "id": 1 } ``` ## Returns `Object` - The signed transaction object. ## Implementation Example ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_signTransaction", "params": [ { "from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155", "nonce": "0x0", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a" } ], "id": 1 }' ``` ```javascript const response = await fetch('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_signTransaction', params: [ { from: '0xb60e8dd61c5d32be8058bb8eb970870f07233155', to: '0xd46e8dd67c5d32be8058bb8eb970870f07244567', gas: '0x76c0', gasPrice: '0x9184e72a000', value: '0x9184e72a' } ], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "id": 1, "jsonrpc": "2.0", "result": { "raw": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675", "tx": { "hash": "0xc6ef2fc5426d6ad6fd9e2a26abeab0aa2411b7ab17f30a99d3cb96aed1d1055b", "nonce": "0x0", "blockHash": "0x0000000000000000000000000000000000000000000000000000000000000000", "blockNumber": "0x0", "transactionIndex": "0x0", "from": "0x407d73d8a49eeb85d32cf465507dd71d507100c1", "to": "0x85h43d8a49eeb85d32cf465507dd71d507100c1", "value": "0x7f110", "gas": "0x7f110", "gasPrice": "0x09184e72a000", "input": "0x603880600c6000396000f300603880600c6000396000f3603880600c6000396000f360" } } } ``` **Note:** This method requires access to the private key for the 'from' address and returns the signed transaction that can be broadcast later. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Avalanche documentation](/docs/avalanche).* --- ## eth_syncing - Avalanche RPC Method # eth_syncing Returns syncing status of Avalanche node. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 } ``` ## Returns Returns `false` if not syncing, or an object with sync status. ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const syncing = await provider.send('eth_syncing', []); if (syncing === false) { console.log('Node is fully synced'); } else { console.log('Syncing:', syncing); } ``` ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get current block - [`net_peerCount`](./net_peerCount) - Get peer count --- ## eth_uninstallFilter - Avalanche RPC Method # eth_uninstallFilter Uninstalls a filter on Avalanche. Should be called when no longer needed. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID to uninstall | ## Request ```json { "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if filter was found and uninstalled | ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const success = await provider.send('eth_uninstallFilter', [filterId]); console.log('Filter removed:', success); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter --- ## Avalanche - High-Performance Blockchain Platform ## Why Build on Avalanche? Avalanche is a high-performance blockchain platform that delivers sub-second finality and supports custom blockchain networks. Built on the innovative Avalanche consensus mechanism, it offers: ### ⚡ **Lightning Fast Performance** - **Sub-second finality** - Transactions confirm in under 1 second - **4,500+ TPS** - Industry-leading throughput capacity - **Low fees** - Cost-effective transactions with predictable pricing ### 🏗️ **Unique Three-Chain Architecture** - **X-Chain** - Exchange Chain for asset creation and trading - **P-Chain** - Platform Chain for validator coordination and subnets - **C-Chain** - Contract Chain for Ethereum-compatible smart contracts ### 🛡️ **Enterprise Security** - **Avalanche Consensus** - Novel consensus protocol with strong safety guarantees - **Validator Network** - Decentralized network of validators securing the platform - **Battle-tested** - Processing millions of transactions since mainnet launch ### 🌍 **Thriving Ecosystem** - **400+ projects** - Growing DeFi, Gaming, and NFT ecosystem - **EVM Compatible** - Full Ethereum compatibility on C-Chain - **Subnet Support** - Create custom blockchain networks ## Quick Start with Avalanche C-Chain Connect to Avalanche C-Chain in seconds with Dwellir's optimized endpoints: ### Installation & Setup ```javascript // Connect to Avalanche C-Chain mainnet const provider = new JsonRpcProvider( 'https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc' ); // Get the latest block const block = await provider.getBlock('latest'); console.log('Latest block:', block.number); // Query account balance const balance = await provider.getBalance('0x...'); console.log('Balance:', balance.toString()); ``` ```javascript const Web3 = require('web3'); // Connect to Avalanche C-Chain mainnet const web3 = new Web3( 'https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc' ); // Get chain ID to verify connection const chainId = await web3.eth.getChainId(); console.log('Connected to Avalanche:', chainId === 43114); // Get gas price for optimal transaction pricing const gasPrice = await web3.eth.getGasPrice(); console.log('Current gas price:', gasPrice); ``` ```typescript // Create Avalanche client const client = createPublicClient({ chain: avalanche, transport: http('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'), }); // Read contract data const data = await client.readContract({ address: '0x...', abi: contractAbi, functionName: 'balanceOf', args: ['0x...'], }); ``` ## Network Information Chain ID 43114 Mainnet Block Time 2 seconds Average Gas Token AVAX Native token RPC Standard Ethereum JSON-RPC 2.0 ## JSON-RPC API Reference Avalanche C-Chain supports the full [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/) with sub-second finality and high throughput. ## Common Integration Patterns ### 🔄 Transaction Monitoring Monitor pending and confirmed transactions efficiently: ```javascript // Watch for transaction confirmation async function waitForTransaction(txHash) { const receipt = await provider.waitForTransaction(txHash, 1); // Avalanche specific: Fast finality means quick confirmations console.log('Transaction confirmed in block:', receipt.blockNumber); return receipt; } ``` ### ⚡ Fast Finality Optimization Leverage Avalanche's sub-second finality: ```javascript // Avalanche transactions finalize quickly async function fastConfirmation(txHash) { const receipt = await provider.waitForTransaction(txHash, 1); // On Avalanche, 1 confirmation is typically sufficient if (receipt.blockNumber) { console.log('Transaction finalized with 1 confirmation'); return receipt; } } ``` ### 🔍 Event Filtering Efficiently query contract events: ```javascript // Query events with optimal batch size for Avalanche async function getEvents(contract, eventName, fromBlock = 0) { const filter = contract.filters[eventName](); const events = []; const batchSize = 5000; // Avalanche recommended batch size for (let i = fromBlock; i <= currentBlock; i += batchSize) { const batch = await contract.queryFilter( filter, i, Math.min(i + batchSize - 1, currentBlock) ); events.push(...batch); } return events; } ``` ## Performance Best Practices ### 1. **Batch Requests** Combine multiple RPC calls for optimal performance: ```javascript const batch = [ { method: 'eth_blockNumber', params: [] }, { method: 'eth_gasPrice', params: [] }, { method: 'eth_getBalance', params: [address, 'latest'] } ]; const results = await provider.send(batch); ``` ### 2. **Connection Pooling** Reuse provider instances to minimize connection overhead: ```javascript // Singleton pattern for provider class AvalancheProvider { static instance = null; static getInstance() { if (!this.instance) { this.instance = new JsonRpcProvider( 'https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc' ); } return this.instance; } } ``` ### 3. **Smart Caching** Cache immutable data to reduce API calls: ```javascript const cache = new Map(); async function getCachedBlockData(blockNumber) { const key = `block_${blockNumber}`; if (!cache.has(key)) { const block = await provider.getBlock(blockNumber); cache.set(key, block); } return cache.get(key); } ``` ## Troubleshooting Common Issues ### Error: "Gas required exceeds allowance" Avalanche uses dynamic gas pricing. Always estimate gas properly: ```javascript // Get current fee data const feeData = await provider.getFeeData(); const tx = { to: recipient, value: amount, maxFeePerGas: feeData.maxFeePerGas, maxPriorityFeePerGas: feeData.maxPriorityFeePerGas, gasLimit: await provider.estimateGas({ to: recipient, value: amount }) }; ``` ### Error: "Transaction underpriced" Avalanche uses EIP-1559 pricing. Use dynamic gas pricing: ```javascript // Get current network conditions const feeData = await provider.getFeeData(); const tx = { to: recipient, value: amount, maxFeePerGas: feeData.maxFeePerGas, maxPriorityFeePerGas: feeData.maxPriorityFeePerGas, gasLimit: 21000n }; ``` ### Error: "Rate limit exceeded" Implement exponential backoff for resilient applications: ```javascript async function callWithRetry(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error.code === 429 && i < maxRetries - 1) { await new Promise(r => setTimeout(r, 2 ** i * 1000)); } else { throw error; } } } } ``` ## Migration Guide ### From Ethereum Mainnet Moving from L1 to Avalanche C-Chain is seamless: ```javascript // Before (Ethereum) const provider = new JsonRpcProvider('https://eth-rpc.example.com'); // After (Avalanche) const provider = new JsonRpcProvider( 'https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc' ); // ✅ Smart contracts work identically // ✅ Same tooling and libraries // ✅ Native token is AVAX instead of ETH // ⚠️ Different chain ID (43114) // ⚠️ Much faster finality (~1 second) ``` ### From Other EVM Chains Avalanche C-Chain is fully EVM compatible: ```javascript // Same contract deployment process const contractFactory = new ContractFactory(abi, bytecode, signer); const contract = await contractFactory.deploy(...constructorArgs); // Wait for deployment (much faster on Avalanche) await contract.waitForDeployment(); ``` ## Resources & Tools ### Official Resources - [Avalanche Documentation](https://docs.avax.network) - [Avalanche Explorer](https://snowtrace.io) - [Avalanche Bridge](https://bridge.avax.network) ### Developer Tools - [Hardhat Config](https://docs.avax.network/build/dapp/smart-contracts/toolchains/hardhat) - [Foundry Setup](https://docs.avax.network/build/dapp/smart-contracts/toolchains/foundry) - [Core Wallet](https://core.app) ### Ecosystem - [DeFi Llama](https://defillama.com/chain/Avalanche) - Track Avalanche DeFi - [Avalanche Website](https://www.avax.network/) - Discover projects and ecosystem - [Subnets](https://subnets.avax.network) - Custom blockchain networks ### Need Help? - 📧 **Email**: support@dwellir.com - 📚 **Docs**: You're here! - 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com) --- *Start building on Avalanche with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)* --- ## net_listening - Avalanche RPC Method # net_listening Returns `true` if client is actively listening for network connections on Avalanche. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if listening | ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const listening = await provider.send('net_listening', []); console.log('Node listening:', listening); ``` ## Related Methods - [`net_peerCount`](./net_peerCount) - Get peer count --- ## net_peerCount - Avalanche RPC Method # net_peerCount Returns number of peers currently connected to Avalanche client. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Number of connected peers (hexadecimal) | ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const peerCount = await provider.send('net_peerCount', []); console.log('Peer count:', parseInt(peerCount, 16)); ``` ## Related Methods - [`net_listening`](./net_listening) - Check if listening --- ## net_version - Avalanche RPC Method # net_version Returns the current network ID on Avalanche. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Network ID as a string | ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const networkId = await provider.send('net_version', []); console.log('Network ID:', networkId); ``` ## Related Methods - [`eth_chainId`](./eth_chainId) - Get chain ID --- ## web3_clientVersion - Avalanche RPC Method # web3_clientVersion Returns the current client version on Avalanche. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Client version string | ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); const version = await provider.send('web3_clientVersion', []); console.log('Client version:', version); ``` --- ## web3_sha3 - Avalanche RPC Method # web3_sha3 Returns Keccak-256 (not standard SHA3-256) of the given data on Avalanche. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `data` | `DATA` | Yes | Data to hash | ## Request ```json { "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Keccak-256 hash of the data | ## Code Examples ```bash curl -X POST https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-avalanche-mainnet-archive.n.dwellir.com/YOUR_API_KEY/ext/bc/C/rpc'); // Using RPC const hash = await provider.send('web3_sha3', ['0x68656c6c6f']); console.log('Hash:', hash); // Using ethers directly (faster) const localHash = keccak256(toUtf8Bytes('hello')); console.log('Local hash:', localHash); ``` --- ## debug_traceBlock - Base RPC Method # debug_traceBlock Traces all transactions in a block on Base by block RLP. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Analyze transaction execution step-by-step - **Smart contract analysis** - Debug contract interactions - **Security auditing** - Trace internal calls for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockRlp` | `DATA` | Yes | RLP-encoded block data | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Use debug_traceBlockByNumber instead (more practical) const traces = await provider.send('debug_traceBlockByNumber', ['latest', {}]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by block number - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by block hash --- ## debug_traceBlockByHash - Base RPC Method # debug_traceBlockByHash Traces all transactions in a block on Base by block hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0xf47c4f664172629e9f74da58f558c6f553e2662adc7a3cf0af0292347bd2f358", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0xf47c4f664172629e9f74da58f558c6f553e2662adc7a3cf0af0292347bd2f358", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0xf47c4f664172629e9f74da58f558c6f553e2662adc7a3cf0af0292347bd2f358'; const traces = await provider.send('debug_traceBlockByHash', [blockHash, { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by number - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceBlockByNumber - Base RPC Method # debug_traceBlockByNumber Traces all transactions in a block on Base by block number. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('debug_traceBlockByNumber', ['latest', { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by hash - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceCall - Base RPC Method # debug_traceCall Traces a call without creating a transaction on Base. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction simulation** - Debug before sending - **Gas analysis** - Analyze gas usage per opcode - **Contract debugging** - Step through execution for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `call` | `Object` | Yes | Call object (same as eth_call) | | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ { "to": "0x4200000000000000000000000000000000000006", "data": "0x70a082310000000000000000000000004200000000000000000000000000000000000006" }, "latest", {} ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ {"to": "0x4200000000000000000000000000000000000006", "data": "0x70a082310000000000000000000000004200000000000000000000000000000000000006"}, "latest", {"tracer": "callTracer"} ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const trace = await provider.send('debug_traceCall', [ { to: '0x4200000000000000000000000000000000000006', data: '0x70a082310000000000000000000000004200000000000000000000000000000000000006' }, 'latest', { tracer: 'callTracer' } ]); console.log('Trace:', trace); ``` ## Related Methods - [`eth_call`](./eth_call) - Execute call without trace - [`debug_traceTransaction`](./debug_traceTransaction) - Trace actual transaction --- ## debug_traceTransaction - Base RPC Method # debug_traceTransaction Traces a transaction execution on Base by transaction hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Understand exactly what happened - **Failure analysis** - Find where and why a transaction reverted - **Gas optimization** - Analyze gas usage for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Tracer Options - `{}` - Default opcode tracer (verbose) - `{ tracer: "callTracer" }` - Call tree tracer - `{ tracer: "prestateTracer" }` - Pre-state tracer ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269'; // Call tracer - shows internal calls const callTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'callTracer' } ]); console.log('Type:', callTrace.type); console.log('From:', callTrace.from); console.log('To:', callTrace.to); console.log('Gas used:', parseInt(callTrace.gasUsed, 16)); // Prestate tracer - shows state before execution const prestateTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'prestateTracer' } ]); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269' # Call tracer trace = w3.provider.make_request('debug_traceTransaction', [ tx_hash, {'tracer': 'callTracer'} ]) print(f'Trace type: {trace["result"]["type"]}') print(f'Gas used: {int(trace["result"]["gasUsed"], 16)}') ``` ## Related Methods - [`debug_traceCall`](./debug_traceCall) - Trace without executing - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace entire block --- ## eth_accounts - Base RPC Method # eth_accounts Returns a list of addresses owned by the client on Base. > **Why Base?** Build on Coinbase's L2 with 54% of L2 market revenue and direct access to 110M+ Coinbase users with $8B+ TVL, $0.08 gas fees, built-in Coinbase distribution, and seamless fiat rails. ## Important Note On public RPC endpoints like Dwellir, `eth_accounts` returns an empty array because the node does not hold any private keys. This method is primarily useful for: - Local development nodes (Ganache, Hardhat, Anvil) - Private nodes with managed accounts - Wallet provider connections (MetaMask injects accounts) ## When to Use This Method `eth_accounts` is relevant for consumer app developers, SocialFi builders, and teams seeking easy fiat onramps in specific scenarios: - **Development Testing** — Retrieve test accounts from local nodes - **Wallet Detection** — Check if a wallet provider has connected accounts - **Client Verification** — Confirm node account access capabilities ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `Array` | List of 20-byte account addresses owned by the client | **Return format**: Array of `0x` prefixed hexadecimal addresses (typically empty for public nodes) ## Request ```json { "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 } ``` ## Response ### Successful Response (Public Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [] } ``` ### Successful Response (Local Development Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [ "0x407d73d8a49eeb85d32cf465507dd71d507100c1", "0x85d32cf465507dd71d507100c1407d73d8a49eeb" ] } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_accounts', params: [], id: 1 }) }); const { result } = await response.json(); console.log('Accounts:', result); // Using ethers.js const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const accounts = await provider.listAccounts(); console.log('Accounts:', accounts); ``` ```python def get_accounts(): response = requests.post( 'https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_accounts', 'params': [], 'id': 1 } ) return response.json()['result'] accounts = get_accounts() print(f'Accounts: {accounts}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) print(f'Accounts: {w3.eth.accounts}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/rpc" ) func main() { client, err := rpc.Dial("https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } var accounts []string err = client.CallContext(context.Background(), &accounts, "eth_accounts") if err != nil { log.Fatal(err) } fmt.Printf("Accounts: %v\n", accounts) } ``` ## Common Use Cases ### 1. Development Environment Detection Check if running against a development node with test accounts: ```javascript async function isDevEnvironment(provider) { const accounts = await provider.listAccounts(); return accounts.length > 0; } const isDev = await isDevEnvironment(provider); if (isDev) { console.log('Development environment detected'); } ``` ### 2. Wallet Connection Check Verify wallet provider has connected accounts: ```javascript async function checkWalletConnection() { if (typeof window.ethereum === 'undefined') { return { connected: false, reason: 'No wallet detected' }; } const accounts = await window.ethereum.request({ method: 'eth_accounts' }); return { connected: accounts.length > 0, accounts: accounts }; } ``` ### 3. Fallback Account Selection Use first available account or request connection: ```javascript async function getActiveAccount() { // Check existing connections let accounts = await window.ethereum.request({ method: 'eth_accounts' }); // Request connection if no accounts if (accounts.length === 0) { accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); } return accounts[0] || null; } ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32601 | Method not found | Node may not support this method | | -32603 | Internal error | Retry with exponential backoff | ```javascript async function safeGetAccounts(provider) { try { const accounts = await provider.listAccounts(); return { success: true, accounts }; } catch (error) { if (error.code === -32601) { console.warn('eth_accounts not supported on this node'); return { success: false, accounts: [], reason: 'unsupported' }; } throw error; } } ``` ## Related Methods - [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102) — Request wallet connection (browser wallets) - [`eth_getBalance`](./eth_getBalance) — Get account balance - [`eth_getTransactionCount`](./eth_getTransactionCount) — Get account nonce --- ## eth_blockNumber - Base RPC Method # eth_blockNumber Returns the number of the most recent block on Base. > **Why Base?** Build on Coinbase's L2 with 54% of L2 market revenue and direct access to 110M+ Coinbase users with $8B+ TVL, $0.08 gas fees, built-in Coinbase distribution, and seamless fiat rails. ## When to Use This Method `eth_blockNumber` is fundamental for consumer app developers, SocialFi builders, and teams seeking easy fiat onramps: - **Syncing Applications** — Keep your dApp in sync with the latest Base blockchain state - **Transaction Monitoring** — Verify confirmations by comparing block numbers - **Event Filtering** — Set the correct block range for querying logs on consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations - **Health Checks** — Monitor node connectivity and sync status ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `QUANTITY` | Hexadecimal string representing the current block number | **Return format**: `0x` prefixed hexadecimal (e.g., `0x5BAD55` = 6,008,149 in decimal) ## Request ```json { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } ``` ## Response ### Successful Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5BAD55" } ``` ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error" } } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }) }); const { result } = await response.json(); const blockNumber = parseInt(result, 16); console.log('Base block:', blockNumber); // Using ethers.js const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockNumber = await provider.getBlockNumber(); console.log('Base block:', blockNumber); ``` ```python def get_block_number(): response = requests.post( 'https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_blockNumber', 'params': [], 'id': 1 } ) result = response.json()['result'] return int(result, 16) block_number = get_block_number() print(f'Base block: {block_number}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) print(f'Base block: {w3.eth.block_number}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockNumber, err := client.BlockNumber(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Base block: %d\n", blockNumber) } ``` ## Common Use Cases ### 1. Block Confirmation Counter Monitor transaction confirmations on Base: ```javascript async function getConfirmations(provider, txHash) { const tx = await provider.getTransaction(txHash); if (!tx || !tx.blockNumber) return 0; const currentBlock = await provider.getBlockNumber(); return currentBlock - tx.blockNumber + 1; } // Wait for specific confirmations async function waitForConfirmations(provider, txHash, confirmations = 6) { let currentConfirmations = 0; while (currentConfirmations < confirmations) { currentConfirmations = await getConfirmations(provider, txHash); console.log(`Confirmations: ${currentConfirmations}/${confirmations}`); await new Promise(r => setTimeout(r, 2000)); } return true; } ``` ### 2. Event Log Filtering Query events from recent blocks on Base: ```javascript async function getRecentEvents(provider, contract, eventName, blockRange = 100) { const currentBlock = await provider.getBlockNumber(); const fromBlock = currentBlock - blockRange; const filter = contract.filters[eventName](); const events = await contract.queryFilter(filter, fromBlock, currentBlock); return events; } ``` ### 3. Node Health Monitoring Check if your Base node is synced: ```javascript async function checkNodeHealth(provider) { try { const blockNumber = await provider.getBlockNumber(); const block = await provider.getBlock(blockNumber); const now = Date.now() / 1000; const blockAge = now - block.timestamp; if (blockAge > 60) { console.warn(`Node may be behind. Last block was ${blockAge}s ago`); return false; } console.log(`Node healthy. Latest block: ${blockNumber}`); return true; } catch (error) { console.error('Node unreachable:', error); return false; } } ``` ## Performance Optimization ### Caching Strategy Cache block numbers to reduce API calls: ```javascript class BlockNumberCache { constructor(ttl = 2000) { this.cache = null; this.timestamp = 0; this.ttl = ttl; } async get(provider) { const now = Date.now(); if (this.cache && (now - this.timestamp) < this.ttl) { return this.cache; } this.cache = await provider.getBlockNumber(); this.timestamp = now; return this.cache; } invalidate() { this.cache = null; this.timestamp = 0; } } const blockCache = new BlockNumberCache(); ``` ### Batch Requests Combine with other calls for efficiency: ```javascript const batch = [ { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }, { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 }, { jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 } ]; const response = await fetch('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await response.json(); ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32603 | Internal error | Retry with exponential backoff | | -32005 | Rate limit exceeded | Implement rate limiting client-side | | -32000 | Execution reverted | Check node sync status | ```javascript async function safeGetBlockNumber(provider, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await provider.getBlockNumber(); } catch (error) { if (error.code === -32005) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } else if (i === maxRetries - 1) { throw error; } } } } ``` ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) — Get full block details by number - [`eth_getBlockByHash`](./eth_getBlockByHash) — Get block details by hash - [`eth_syncing`](./eth_syncing) — Check if node is still syncing --- ## eth_call - Base RPC Method # eth_call Executes a new message call immediately without creating a transaction on Base. Used for reading smart contract state. > **Why Base?** Build on Coinbase's L2 with 54% of L2 market revenue and direct access to 110M+ Coinbase users with $8B+ TVL, $0.08 gas fees, built-in Coinbase distribution, and seamless fiat rails. ## Use Cases The `eth_call` method is essential for: - **Reading contract state** - Query view/pure functions - **Simulating transactions** - Test execution without gas costs - **DeFi integrations** - Check prices, balances, allowances for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations - **Complex queries** - Execute multi-step contract logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | 20-byte address executing the call | | `to` | `DATA` | Yes | 20-byte contract address | | `gas` | `QUANTITY` | No | Gas limit for the call | | `gasPrice` | `QUANTITY` | No | Gas price in wei | | `value` | `QUANTITY` | No | Value to send in wei | | `data` | `DATA` | Yes | Encoded function call data | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_call", "params": [ { "to": "0x4200000000000000000000000000000000000006", "data": "0x70a082310000000000000000000000004200000000000000000000000000000000000006" }, "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | The return value of the executed contract function | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000" } ``` ## Code Examples ```bash # Call ERC20 balanceOf function curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{ "to": "0x4200000000000000000000000000000000000006", "data": "0x70a082310000000000000000000000004200000000000000000000000000000000000006" }, "latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // ERC20 ABI for common functions const ERC20_ABI = [ "function balanceOf(address owner) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function totalSupply() view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)" ]; // Read ERC20 token balance async function getTokenBalance(tokenAddress, walletAddress) { const contract = new Contract(tokenAddress, ERC20_ABI, provider); const balance = await contract.balanceOf(walletAddress); const decimals = await contract.decimals(); const symbol = await contract.symbol(); return { raw: balance.toString(), formatted: (Number(balance) / Math.pow(10, decimals)).toFixed(4), symbol: symbol }; } // Direct eth_call async function directCall(to, data) { const result = await provider.call({ to, data }); return result; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) def get_erc20_balance(token_address, wallet_address): # balanceOf(address) selector function_signature = "balanceOf(address)" function_selector = w3.keccak(text=function_signature)[:4].hex() # Encode address parameter encoded_address = wallet_address[2:].lower().zfill(64) data = function_selector + encoded_address # Make the call result = w3.eth.call({ 'to': token_address, 'data': data }) return int(result.hex(), 16) balance = get_erc20_balance( '0x4200000000000000000000000000000000000006', '0x4200000000000000000000000000000000000006' ) print(f'Balance: {balance}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0x4200000000000000000000000000000000000006") data := common.FromHex("0x70a082310000000000000000000000004200000000000000000000000000000000000006") msg := ethereum.CallMsg{ To: &contractAddress, Data: data, } result, err := client.CallContract(context.Background(), msg, nil) if err != nil { log.Fatal(err) } fmt.Printf("Result: 0x%x\n", result) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Contract function reverted | | -32602 | Invalid parameters | Invalid data encoding | | -32015 | VM execution error | Contract logic error | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas for transaction - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send actual transaction --- ## eth_chainId - Base RPC Method # eth_chainId Returns the chain ID used for transaction signing on Base. > **Why Base?** Build on Coinbase's L2 with 54% of L2 market revenue and direct access to 110M+ Coinbase users with $8B+ TVL, $0.08 gas fees, built-in Coinbase distribution, and seamless fiat rails. ## Use Cases The `eth_chainId` method is essential for: - **Transaction signing** - Ensure transactions are signed for the correct network - **Network verification** - Confirm connection to the expected chain - **Multi-chain apps** - Handle different networks programmatically - **Wallet integration** - Validate network before transactions ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Chain ID in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1" } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const network = await provider.getNetwork(); console.log('Chain ID:', network.chainId); // Verify network before transaction async function verifyNetwork(expectedChainId) { const network = await provider.getNetwork(); if (network.chainId !== BigInt(expectedChainId)) { throw new Error(`Wrong network. Expected ${expectedChainId}, got ${network.chainId}`); } return true; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) chain_id = w3.eth.chain_id print(f'Chain ID: {chain_id}') # Verify network def verify_network(expected_chain_id): chain_id = w3.eth.chain_id if chain_id != expected_chain_id: raise ValueError(f'Wrong network. Expected {expected_chain_id}, got {chain_id}') return True ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } chainID, err := client.ChainID(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Chain ID: %d\n", chainID) } ``` ## Related Methods - [`net_version`](./net_version) - Get network version - [`eth_syncing`](./eth_syncing) - Check sync status --- ## eth_coinbase - Get coinbase address(Base) # eth_coinbase Get coinbase address on the Base network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_coinbase](https://ethereum.org/developers/docs/apis/json-rpc/#eth_coinbase) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_coinbase", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_coinbase', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Base documentation](/docs/base).* --- ## eth_estimateGas - Base RPC Method # eth_estimateGas Estimates the gas necessary to execute a transaction on Base. > **Why Base?** Build on Coinbase's L2 with 54% of L2 market revenue and direct access to 110M+ Coinbase users with $8B+ TVL, $0.08 gas fees, built-in Coinbase distribution, and seamless fiat rails. ## Use Cases The `eth_estimateGas` method is essential for: - **Transaction preparation** - Set appropriate gas limits - **Cost estimation** - Calculate transaction costs before sending - **Error detection** - Identify reverts before spending gas - **DeFi operations** - Estimate costs for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | Sender address | | `to` | `DATA` | No | Recipient address | | `gas` | `QUANTITY` | No | Gas limit | | `gasPrice` | `QUANTITY` | No | Gas price | | `value` | `QUANTITY` | No | Value in wei | | `data` | `DATA` | No | Transaction data | ## Request ```json { "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0x4200000000000000000000000000000000000006", "to": "0x4200000000000000000000000000000000000006", "value": "0x1" }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Estimated gas amount in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5208" } ``` **Note**: `0x5208` = 21000 gas (standard ETH transfer) ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0x4200000000000000000000000000000000000006", "to": "0x4200000000000000000000000000000000000006", "value": "0x1" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Estimate simple transfer async function estimateTransfer(to, value) { const gasEstimate = await provider.estimateGas({ to: to, value: parseEther(value) }); console.log('Estimated gas:', gasEstimate.toString()); return gasEstimate; } // Estimate contract call async function estimateContractCall(contract, method, args) { const gasEstimate = await contract[method].estimateGas(...args); console.log('Estimated gas:', gasEstimate.toString()); // Add 20% buffer for safety return gasEstimate * 120n / 100n; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) def estimate_transfer(to, value_in_ether): gas_estimate = w3.eth.estimate_gas({ 'to': to, 'value': w3.to_wei(value_in_ether, 'ether') }) print(f'Estimated gas: {gas_estimate}') return gas_estimate def estimate_contract_call(contract, method, args): func = getattr(contract.functions, method) gas_estimate = func(*args).estimate_gas() # Add 20% buffer return int(gas_estimate * 1.2) # Estimate simple transfer gas = estimate_transfer('0x4200000000000000000000000000000000000006', 0.1) ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } toAddress := common.HexToAddress("0x4200000000000000000000000000000000000006") msg := ethereum.CallMsg{ To: &toAddress, Value: big.NewInt(1000000000000000000), } gasLimit, err := client.EstimateGas(context.Background(), msg) if err != nil { log.Fatal(err) } fmt.Printf("Estimated gas: %d\n", gasLimit) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Transaction would fail | | -32602 | Invalid params | Invalid transaction parameters | **Tip**: If estimation fails, the transaction would likely revert if sent. ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_estimateL1Fee - Estimate L1 data posting fee # eth_estimateL1Fee Estimate L1 data posting fee on the Base network. ## Parameters Varies by method. Please refer to the official documentation: [Optimism docs on estimating fees](https://docs.optimism.io/app-developers/transactions/estimates) for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateL1Fee", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_estimateL1Fee', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Base documentation](/docs/base).* --- ## eth_feeHistory - Base RPC Method # eth_feeHistory Returns historical gas information on Base for fee estimation. ## Use Cases - **Fee prediction** - Estimate future gas prices based on history - **Gas analytics** - Analyze fee trends over time - **Optimal timing** - Find best times for transactions on consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockCount` | `QUANTITY` | Yes | Number of blocks in the range | | `newestBlock` | `QUANTITY\|TAG` | Yes | Highest block of the range | | `rewardPercentiles` | `Array` | Yes | Percentiles to sample for priority fees | ## Request ```json { "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const feeHistory = await provider.send('eth_feeHistory', ['0xa', 'latest', [25, 50, 75]]); console.log('Base fees:', feeHistory.baseFeePerGas.map(f => formatUnits(f, 'gwei'))); console.log('Reward (25th percentile):', feeHistory.reward.map(r => formatUnits(r[0], 'gwei'))); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) fee_history = w3.eth.fee_history(10, 'latest', [25, 50, 75]) print(f'Base fees: {[w3.from_wei(f, "gwei") for f in fee_history["baseFeePerGas"]]}') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee --- ## eth_gasPrice - Base RPC Method # eth_gasPrice Returns the current gas price on Base in wei. > **Why Base?** Build on Coinbase's L2 with 54% of L2 market revenue and direct access to 110M+ Coinbase users with $8B+ TVL, $0.08 gas fees, built-in Coinbase distribution, and seamless fiat rails. ## Use Cases The `eth_gasPrice` method is essential for: - **Transaction pricing** - Set appropriate gas prices - **Cost estimation** - Calculate transaction costs before sending - **Gas monitoring** - Track network congestion - **DeFi operations** - Optimize costs for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Current gas price in wei (hexadecimal) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x3b9aca00" } ``` **Note**: `0x3b9aca00` = 1 Gwei (1,000,000,000 wei) ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); const gasPrice = feeData.gasPrice; console.log('Gas Price:', formatUnits(gasPrice, 'gwei'), 'Gwei'); // Calculate transaction cost async function estimateTransactionCost(gasLimit) { const feeData = await provider.getFeeData(); const cost = feeData.gasPrice * BigInt(gasLimit); return formatUnits(cost, 'ether'); } const cost = await estimateTransactionCost(21000); console.log('Transfer cost:', cost, 'ETH'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) gas_price = w3.eth.gas_price print(f'Gas Price: {w3.from_wei(gas_price, "gwei")} Gwei') # Calculate transaction cost def estimate_transaction_cost(gas_limit): gas_price = w3.eth.gas_price cost = gas_price * gas_limit return w3.from_wei(cost, 'ether') cost = estimate_transaction_cost(21000) print(f'Transfer cost: {cost} ETH') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } gasPrice, err := client.SuggestGasPrice(context.Background()) if err != nil { log.Fatal(err) } // Convert to Gwei gwei := new(big.Float).Quo( new(big.Float).SetInt(gasPrice), big.NewFloat(1e9), ) fmt.Printf("Gas Price: %f Gwei\n", gwei) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32603 | Internal error | Node error | ## Related Methods - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee (EIP-1559) - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas needed --- ## eth_getBalance - Base RPC Method # eth_getBalance Returns the balance of a given address on Base. > **Why Base?** Build on Coinbase's L2 with 54% of L2 market revenue and direct access to 110M+ Coinbase users with $8B+ TVL, $0.08 gas fees, built-in Coinbase distribution, and seamless fiat rails. ## Use Cases The `eth_getBalance` method is essential for: - **Wallet applications** - Display user balances - **Transaction validation** - Check if account has sufficient funds - **DeFi applications** - Monitor collateral and liquidity for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations - **Account monitoring** - Track balance changes over time ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address to check balance for | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0x4200000000000000000000000000000000000006", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Integer of the current balance in wei (hexadecimal) | **Note**: 1 native token = 10^18 wei. Convert using `balance / 10^18`. ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1a055690d9db80000" } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0x4200000000000000000000000000000000000006", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x4200000000000000000000000000000000000006'; const balanceWei = await provider.getBalance(address); const balance = formatEther(balanceWei); console.log(`Balance: ${balance}`); // Get balance at specific block const historicalBalance = await provider.getBalance(address, 1000000); console.log(`Historical balance: ${formatEther(historicalBalance)}`); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x4200000000000000000000000000000000000006' balance_wei = w3.eth.get_balance(address) balance = w3.from_wei(balance_wei, 'ether') print(f'Balance: {balance}') # Get balance at specific block historical_balance = w3.eth.get_balance(address, block_identifier=1000000) print(f'Historical balance: {w3.from_wei(historical_balance, "ether")}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0x4200000000000000000000000000000000000006") balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } // Convert to ether fbalance := new(big.Float).SetInt(balance) ethValue := new(big.Float).Quo(fbalance, big.NewFloat(1e18)) fmt.Printf("Balance: %f\n", ethValue) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid address format or block parameter | | -32000 | Execution error | Node execution error | ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_getTransactionCount`](./eth_getTransactionCount) - Get account nonce --- ## eth_getBlockByHash - Base RPC Method # eth_getBlockByHash Returns information about a block by hash on Base. > **Why Base?** Build on Coinbase's L2 with 54% of L2 market revenue and direct access to 110M+ Coinbase users with $8B+ TVL, $0.08 gas fees, built-in Coinbase distribution, and seamless fiat rails. ## Use Cases The `eth_getBlockByHash` method is essential for: - **Block verification** - Verify block data using its unique hash - **Chain reorganization handling** - Track blocks during reorgs - **Cross-chain bridges** - Verify block finality for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations - **Deterministic queries** - Get consistent block data regardless of chain state ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0xf47c4f664172629e9f74da58f558c6f553e2662adc7a3cf0af0292347bd2f358", false ], "id": 1 } ``` ## Returns Returns the same block object as `eth_getBlockByNumber`, or `null` if no block is found. | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used | | `transactions` | `Array` | Transaction objects or hashes | ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0xf47c4f664172629e9f74da58f558c6f553e2662adc7a3cf0af0292347bd2f358", false ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0xf47c4f664172629e9f74da58f558c6f553e2662adc7a3cf0af0292347bd2f358'; const block = await provider.getBlock(blockHash); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) block_hash = '0xf47c4f664172629e9f74da58f558c6f553e2662adc7a3cf0af0292347bd2f358' block = w3.eth.get_block(block_hash) print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockHash := common.HexToHash("0xf47c4f664172629e9f74da58f558c6f553e2662adc7a3cf0af0292347bd2f358") block, err := client.BlockByHash(context.Background(), blockHash) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block hash format | | -32000 | Block not found | Block with this hash does not exist | ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) - Get block by number - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number --- ## eth_getBlockByNumber - Base RPC Method # eth_getBlockByNumber Returns information about a block by block number on Base. > **Why Base?** Build on Coinbase's L2 with 54% of L2 market revenue and direct access to 110M+ Coinbase users with $8B+ TVL, $0.08 gas fees, built-in Coinbase distribution, and seamless fiat rails. ## Use Cases The `eth_getBlockByNumber` method is essential for: - **Block explorers** - Display complete block information - **Transaction indexers** - Process all transactions in a block - **Analytics platforms** - Analyze blockchain data for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations - **Timestamp verification** - Get block timestamps for time-based logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used by all transactions | | `gasLimit` | `QUANTITY` | Maximum gas allowed in block | | `transactions` | `Array` | Array of transaction objects or hashes | | `baseFeePerGas` | `QUANTITY` | Base fee per gas (EIP-1559) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": { "number": "0x5BAD55", "hash": "0xf47c4f664172629e9f74da58f558c6f553e2662adc7a3cf0af0292347bd2f358", "parentHash": "0x...", "timestamp": "0x64d8f6d0", "gasUsed": "0x1234", "gasLimit": "0x1c9c380", "transactions": [], "baseFeePerGas": "0x5f5e100" } } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Get latest block const block = await provider.getBlock('latest'); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); console.log('Transactions:', block.transactions.length); // Get block with full transactions const blockWithTxs = await provider.getBlock('latest', true); for (const tx of blockWithTxs.prefetchedTransactions) { console.log('Transaction:', tx.hash); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) # Get latest block block = w3.eth.get_block('latest') print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') print(f'Transactions: {len(block.transactions)}') # Get block with full transactions block_full = w3.eth.get_block('latest', full_transactions=True) for tx in block_full.transactions: print(f'Transaction: {tx.hash.hex()}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } // Get latest block block, err := client.BlockByNumber(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) fmt.Printf("Timestamp: %d\n", block.Time()) fmt.Printf("Transactions: %d\n", len(block.Transactions())) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block number or parameter format | | -32000 | Block not found | Block does not exist | ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number - [`eth_getBlockByHash`](./eth_getBlockByHash) - Get block by hash - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_getCode - Base RPC Method # eth_getCode Returns the bytecode at a given address on Base. > **Why Base?** Build on Coinbase's L2 with 54% of L2 market revenue and direct access to 110M+ Coinbase users with $8B+ TVL, $0.08 gas fees, built-in Coinbase distribution, and seamless fiat rails. ## Use Cases The `eth_getCode` method is essential for: - **Contract verification** - Check if address is a contract - **Security analysis** - Verify deployed bytecode matches expected - **DeFi integrations** - Validate contracts before interactions - **Protocol analysis** - Analyze contract deployments for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0x4200000000000000000000000000000000000006", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Contract bytecode or `0x` if EOA | ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0x4200000000000000000000000000000000000006", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x4200000000000000000000000000000000000006'; const code = await provider.getCode(address); if (code === '0x') { console.log('Address is an EOA (externally owned account)'); } else { console.log('Address is a contract'); console.log('Bytecode length:', code.length); } // Check if address is a contract async function isContract(address) { const code = await provider.getCode(address); return code !== '0x'; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x4200000000000000000000000000000000000006' code = w3.eth.get_code(address) if code == b'': print('Address is an EOA') else: print('Address is a contract') print(f'Bytecode length: {len(code.hex())}') # Check if address is a contract def is_contract(address): code = w3.eth.get_code(address) return code != b'' ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0x4200000000000000000000000000000000000006") code, err := client.CodeAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } if len(code) == 0 { fmt.Println("Address is an EOA") } else { fmt.Printf("Contract bytecode length: %d\n", len(code)) } } ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_getStorageAt`](./eth_getStorageAt) - Get contract storage --- ## eth_getFilterChanges - Base RPC Method # eth_getFilterChanges Polling method for a filter on Base, returns an array of logs since last poll. ## Use Cases - **Event streaming** - Get new events incrementally - **Real-time monitoring** - Track contract activity for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations - **Efficient indexing** - Process only new events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Poll loop async function pollFilter(filterId, interval = 2000) { while (true) { const changes = await provider.send('eth_getFilterChanges', [filterId]); if (changes.length > 0) { console.log('New events:', changes); } await new Promise(r => setTimeout(r, interval)); } } ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter --- ## eth_getFilterLogs - Base RPC Method # eth_getFilterLogs Returns an array of all logs matching filter with given ID on Base. ## Use Cases - **Historical queries** - Get all matching logs for a filter - **Full event history** - Retrieve complete event data for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const logs = await provider.send('eth_getFilterLogs', [filterId]); console.log('All matching logs:', logs.length); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_getLogs - Base RPC Method # eth_getLogs Returns an array of all logs matching a given filter object on Base. > **Why Base?** Build on Coinbase's L2 with 54% of L2 market revenue and direct access to 110M+ Coinbase users with $8B+ TVL, $0.08 gas fees, built-in Coinbase distribution, and seamless fiat rails. ## Use Cases The `eth_getLogs` method is essential for: - **Event indexing** - Track contract events for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations - **Token transfers** - Monitor ERC20/ERC721 transfers - **DeFi analytics** - Track swaps, liquidity events, and more - **Notification systems** - Alert on specific on-chain events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block (default: `"latest"`) | | `toBlock` | `QUANTITY\|TAG` | No | Ending block (default: `"latest"`) | | `address` | `DATA\|Array` | No | Contract address(es) to filter | | `topics` | `Array` | No | Array of topic filters | | `blockHash` | `DATA` | No | Filter single block by hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0x4200000000000000000000000000000000000006", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns Array of log objects: | Field | Type | Description | |-------|------|-------------| | `address` | `DATA` | Contract that emitted the log | | `topics` | `Array` | Array of indexed topics | | `data` | `DATA` | Non-indexed log data | | `blockNumber` | `QUANTITY` | Block number | | `transactionHash` | `DATA` | Transaction hash | | `logIndex` | `QUANTITY` | Log index in block | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": [{ "address": "0x4200000000000000000000000000000000000006", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."], "data": "0x...", "blockNumber": "0x5BAD55", "transactionHash": "0x...", "logIndex": "0x0" }] } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0x4200000000000000000000000000000000000006", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Get Transfer events const TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'; async function getTransferEvents(tokenAddress, fromBlock, toBlock) { const logs = await provider.getLogs({ address: tokenAddress, topics: [TRANSFER_TOPIC], fromBlock: fromBlock, toBlock: toBlock }); return logs.map(log => ({ from: '0x' + log.topics[1].slice(26), to: '0x' + log.topics[2].slice(26), blockNumber: log.blockNumber, transactionHash: log.transactionHash })); } const events = await getTransferEvents( '0x4200000000000000000000000000000000000006', 'latest', 'latest' ); console.log('Transfer events:', events); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' def get_transfer_events(token_address, from_block, to_block): logs = w3.eth.get_logs({ 'address': token_address, 'topics': [TRANSFER_TOPIC], 'fromBlock': from_block, 'toBlock': to_block }) events = [] for log in logs: events.append({ 'from': '0x' + log['topics'][1].hex()[26:], 'to': '0x' + log['topics'][2].hex()[26:], 'block': log['blockNumber'], 'tx': log['transactionHash'].hex() }) return events events = get_transfer_events( '0x4200000000000000000000000000000000000006', 'latest', 'latest' ) print(f'Found {len(events)} transfer events') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0x4200000000000000000000000000000000000006") transferTopic := common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef") query := ethereum.FilterQuery{ FromBlock: big.NewInt(0), ToBlock: nil, Addresses: []common.Address{contractAddress}, Topics: [][]common.Hash, } logs, err := client.FilterLogs(context.Background(), query) if err != nil { log.Fatal(err) } fmt.Printf("Found %d events\n", len(logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32005 | Query returned more than 10000 results | Reduce block range | | -32602 | Invalid params | Invalid filter parameters | ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create a filter for logs - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for new logs --- ## eth_getStorageAt - Base RPC Method # eth_getStorageAt Returns the value from a storage position at a given address on Base. ## Use Cases - **Contract analysis** - Read raw storage values - **State verification** - Verify contract state - **Security auditing** - Analyze storage layout for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations - **Protocol monitoring** - Track state changes ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte contract address | | `position` | `QUANTITY` | Yes | Storage slot position | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0x4200000000000000000000000000000000000006", "0x0", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0x4200000000000000000000000000000000000006", "0x0", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x4200000000000000000000000000000000000006'; const slot = 0; const storage = await provider.getStorage(address, slot); console.log('Storage at slot 0:', storage); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x4200000000000000000000000000000000000006' storage = w3.eth.get_storage_at(address, 0) print(f'Storage at slot 0: {storage.hex()}') ``` ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_call`](./eth_call) - Call contract functions --- ## eth_getTransactionByHash - Base RPC Method # eth_getTransactionByHash Returns the information about a transaction by transaction hash on Base. > **Why Base?** Build on Coinbase's L2 with 54% of L2 market revenue and direct access to 110M+ Coinbase users with $8B+ TVL, $0.08 gas fees, built-in Coinbase distribution, and seamless fiat rails. ## Use Cases The `eth_getTransactionByHash` method is essential for: - **Transaction tracking** - Get details of pending or confirmed transactions - **Payment verification** - Verify transaction parameters - **Debugging** - Analyze transaction data for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations - **Block explorers** - Display transaction information ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `hash` | `DATA` | Transaction hash | | `from` | `DATA` | Sender address | | `to` | `DATA` | Recipient address | | `value` | `QUANTITY` | Value in wei | | `gas` | `QUANTITY` | Gas provided | | `gasPrice` | `QUANTITY` | Gas price in wei | | `input` | `DATA` | Transaction input data | | `nonce` | `QUANTITY` | Sender's nonce | | `blockHash` | `DATA` | Block hash (null if pending) | | `blockNumber` | `QUANTITY` | Block number (null if pending) | ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269'; const tx = await provider.getTransaction(txHash); if (tx) { console.log('From:', tx.from); console.log('To:', tx.to); console.log('Value:', formatEther(tx.value)); console.log('Block:', tx.blockNumber); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269' tx = w3.eth.get_transaction(tx_hash) if tx: print(f'From: {tx["from"]}') print(f'To: {tx["to"]}') print(f'Value: {w3.from_wei(tx["value"], "ether")}') print(f'Block: {tx["blockNumber"]}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269") tx, isPending, err := client.TransactionByHash(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Pending: %v\n", isPending) fmt.Printf("Value: %s\n", tx.Value().String()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash format | ## Related Methods - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction receipt - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionCount - Base RPC Method # eth_getTransactionCount Returns the number of transactions sent from an address on Base (the nonce). ## Use Cases - **Transaction building** - Get correct nonce for new transactions - **Account analysis** - Count total outgoing transactions - **Nonce management** - Handle pending transaction queues - **Wallet operations** - Prepare transactions for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag (`pending` for next nonce) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x4200000000000000000000000000000000000006", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x4200000000000000000000000000000000000006", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x4200000000000000000000000000000000000006'; const nonce = await provider.getTransactionCount(address); console.log('Nonce:', nonce); // Get pending nonce for new transaction const pendingNonce = await provider.getTransactionCount(address, 'pending'); console.log('Next nonce:', pendingNonce); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x4200000000000000000000000000000000000006' nonce = w3.eth.get_transaction_count(address) print(f'Nonce: {nonce}') # Get pending nonce pending_nonce = w3.eth.get_transaction_count(address, 'pending') print(f'Next nonce: {pending_nonce}') ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionReceipt - Base RPC Method # eth_getTransactionReceipt Returns the receipt of a transaction by transaction hash on Base. Receipt is only available for mined transactions. > **Why Base?** Build on Coinbase's L2 with 54% of L2 market revenue and direct access to 110M+ Coinbase users with $8B+ TVL, $0.08 gas fees, built-in Coinbase distribution, and seamless fiat rails. ## Use Cases The `eth_getTransactionReceipt` method is essential for: - **Transaction confirmation** - Verify transaction was mined successfully - **Gas analysis** - Check actual gas used vs estimated - **Event parsing** - Read emitted events from logs - **Status verification** - Confirm success/failure for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `status` | `QUANTITY` | `1` (success) or `0` (failure) | | `transactionHash` | `DATA` | Transaction hash | | `blockHash` | `DATA` | Block hash | | `blockNumber` | `QUANTITY` | Block number | | `gasUsed` | `QUANTITY` | Gas used by this transaction | | `cumulativeGasUsed` | `QUANTITY` | Total gas used in block up to this tx | | `logs` | `Array` | Array of log objects | | `contractAddress` | `DATA` | Created contract address (if deployment) | ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269'; const receipt = await provider.getTransactionReceipt(txHash); if (receipt) { console.log('Status:', receipt.status === 1 ? 'Success' : 'Failed'); console.log('Gas Used:', receipt.gasUsed.toString()); console.log('Block:', receipt.blockNumber); console.log('Logs:', receipt.logs.length); // Parse specific events for (const log of receipt.logs) { console.log('Event from:', log.address); } } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269' receipt = w3.eth.get_transaction_receipt(tx_hash) if receipt: status = 'Success' if receipt['status'] == 1 else 'Failed' print(f'Status: {status}') print(f'Gas Used: {receipt["gasUsed"]}') print(f'Block: {receipt["blockNumber"]}') print(f'Logs: {len(receipt["logs"])}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269") receipt, err := client.TransactionReceipt(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Status: %d\n", receipt.Status) fmt.Printf("Gas Used: %d\n", receipt.GasUsed) fmt.Printf("Logs: %d\n", len(receipt.Logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash | **Note**: Returns `null` if transaction is not yet mined. ## Related Methods - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details - [`eth_getLogs`](./eth_getLogs) - Query logs by filter --- ## eth_hashrate - Get node hashrate(Base) # eth_hashrate Get node hashrate on the Base network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_hashrate](https://ethereum.org/developers/docs/apis/json-rpc/#eth_hashrate) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_hashrate", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_hashrate', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Base documentation](/docs/base).* --- ## eth_maxPriorityFeePerGas - Base RPC Method # eth_maxPriorityFeePerGas Returns the current recommended priority fee per gas on Base for EIP-1559 transactions. ## Use Cases - **EIP-1559 transactions** - Set appropriate priority fees - **Transaction acceleration** - Calculate tips for faster inclusion - **Gas optimization** - Balance speed vs cost for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); console.log('Max Priority Fee:', formatUnits(feeData.maxPriorityFeePerGas, 'gwei'), 'Gwei'); console.log('Max Fee Per Gas:', formatUnits(feeData.maxFeePerGas, 'gwei'), 'Gwei'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) priority_fee = w3.eth.max_priority_fee print(f'Max Priority Fee: {w3.from_wei(priority_fee, "gwei")} Gwei') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get legacy gas price - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data --- ## eth_mining - Check if node is mining(Base) # eth_mining Check if node is mining on the Base network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_mining](https://ethereum.org/developers/docs/apis/json-rpc/#eth_mining) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_mining', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Base documentation](/docs/base).* --- ## eth_newBlockFilter - Base RPC Method # eth_newBlockFilter Creates a filter on Base to notify when a new block arrives. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newBlockFilter', []); // Poll for new blocks const newBlocks = await provider.send('eth_getFilterChanges', [filterId]); console.log('New block hashes:', newBlocks); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_blockNumber`](./eth_blockNumber) - Get current block --- ## eth_newFilter - Base RPC Method # eth_newFilter Creates a filter object on Base to notify when state changes (logs). ## Use Cases - **Event monitoring** - Subscribe to contract events - **Real-time updates** - Track events for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations - **Indexing** - Build event indexes incrementally ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block | | `toBlock` | `QUANTITY\|TAG` | No | Ending block | | `address` | `DATA\|Array` | No | Contract address(es) | | `topics` | `Array` | No | Topic filters | ## Request ```json { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0x4200000000000000000000000000000000000006", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0x4200000000000000000000000000000000000006" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Create filter const filterId = await provider.send('eth_newFilter', [{ fromBlock: 'latest', address: '0x4200000000000000000000000000000000000006', topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'] }]); // Poll for changes const changes = await provider.send('eth_getFilterChanges', [filterId]); console.log('New events:', changes); // Cleanup await provider.send('eth_uninstallFilter', [filterId]); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for changes - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_newPendingTransactionFilter - Base RPC Method # eth_newPendingTransactionFilter Creates a filter on Base to notify when new pending transactions arrive. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newPendingTransactionFilter', []); // Poll for pending transactions const pendingTxs = await provider.send('eth_getFilterChanges', [filterId]); console.log('Pending transaction hashes:', pendingTxs); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_protocolVersion - Get protocol version(Base) # eth_protocolVersion Get protocol version on the Base network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_protocolVersion](https://ethereum.org/developers/docs/apis/json-rpc/#eth_protocolversion) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_protocolVersion", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_protocolVersion', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Base documentation](/docs/base).* --- ## eth_sendRawTransaction - Base RPC Method # eth_sendRawTransaction Submits a pre-signed transaction for broadcast to Base. > **Why Base?** Build on Coinbase's L2 with 54% of L2 market revenue and direct access to 110M+ Coinbase users with $8B+ TVL, $0.08 gas fees, built-in Coinbase distribution, and seamless fiat rails. ## Use Cases The `eth_sendRawTransaction` method is essential for: - **Broadcasting transactions** - Submit signed transactions to the network - **Wallet operations** - Send native tokens and interact with contracts - **DeFi operations** - Execute swaps, provide liquidity for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations - **Batch operations** - Submit multiple transactions efficiently ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `signedTransactionData` | `DATA` | Yes | The signed transaction data (RLP encoded) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | 32-byte transaction hash | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c808504a817c80082520894..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const wallet = new Wallet('YOUR_PRIVATE_KEY', provider); // Send native tokens async function sendTransaction(to, value) { const tx = await wallet.sendTransaction({ to: to, value: parseEther(value) }); console.log('Transaction hash:', tx.hash); // Wait for confirmation const receipt = await tx.wait(); console.log('Confirmed in block:', receipt.blockNumber); return receipt; } // Send to contract async function sendContractTransaction(contract, method, args, value = '0') { const tx = await contract[method](...args, { value: parseEther(value) }); return await tx.wait(); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) def send_transaction(private_key, to, value_in_ether): account = w3.eth.account.from_key(private_key) # Build transaction tx = { 'nonce': w3.eth.get_transaction_count(account.address), 'to': to, 'value': w3.to_wei(value_in_ether, 'ether'), 'gas': 21000, 'gasPrice': w3.eth.gas_price, 'chainId': w3.eth.chain_id } # Sign transaction signed_tx = account.sign_transaction(tx) # Send transaction tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) print(f'Transaction hash: {tx_hash.hex()}') # Wait for confirmation receipt = w3.eth.wait_for_transaction_receipt(tx_hash) print(f'Confirmed in block: {receipt["blockNumber"]}') return receipt ``` ```go package main "context" "crypto/ecdsa" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY") if err != nil { log.Fatal(err) } publicKey := privateKey.Public() publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey) fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA) nonce, _ := client.PendingNonceAt(context.Background(), fromAddress) value := big.NewInt(1000000000000000000) gasLimit := uint64(21000) gasPrice, _ := client.SuggestGasPrice(context.Background()) toAddress := common.HexToAddress("0x4200000000000000000000000000000000000006") tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil) chainID, _ := client.NetworkID(context.Background()) signedTx, _ := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey) err = client.SendTransaction(context.Background(), signedTx) if err != nil { log.Fatal(err) } fmt.Printf("Transaction hash: %s\n", signedTx.Hash().Hex()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Nonce too low | Transaction nonce already used | | -32000 | Insufficient funds | Account has insufficient balance | | -32000 | Gas too low | Gas limit insufficient | | -32000 | Replacement underpriced | Gas price too low for replacement | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas required - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction result --- ## eth_sendTransaction - Send transaction (wallet... # eth_sendTransaction > **Important**: Dwellir's shared Base endpoints do not manage user private keys. JSON-RPC nodes cannot unlock your account, so `eth_sendTransaction` calls will fail. Sign transactions client-side and broadcast them with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Why this method is disabled on shared nodes - [`eth_sendTransaction` requires the node to hold and unlock the `from` account's private key](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction). - Managed infrastructure providers disable it for security reasons rather than storing customer keys on shared servers (for example, [Infura explicitly blocks the method on shared endpoints](https://docs.infura.io/api/networks/ethereum/json-rpc-methods/eth_sendtransaction)). ## Recommended workflow 1. Build the raw transaction locally with your wallet or SDK. 2. Sign the payload client-side (hardware wallet, custodial service, or library). 3. Submit the signed hex string with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Example response from the shared endpoint ```bash curl -s -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"0x0000000000000000000000000000000000000000"}],"id":1}' ``` ```json {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"unknown account"}} ``` Need help? Contact our [support team](mailto:support@dwellir.com) or use the dedicated [`eth_sendRawTransaction`](./eth_sendRawTransaction) guide. --- ## eth_signTransaction - Sign transaction (rarely... # eth_signTransaction Signs a transaction using an unlocked account on the node. **Important**: Most RPC providers don't support this method for security reasons, as it requires private keys to be stored on the server. ## Security Considerations - This method requires an unlocked account on the node - Private keys must be available to the RPC server - Most production RPC providers disable this method - Use client-side signing libraries instead for better security ## Parameters 1. `Object` - The transaction object: - `from`: `DATA`, 20 Bytes - The address the transaction is sent from - `to`: `DATA`, 20 Bytes - (optional) The address the transaction is directed to - `gas`: `QUANTITY` - (optional) Integer of the gas provided for the transaction execution - `gasPrice`: `QUANTITY` - (optional) Integer of the gasPrice used for each paid gas - `value`: `QUANTITY` - (optional) Integer of the value sent with this transaction - `data`: `DATA` - (optional) The compiled code of a contract OR the hash of the invoked method signature and encoded parameters ## Returns `DATA` - The signed transaction data, ready for transmission via `eth_sendRawTransaction`. ## Implementation Example ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_signTransaction", "params": [{ "from": "0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a" }], "id": 1 }' ``` ```javascript const response = await fetch('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_signTransaction', params: [{ from: '0x9b2055d370f73ec7d8a03e965129118dc8f5bf83', to: '0xd46e8dd67c5d32be8058bb8eb970870f07244567', gas: '0x76c0', gasPrice: '0x9184e72a000', value: '0x9184e72a' }], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0xf86c808504a817c8008276c094d46e8dd67c5d32be8058bb8eb970870f072445675849184e72a8001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804" } ``` **Note**: This method is typically not available on hosted RPC providers for security reasons. The response shows a signed transaction ready for broadcast. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Base documentation](/docs/base).* --- ## eth_syncing - Base RPC Method # eth_syncing Returns syncing status of Base node. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 } ``` ## Returns Returns `false` if not syncing, or an object with sync status. ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const syncing = await provider.send('eth_syncing', []); if (syncing === false) { console.log('Node is fully synced'); } else { console.log('Syncing:', syncing); } ``` ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get current block - [`net_peerCount`](./net_peerCount) - Get peer count --- ## eth_uninstallFilter - Base RPC Method # eth_uninstallFilter Uninstalls a filter on Base. Should be called when no longer needed. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID to uninstall | ## Request ```json { "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if filter was found and uninstalled | ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const success = await provider.send('eth_uninstallFilter', [filterId]); console.log('Filter removed:', success); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter --- ## Base - Ethereum L2 Documentation # Base L2 - Build on Coinbase's Ethereum Layer 2 ## Why Build on Base? Base is Coinbase's Ethereum Layer 2 solution, designed to bring the next billion users onchain. Built on Optimism's OP Stack, Base offers: ### 🚀 **Lightning Fast Performance** - **Sub-second block times** - Get near-instant transaction confirmations - **10-100x lower costs** than Ethereum mainnet - **EIP-4844 enabled** - Leveraging blob data for even lower fees ### 🛡️ **Enterprise Security** - **Backed by Coinbase** - Institutional-grade infrastructure - **Ethereum security** - Inherits L1 security guarantees - **Battle-tested** - Built on proven Optimism technology ### 🌍 **Massive Ecosystem** - **1M+ weekly active users** - Rapidly growing user base - **$2B+ TVL** - Strong DeFi ecosystem - **Major integrations** - Circle USDC, Chainlink, The Graph ## Quick Start with Base Connect to Base in seconds with Dwellir's optimized endpoints: ### Installation & Setup ```javascript // Connect to Base mainnet const provider = new JsonRpcProvider( 'https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); // Get the latest block const block = await provider.getBlock('latest'); console.log('Latest block:', block.number); // Query account balance const balance = await provider.getBalance('0x...'); console.log('Balance:', balance.toString()); ``` ```javascript const Web3 = require('web3'); // Connect to Base mainnet const web3 = new Web3( 'https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); // Get chain ID to verify connection const chainId = await web3.eth.getChainId(); console.log('Connected to Base:', chainId === 8453); // Get gas price for optimal transaction pricing const gasPrice = await web3.eth.getGasPrice(); console.log('Current gas price:', gasPrice); ``` ```typescript // Create Base client const client = createPublicClient({ chain: base, transport: http('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'), }); // Read contract data const data = await client.readContract({ address: '0x...', abi: contractAbi, functionName: 'balanceOf', args: ['0x...'], }); ``` ## Network Information Chain ID 8453 Mainnet Block Time 2 seconds Average Gas Token ETH Native token RPC Standard Ethereum JSON-RPC 2.0 ## JSON-RPC API Reference Base supports the full [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/). Access all standard methods plus L2-specific optimizations. ## Common Integration Patterns ### 🔄 Transaction Monitoring Monitor pending and confirmed transactions efficiently: ```javascript // Watch for transaction confirmation async function waitForTransaction(txHash) { const receipt = await provider.waitForTransaction(txHash, 1); // L2 specific: Check L1 data availability if (receipt.l1Fee) { console.log('L1 data cost:', receipt.l1Fee); } return receipt; } ``` ### 💰 Gas Optimization Optimize gas costs on Base L2: ```javascript // Estimate L2 execution gas const l2Gas = await provider.estimateGas(tx); // Get current L1 data fee (Base specific) const l1DataFee = await provider.send('eth_estimateL1Fee', [tx]); // Total cost = L2 execution + L1 data posting const totalCost = l2Gas + BigInt(l1DataFee); ``` ### 🔍 Event Filtering Efficiently query contract events: ```javascript // Query events with automatic retry and pagination async function getEvents(contract, eventName, fromBlock = 0) { const filter = contract.filters[eventName](); const events = []; const batchSize = 2000; // Base recommended batch size for (let i = fromBlock; i <= currentBlock; i += batchSize) { const batch = await contract.queryFilter( filter, i, Math.min(i + batchSize - 1, currentBlock) ); events.push(...batch); } return events; } ``` ## Performance Best Practices ### 1. **Batch Requests** Combine multiple RPC calls for optimal performance: ```javascript const batch = [ { method: 'eth_blockNumber', params: [] }, { method: 'eth_gasPrice', params: [] }, { method: 'eth_getBalance', params: [address, 'latest'] } ]; const results = await provider.send(batch); ``` ### 2. **Connection Pooling** Reuse provider instances to minimize connection overhead: ```javascript // Singleton pattern for provider class BaseProvider { static instance = null; static getInstance() { if (!this.instance) { this.instance = new JsonRpcProvider( 'https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); } return this.instance; } } ``` ### 3. **Smart Caching** Cache immutable data to reduce API calls: ```javascript const cache = new Map(); async function getCachedBlockData(blockNumber) { const key = `block_${blockNumber}`; if (!cache.has(key)) { const block = await provider.getBlock(blockNumber); cache.set(key, block); } return cache.get(key); } ``` ## Troubleshooting Common Issues ### Error: "Insufficient funds for L1 fee" Base transactions require ETH for both L2 execution and L1 data availability: ```javascript // Always account for L1 fees in balance checks const balance = await provider.getBalance(address); const l1Fee = await provider.send('eth_estimateL1Fee', [tx]); const l2Gas = await provider.estimateGas(tx); const totalRequired = l2Gas + BigInt(l1Fee) + tx.value; if (balance < totalRequired) { throw new Error(`Need ${totalRequired - balance} more ETH`); } ``` ### Error: "Transaction underpriced" Base uses EIP-1559 pricing. Always use dynamic gas pricing: ```javascript // Get current fee data const feeData = await provider.getFeeData(); const tx = { to: recipient, value: amount, maxFeePerGas: feeData.maxFeePerGas, maxPriorityFeePerGas: feeData.maxPriorityFeePerGas, gasLimit: 21000n }; ``` ### Error: "Rate limit exceeded" Implement exponential backoff for resilient applications: ```javascript async function callWithRetry(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error.code === 429 && i < maxRetries - 1) { await new Promise(r => setTimeout(r, 2 ** i * 1000)); } else { throw error; } } } } ``` ## Migration Guide ### From Ethereum Mainnet Moving from L1 to Base L2 requires minimal changes: ```javascript // Before (Ethereum) const provider = new JsonRpcProvider('https://eth-rpc.example.com'); // After (Base) const provider = new JsonRpcProvider( 'https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); // ✅ Smart contracts work identically // ✅ Same tooling and libraries // ⚠️ Different chain ID (8453) // ⚠️ Separate block numbers // ⚠️ L1 data fees apply ``` ## Resources & Tools ### Official Resources - [Base Documentation](https://docs.base.org) - [Base Bridge](https://bridge.base.org) - [Base Block Explorer](https://basescan.org) ### Developer Tools - [Hardhat Config](https://docs.base.org/tools/hardhat) - [Foundry Setup](https://docs.base.org/tools/foundry) - [Truffle Integration](https://docs.base.org/tools/truffle) ### Need Help? - 📧 **Email**: support@dwellir.com - 📚 **Docs**: You're here! - 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com) --- *Start building on Base with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)* --- ## net_listening - Base RPC Method # net_listening Returns `true` if client is actively listening for network connections on Base. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if listening | ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const listening = await provider.send('net_listening', []); console.log('Node listening:', listening); ``` ## Related Methods - [`net_peerCount`](./net_peerCount) - Get peer count --- ## net_peerCount - Base RPC Method # net_peerCount Returns number of peers currently connected to Base client. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Number of connected peers (hexadecimal) | ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const peerCount = await provider.send('net_peerCount', []); console.log('Peer count:', parseInt(peerCount, 16)); ``` ## Related Methods - [`net_listening`](./net_listening) - Check if listening --- ## net_version - Base RPC Method # net_version Returns the current network ID on Base. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Network ID as a string | ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const networkId = await provider.send('net_version', []); console.log('Network ID:', networkId); ``` ## Related Methods - [`eth_chainId`](./eth_chainId) - Get chain ID --- ## rollup_gasPrices - Get L2 gas price oracle data # rollup_gasPrices Get L2 gas price oracle data on the Base network. ## Parameters Varies by method. Please refer to the official documentation: [Optimism JSON-RPC (rollup methods)](https://docs.optimism.io/operators/node-operators/json-rpc) for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "rollup_gasPrices", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'rollup_gasPrices', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Base documentation](/docs/base).* --- ## rollup_getInfo - Get rollup configuration # rollup_getInfo Get rollup configuration on the Base network. ## Parameters Varies by method. Please refer to the official documentation: [Optimism JSON-RPC (rollup methods)](https://docs.optimism.io/operators/node-operators/json-rpc) for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "rollup_getInfo", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'rollup_getInfo', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Base documentation](/docs/base).* --- ## trace_block - Base RPC Method # trace_block Returns traces for all transactions in a block on Base. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Block analysis** - Inspect all internal transactions in a block - **MEV research** - Analyze transaction ordering and internal calls - **Indexing** - Build comprehensive transaction indexes for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex or tag (`latest`, `earliest`, `pending`) | ## Request ```json { "jsonrpc": "2.0", "method": "trace_block", "params": ["latest"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_block", "params": ["latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('trace_block', ['latest']); console.log('Traces in block:', traces.length); for (const trace of traces.slice(0, 5)) { console.log(` ${trace.action.from} -> ${trace.action.to} (${trace.type})`); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) traces = w3.provider.make_request('trace_block', ['latest']) for trace in traces['result'][:5]: action = trace['action'] print(f'{action["from"]} -> {action.get("to", "CREATE")} ({trace["type"]})') ``` ## Related Methods - [`trace_filter`](./trace_filter) - Filter traces by address or block range - [`trace_transaction`](./trace_transaction) - Trace a specific transaction - [`trace_get`](./trace_get) - Get a specific trace by index --- ## trace_call - Base RPC Method # trace_call Traces a call without creating a transaction on Base, returning the trace output. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Call simulation** - Preview internal calls before sending a transaction - **Contract interaction analysis** - Understand how contracts interact - **Gas estimation** - Analyze gas usage patterns for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `callObject` | `Object` | Yes | Transaction call object (`from`, `to`, `gas`, `value`, `data`) | | `traceTypes` | `Array` | Yes | Trace types: `["trace"]`, `["vmTrace"]`, `["stateDiff"]`, or combinations | | `blockNumber` | `QUANTITY\|TAG` | No | Block number or tag (default: `latest`) | ## Request ```json { "jsonrpc": "2.0", "method": "trace_call", "params": [ { "to": "0x4200000000000000000000000000000000000006", "data": "0x70a082310000000000000000000000004200000000000000000000000000000000000006" }, ["trace"], "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_call", "params": [ {"to": "0x4200000000000000000000000000000000000006", "data": "0x70a082310000000000000000000000004200000000000000000000000000000000000006"}, ["trace"], "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const result = await provider.send('trace_call', [ { to: '0x4200000000000000000000000000000000000006', data: '0x70a082310000000000000000000000004200000000000000000000000000000000000006' }, ['trace'], 'latest' ]); console.log('Trace output:', result.trace); console.log('VM trace:', result.vmTrace); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) result = w3.provider.make_request('trace_call', [ { 'to': '0x4200000000000000000000000000000000000006', 'data': '0x70a082310000000000000000000000004200000000000000000000000000000000000006' }, ['trace'], 'latest' ]) print(f'Trace: {result["result"]["trace"]}') ``` ## Related Methods - [`trace_filter`](./trace_filter) - Filter traces by criteria - [`eth_call`](./eth_call) - Execute call without trace - [`trace_transaction`](./trace_transaction) - Trace a specific transaction --- ## trace_callMany - Base RPC Method # trace_callMany Traces multiple calls in sequence on Base, where each call can depend on the state changes of the previous one. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Multi-step simulation** - Simulate a sequence of dependent transactions - **Arbitrage analysis** - Test multi-hop swap paths - **Batch operations** - Preview multiple contract interactions for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `calls` | `Array` | Yes | Array of `[callObject, traceTypes]` pairs | | `blockNumber` | `QUANTITY\|TAG` | No | Block number or tag (default: `latest`) | Each element in `calls` is a tuple of: - `callObject` - Transaction call object (`from`, `to`, `gas`, `value`, `data`) - `traceTypes` - Array of trace types: `["trace"]`, `["vmTrace"]`, `["stateDiff"]` ## Request ```json { "jsonrpc": "2.0", "method": "trace_callMany", "params": [ [ [{"to": "0x4200000000000000000000000000000000000006", "data": "0x70a082310000000000000000000000004200000000000000000000000000000000000006"}, ["trace"]], [{"to": "0x4200000000000000000000000000000000000006", "data": "0x18160ddd"}, ["trace"]] ], "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_callMany", "params": [ [ [{"to": "0x4200000000000000000000000000000000000006", "data": "0x70a082310000000000000000000000004200000000000000000000000000000000000006"}, ["trace"]], [{"to": "0x4200000000000000000000000000000000000006", "data": "0x18160ddd"}, ["trace"]] ], "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const results = await provider.send('trace_callMany', [ [ [{ to: '0x4200000000000000000000000000000000000006', data: '0x70a082310000000000000000000000004200000000000000000000000000000000000006' }, ['trace']], [{ to: '0x4200000000000000000000000000000000000006', data: '0x18160ddd' }, ['trace']] ], 'latest' ]); console.log('Call results:', results.length); for (const result of results) { console.log(' Output:', result.output); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) results = w3.provider.make_request('trace_callMany', [ [ [{'to': '0x4200000000000000000000000000000000000006', 'data': '0x70a082310000000000000000000000004200000000000000000000000000000000000006'}, ['trace']], [{'to': '0x4200000000000000000000000000000000000006', 'data': '0x18160ddd'}, ['trace']] ], 'latest' ]) for i, result in enumerate(results['result']): print(f'Call {i}: output={result.get("output", "N/A")}') ``` ## Related Methods - [`trace_call`](./trace_call) - Trace a single call - [`eth_call`](./eth_call) - Execute call without trace --- ## trace_filter - Base RPC Method # trace_filter Returns traces matching a filter on Base. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Address activity** - Find all internal transactions involving an address - **Contract monitoring** - Track calls to specific contracts - **Forensic analysis** - Investigate transaction patterns for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterObject` | `Object` | Yes | Filter criteria (see below) | ### Filter Object Fields | Field | Type | Description | |-------|------|-------------| | `fromBlock` | `QUANTITY\|TAG` | Start block (hex or tag) | | `toBlock` | `QUANTITY\|TAG` | End block (hex or tag) | | `fromAddress` | `Array` | Filter by sender addresses | | `toAddress` | `Array` | Filter by receiver addresses | | `after` | `QUANTITY` | Offset for pagination | | `count` | `QUANTITY` | Max results to return | ## Request ```json { "jsonrpc": "2.0", "method": "trace_filter", "params": [{ "fromBlock": "latest", "toBlock": "latest", "toAddress": ["0x4200000000000000000000000000000000000006"], "count": 10 }], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_filter", "params": [{ "fromBlock": "latest", "toBlock": "latest", "toAddress": ["0x4200000000000000000000000000000000000006"], "count": 10 }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('trace_filter', [{ fromBlock: 'latest', toBlock: 'latest', toAddress: ['0x4200000000000000000000000000000000000006'], count: 10 }]); console.log('Matching traces:', traces.length); for (const trace of traces) { console.log(` Block ${trace.blockNumber}: ${trace.action.from} -> ${trace.action.to}`); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) traces = w3.provider.make_request('trace_filter', [{ 'fromBlock': 'latest', 'toBlock': 'latest', 'toAddress': ['0x4200000000000000000000000000000000000006'], 'count': 10 }]) for trace in traces['result']: action = trace['action'] print(f'Block {trace["blockNumber"]}: {action["from"]} -> {action.get("to", "CREATE")}') ``` ## Related Methods - [`trace_block`](./trace_block) - Get all traces in a block - [`trace_transaction`](./trace_transaction) - Get traces for a specific transaction - [`eth_getLogs`](./eth_getLogs) - Filter event logs --- ## trace_get - Base RPC Method # trace_get Returns a trace at a specific position within a transaction on Base. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Specific trace lookup** - Get a single trace by its position index - **Internal call inspection** - Examine a specific internal call - **Targeted debugging** - Investigate particular call depth for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `indices` | `Array` | Yes | Trace index positions (e.g., `["0x0"]` for the first trace) | ## Request ```json { "jsonrpc": "2.0", "method": "trace_get", "params": ["0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269", ["0x0"]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_get", "params": ["0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269", ["0x0"]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const trace = await provider.send('trace_get', [ '0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269', ['0x0'] ]); console.log('Trace type:', trace.type); console.log('From:', trace.action.from); console.log('To:', trace.action.to); console.log('Value:', trace.action.value); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) trace = w3.provider.make_request('trace_get', [ '0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269', ['0x0'] ]) result = trace['result'] print(f'Type: {result["type"]}') print(f'From: {result["action"]["from"]}') print(f'To: {result["action"]["to"]}') ``` ## Related Methods - [`trace_transaction`](./trace_transaction) - Get all traces for a transaction - [`trace_block`](./trace_block) - Get all traces in a block --- ## trace_replayBlockTransactions - Base RPC Method # trace_replayBlockTransactions Replays all transactions in a block on Base and returns the requested traces. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Block replay** - Re-execute all transactions with full trace output - **State diff analysis** - Get state changes for every transaction in a block - **VM trace extraction** - Obtain detailed EVM execution traces for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex or tag | | `traceTypes` | `Array` | Yes | Trace types: `["trace"]`, `["vmTrace"]`, `["stateDiff"]`, or combinations | ## Request ```json { "jsonrpc": "2.0", "method": "trace_replayBlockTransactions", "params": ["latest", ["trace"]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_replayBlockTransactions", "params": ["latest", ["trace"]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const results = await provider.send('trace_replayBlockTransactions', [ 'latest', ['trace'] ]); console.log('Transactions replayed:', results.length); for (const result of results.slice(0, 3)) { console.log(` Tx ${result.transactionHash}: ${result.trace.length} traces`); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) results = w3.provider.make_request('trace_replayBlockTransactions', [ 'latest', ['trace'] ]) for tx in results['result'][:3]: print(f'Tx {tx["transactionHash"]}: {len(tx["trace"])} traces') ``` ## Related Methods - [`trace_replayTransaction`](./trace_replayTransaction) - Replay a single transaction - [`trace_block`](./trace_block) - Get traces without replay - [`trace_filter`](./trace_filter) - Filter traces by criteria --- ## trace_replayTransaction - Base RPC Method # trace_replayTransaction Replays a transaction on Base and returns the requested traces. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction replay** - Re-execute a transaction with full trace output - **State diff extraction** - Get exact state changes from a transaction - **VM trace debugging** - Get opcode-level execution details for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `traceTypes` | `Array` | Yes | Trace types: `["trace"]`, `["vmTrace"]`, `["stateDiff"]`, or combinations | ## Request ```json { "jsonrpc": "2.0", "method": "trace_replayTransaction", "params": ["0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269", ["trace"]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_replayTransaction", "params": ["0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269", ["trace"]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const result = await provider.send('trace_replayTransaction', [ '0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269', ['trace'] ]); console.log('Trace:', result.trace.length, 'entries'); console.log('State diff:', result.stateDiff ? 'present' : 'not requested'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) result = w3.provider.make_request('trace_replayTransaction', [ '0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269', ['trace'] ]) trace = result['result'] print(f'Trace entries: {len(trace["trace"])}') ``` ## Related Methods - [`trace_replayBlockTransactions`](./trace_replayBlockTransactions) - Replay all transactions in a block - [`trace_transaction`](./trace_transaction) - Get traces without replay - [`trace_block`](./trace_block) - Get all traces in a block --- ## trace_transaction - Base RPC Method # trace_transaction Returns all traces for a specific transaction on Base. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction analysis** - See all internal calls made by a transaction - **Token transfer tracking** - Trace value flows through contracts - **Debugging** - Understand execution flow for consumer dApps, SocialFi, NFT marketplaces, and merchant payment integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "trace_transaction", "params": ["0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_transaction", "params": ["0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('trace_transaction', [ '0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269' ]); console.log('Traces:', traces.length); for (const trace of traces) { console.log(` ${trace.action.from} -> ${trace.action.to} (${trace.type})`); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) traces = w3.provider.make_request('trace_transaction', [ '0x5c884a466fb59ee69114a0c99cb15d4d8af670a37be53fd59ffda3b5566b4269' ]) for trace in traces['result']: action = trace['action'] print(f'{action["from"]} -> {action.get("to", "CREATE")} ({trace["type"]})') ``` ## Related Methods - [`trace_get`](./trace_get) - Get a specific trace by index - [`trace_block`](./trace_block) - Get all traces in a block - [`trace_filter`](./trace_filter) - Filter traces by criteria --- ## web3_clientVersion - Base RPC Method # web3_clientVersion Returns the current client version on Base. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Client version string | ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const version = await provider.send('web3_clientVersion', []); console.log('Client version:', version); ``` --- ## web3_sha3 - Base RPC Method # web3_sha3 Returns Keccak-256 (not standard SHA3-256) of the given data on Base. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `data` | `DATA` | Yes | Data to hash | ## Request ```json { "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Keccak-256 hash of the data | ## Code Examples ```bash curl -X POST https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Using RPC const hash = await provider.send('web3_sha3', ['0x68656c6c6f']); console.log('Hash:', hash); // Using ethers directly (faster) const localHash = keccak256(toUtf8Bytes('hello')); console.log('Local hash:', localHash); ``` --- ## debug_traceBlock - Berachain RPC Method # debug_traceBlock Traces all transactions in a block on Berachain by block RLP. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Analyze transaction execution step-by-step - **Smart contract analysis** - Debug contract interactions - **Security auditing** - Trace internal calls for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockRlp` | `DATA` | Yes | RLP-encoded block data | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); // Use debug_traceBlockByNumber instead (more practical) const traces = await provider.send('debug_traceBlockByNumber', ['latest', {}]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by block number - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by block hash --- ## debug_traceBlockByHash - Berachain RPC Method # debug_traceBlockByHash Traces all transactions in a block on Berachain by block hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0x969b796c2c98668e687636319dba231c7f3f77e1c89dab82fba3d17f8f0f9e55", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0x969b796c2c98668e687636319dba231c7f3f77e1c89dab82fba3d17f8f0f9e55", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0x969b796c2c98668e687636319dba231c7f3f77e1c89dab82fba3d17f8f0f9e55'; const traces = await provider.send('debug_traceBlockByHash', [blockHash, { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by number - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceBlockByNumber - Berachain RPC Method # debug_traceBlockByNumber Traces all transactions in a block on Berachain by block number. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('debug_traceBlockByNumber', ['latest', { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by hash - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceCall - Berachain RPC Method # debug_traceCall Traces a call without creating a transaction on Berachain. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction simulation** - Debug before sending - **Gas analysis** - Analyze gas usage per opcode - **Contract debugging** - Step through execution for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `call` | `Object` | Yes | Call object (same as eth_call) | | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ { "to": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "data": "0x70a082310000000000000000000000007507c1dc16935B82698e4C63f2746A2fCf994dF8" }, "latest", {} ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ {"to": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "data": "0x70a082310000000000000000000000007507c1dc16935B82698e4C63f2746A2fCf994dF8"}, "latest", {"tracer": "callTracer"} ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const trace = await provider.send('debug_traceCall', [ { to: '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8', data: '0x70a082310000000000000000000000007507c1dc16935B82698e4C63f2746A2fCf994dF8' }, 'latest', { tracer: 'callTracer' } ]); console.log('Trace:', trace); ``` ## Related Methods - [`eth_call`](./eth_call) - Execute call without trace - [`debug_traceTransaction`](./debug_traceTransaction) - Trace actual transaction --- ## debug_traceTransaction - Berachain RPC Method # debug_traceTransaction Traces a transaction execution on Berachain by transaction hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Understand exactly what happened - **Failure analysis** - Find where and why a transaction reverted - **Gas optimization** - Analyze gas usage for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Tracer Options - `{}` - Default opcode tracer (verbose) - `{ tracer: "callTracer" }` - Call tree tracer - `{ tracer: "prestateTracer" }` - Pre-state tracer ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const txHash = '0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671'; // Call tracer - shows internal calls const callTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'callTracer' } ]); console.log('Type:', callTrace.type); console.log('From:', callTrace.from); console.log('To:', callTrace.to); console.log('Gas used:', parseInt(callTrace.gasUsed, 16)); // Prestate tracer - shows state before execution const prestateTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'prestateTracer' } ]); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671' # Call tracer trace = w3.provider.make_request('debug_traceTransaction', [ tx_hash, {'tracer': 'callTracer'} ]) print(f'Trace type: {trace["result"]["type"]}') print(f'Gas used: {int(trace["result"]["gasUsed"], 16)}') ``` ## Related Methods - [`debug_traceCall`](./debug_traceCall) - Trace without executing - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace entire block --- ## eth_accounts - Berachain RPC Method # eth_accounts Returns a list of addresses owned by the client on Berachain. > **Why Berachain?** Build on the Proof-of-Liquidity L1 with $3.2B+ TVL and innovative three-token economics with Proof-of-Liquidity consensus, three-token model (BERA/BGT/HONEY), $142M funding, and unified validator-DeFi incentive alignment. ## Important Note On public RPC endpoints like Dwellir, `eth_accounts` returns an empty array because the node does not hold any private keys. This method is primarily useful for: - Local development nodes (Ganache, Hardhat, Anvil) - Private nodes with managed accounts - Wallet provider connections (MetaMask injects accounts) ## When to Use This Method `eth_accounts` is relevant for DeFi protocol developers, liquidity providers, and teams building yield-optimized applications in specific scenarios: - **Development Testing** — Retrieve test accounts from local nodes - **Wallet Detection** — Check if a wallet provider has connected accounts - **Client Verification** — Confirm node account access capabilities ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `Array` | List of 20-byte account addresses owned by the client | **Return format**: Array of `0x` prefixed hexadecimal addresses (typically empty for public nodes) ## Request ```json { "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 } ``` ## Response ### Successful Response (Public Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [] } ``` ### Successful Response (Local Development Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [ "0x407d73d8a49eeb85d32cf465507dd71d507100c1", "0x85d32cf465507dd71d507100c1407d73d8a49eeb" ] } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_accounts', params: [], id: 1 }) }); const { result } = await response.json(); console.log('Accounts:', result); // Using ethers.js const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const accounts = await provider.listAccounts(); console.log('Accounts:', accounts); ``` ```python def get_accounts(): response = requests.post( 'https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_accounts', 'params': [], 'id': 1 } ) return response.json()['result'] accounts = get_accounts() print(f'Accounts: {accounts}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) print(f'Accounts: {w3.eth.accounts}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/rpc" ) func main() { client, err := rpc.Dial("https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } var accounts []string err = client.CallContext(context.Background(), &accounts, "eth_accounts") if err != nil { log.Fatal(err) } fmt.Printf("Accounts: %v\n", accounts) } ``` ## Common Use Cases ### 1. Development Environment Detection Check if running against a development node with test accounts: ```javascript async function isDevEnvironment(provider) { const accounts = await provider.listAccounts(); return accounts.length > 0; } const isDev = await isDevEnvironment(provider); if (isDev) { console.log('Development environment detected'); } ``` ### 2. Wallet Connection Check Verify wallet provider has connected accounts: ```javascript async function checkWalletConnection() { if (typeof window.ethereum === 'undefined') { return { connected: false, reason: 'No wallet detected' }; } const accounts = await window.ethereum.request({ method: 'eth_accounts' }); return { connected: accounts.length > 0, accounts: accounts }; } ``` ### 3. Fallback Account Selection Use first available account or request connection: ```javascript async function getActiveAccount() { // Check existing connections let accounts = await window.ethereum.request({ method: 'eth_accounts' }); // Request connection if no accounts if (accounts.length === 0) { accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); } return accounts[0] || null; } ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32601 | Method not found | Node may not support this method | | -32603 | Internal error | Retry with exponential backoff | ```javascript async function safeGetAccounts(provider) { try { const accounts = await provider.listAccounts(); return { success: true, accounts }; } catch (error) { if (error.code === -32601) { console.warn('eth_accounts not supported on this node'); return { success: false, accounts: [], reason: 'unsupported' }; } throw error; } } ``` ## Related Methods - [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102) — Request wallet connection (browser wallets) - [`eth_getBalance`](./eth_getBalance) — Get account balance - [`eth_getTransactionCount`](./eth_getTransactionCount) — Get account nonce --- ## eth_blockNumber - Berachain RPC Method # eth_blockNumber Returns the number of the most recent block on Berachain. > **Why Berachain?** Build on the Proof-of-Liquidity L1 with $3.2B+ TVL and innovative three-token economics with Proof-of-Liquidity consensus, three-token model (BERA/BGT/HONEY), $142M funding, and unified validator-DeFi incentive alignment. ## When to Use This Method `eth_blockNumber` is fundamental for DeFi protocol developers, liquidity providers, and teams building yield-optimized applications: - **Syncing Applications** — Keep your dApp in sync with the latest Berachain blockchain state - **Transaction Monitoring** — Verify confirmations by comparing block numbers - **Event Filtering** — Set the correct block range for querying logs on liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives - **Health Checks** — Monitor node connectivity and sync status ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `QUANTITY` | Hexadecimal string representing the current block number | **Return format**: `0x` prefixed hexadecimal (e.g., `0x5BAD55` = 6,008,149 in decimal) ## Request ```json { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } ``` ## Response ### Successful Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5BAD55" } ``` ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error" } } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }) }); const { result } = await response.json(); const blockNumber = parseInt(result, 16); console.log('Berachain block:', blockNumber); // Using ethers.js const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const blockNumber = await provider.getBlockNumber(); console.log('Berachain block:', blockNumber); ``` ```python def get_block_number(): response = requests.post( 'https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_blockNumber', 'params': [], 'id': 1 } ) result = response.json()['result'] return int(result, 16) block_number = get_block_number() print(f'Berachain block: {block_number}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) print(f'Berachain block: {w3.eth.block_number}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockNumber, err := client.BlockNumber(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Berachain block: %d\n", blockNumber) } ``` ## Common Use Cases ### 1. Block Confirmation Counter Monitor transaction confirmations on Berachain: ```javascript async function getConfirmations(provider, txHash) { const tx = await provider.getTransaction(txHash); if (!tx || !tx.blockNumber) return 0; const currentBlock = await provider.getBlockNumber(); return currentBlock - tx.blockNumber + 1; } // Wait for specific confirmations async function waitForConfirmations(provider, txHash, confirmations = 6) { let currentConfirmations = 0; while (currentConfirmations < confirmations) { currentConfirmations = await getConfirmations(provider, txHash); console.log(`Confirmations: ${currentConfirmations}/${confirmations}`); await new Promise(r => setTimeout(r, 2000)); } return true; } ``` ### 2. Event Log Filtering Query events from recent blocks on Berachain: ```javascript async function getRecentEvents(provider, contract, eventName, blockRange = 100) { const currentBlock = await provider.getBlockNumber(); const fromBlock = currentBlock - blockRange; const filter = contract.filters[eventName](); const events = await contract.queryFilter(filter, fromBlock, currentBlock); return events; } ``` ### 3. Node Health Monitoring Check if your Berachain node is synced: ```javascript async function checkNodeHealth(provider) { try { const blockNumber = await provider.getBlockNumber(); const block = await provider.getBlock(blockNumber); const now = Date.now() / 1000; const blockAge = now - block.timestamp; if (blockAge > 60) { console.warn(`Node may be behind. Last block was ${blockAge}s ago`); return false; } console.log(`Node healthy. Latest block: ${blockNumber}`); return true; } catch (error) { console.error('Node unreachable:', error); return false; } } ``` ## Performance Optimization ### Caching Strategy Cache block numbers to reduce API calls: ```javascript class BlockNumberCache { constructor(ttl = 2000) { this.cache = null; this.timestamp = 0; this.ttl = ttl; } async get(provider) { const now = Date.now(); if (this.cache && (now - this.timestamp) < this.ttl) { return this.cache; } this.cache = await provider.getBlockNumber(); this.timestamp = now; return this.cache; } invalidate() { this.cache = null; this.timestamp = 0; } } const blockCache = new BlockNumberCache(); ``` ### Batch Requests Combine with other calls for efficiency: ```javascript const batch = [ { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }, { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 }, { jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 } ]; const response = await fetch('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await response.json(); ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32603 | Internal error | Retry with exponential backoff | | -32005 | Rate limit exceeded | Implement rate limiting client-side | | -32000 | Execution reverted | Check node sync status | ```javascript async function safeGetBlockNumber(provider, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await provider.getBlockNumber(); } catch (error) { if (error.code === -32005) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } else if (i === maxRetries - 1) { throw error; } } } } ``` ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) — Get full block details by number - [`eth_getBlockByHash`](./eth_getBlockByHash) — Get block details by hash - [`eth_syncing`](./eth_syncing) — Check if node is still syncing --- ## eth_call - Berachain RPC Method # eth_call Executes a new message call immediately without creating a transaction on Berachain. Used for reading smart contract state. > **Why Berachain?** Build on the Proof-of-Liquidity L1 with $3.2B+ TVL and innovative three-token economics with Proof-of-Liquidity consensus, three-token model (BERA/BGT/HONEY), $142M funding, and unified validator-DeFi incentive alignment. ## Use Cases The `eth_call` method is essential for: - **Reading contract state** - Query view/pure functions - **Simulating transactions** - Test execution without gas costs - **DeFi integrations** - Check prices, balances, allowances for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives - **Complex queries** - Execute multi-step contract logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | 20-byte address executing the call | | `to` | `DATA` | Yes | 20-byte contract address | | `gas` | `QUANTITY` | No | Gas limit for the call | | `gasPrice` | `QUANTITY` | No | Gas price in wei | | `value` | `QUANTITY` | No | Value to send in wei | | `data` | `DATA` | Yes | Encoded function call data | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_call", "params": [ { "to": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "data": "0x70a082310000000000000000000000007507c1dc16935B82698e4C63f2746A2fCf994dF8" }, "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | The return value of the executed contract function | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000" } ``` ## Code Examples ```bash # Call ERC20 balanceOf function curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{ "to": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "data": "0x70a082310000000000000000000000007507c1dc16935B82698e4C63f2746A2fCf994dF8" }, "latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); // ERC20 ABI for common functions const ERC20_ABI = [ "function balanceOf(address owner) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function totalSupply() view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)" ]; // Read ERC20 token balance async function getTokenBalance(tokenAddress, walletAddress) { const contract = new Contract(tokenAddress, ERC20_ABI, provider); const balance = await contract.balanceOf(walletAddress); const decimals = await contract.decimals(); const symbol = await contract.symbol(); return { raw: balance.toString(), formatted: (Number(balance) / Math.pow(10, decimals)).toFixed(4), symbol: symbol }; } // Direct eth_call async function directCall(to, data) { const result = await provider.call({ to, data }); return result; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) def get_erc20_balance(token_address, wallet_address): # balanceOf(address) selector function_signature = "balanceOf(address)" function_selector = w3.keccak(text=function_signature)[:4].hex() # Encode address parameter encoded_address = wallet_address[2:].lower().zfill(64) data = function_selector + encoded_address # Make the call result = w3.eth.call({ 'to': token_address, 'data': data }) return int(result.hex(), 16) balance = get_erc20_balance( '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8', '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8' ) print(f'Balance: {balance}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0x7507c1dc16935B82698e4C63f2746A2fCf994dF8") data := common.FromHex("0x70a082310000000000000000000000007507c1dc16935B82698e4C63f2746A2fCf994dF8") msg := ethereum.CallMsg{ To: &contractAddress, Data: data, } result, err := client.CallContract(context.Background(), msg, nil) if err != nil { log.Fatal(err) } fmt.Printf("Result: 0x%x\n", result) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Contract function reverted | | -32602 | Invalid parameters | Invalid data encoding | | -32015 | VM execution error | Contract logic error | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas for transaction - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send actual transaction --- ## eth_chainId - Berachain RPC Method # eth_chainId Returns the chain ID used for transaction signing on Berachain. > **Why Berachain?** Build on the Proof-of-Liquidity L1 with $3.2B+ TVL and innovative three-token economics with Proof-of-Liquidity consensus, three-token model (BERA/BGT/HONEY), $142M funding, and unified validator-DeFi incentive alignment. ## Use Cases The `eth_chainId` method is essential for: - **Transaction signing** - Ensure transactions are signed for the correct network - **Network verification** - Confirm connection to the expected chain - **Multi-chain apps** - Handle different networks programmatically - **Wallet integration** - Validate network before transactions ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Chain ID in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1" } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const network = await provider.getNetwork(); console.log('Chain ID:', network.chainId); // Verify network before transaction async function verifyNetwork(expectedChainId) { const network = await provider.getNetwork(); if (network.chainId !== BigInt(expectedChainId)) { throw new Error(`Wrong network. Expected ${expectedChainId}, got ${network.chainId}`); } return true; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) chain_id = w3.eth.chain_id print(f'Chain ID: {chain_id}') # Verify network def verify_network(expected_chain_id): chain_id = w3.eth.chain_id if chain_id != expected_chain_id: raise ValueError(f'Wrong network. Expected {expected_chain_id}, got {chain_id}') return True ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } chainID, err := client.ChainID(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Chain ID: %d\n", chainID) } ``` ## Related Methods - [`net_version`](./net_version) - Get network version - [`eth_syncing`](./eth_syncing) - Check sync status --- ## eth_coinbase - Get coinbase address(Berachain) # eth_coinbase Get coinbase address on the Berachain network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_coinbase](https://ethereum.org/developers/docs/apis/json-rpc/#eth_coinbase) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_coinbase", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_coinbase', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Berachain documentation](/docs/berachain).* --- ## eth_estimateGas - Berachain RPC Method # eth_estimateGas Estimates the gas necessary to execute a transaction on Berachain. > **Why Berachain?** Build on the Proof-of-Liquidity L1 with $3.2B+ TVL and innovative three-token economics with Proof-of-Liquidity consensus, three-token model (BERA/BGT/HONEY), $142M funding, and unified validator-DeFi incentive alignment. ## Use Cases The `eth_estimateGas` method is essential for: - **Transaction preparation** - Set appropriate gas limits - **Cost estimation** - Calculate transaction costs before sending - **Error detection** - Identify reverts before spending gas - **DeFi operations** - Estimate costs for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | Sender address | | `to` | `DATA` | No | Recipient address | | `gas` | `QUANTITY` | No | Gas limit | | `gasPrice` | `QUANTITY` | No | Gas price | | `value` | `QUANTITY` | No | Value in wei | | `data` | `DATA` | No | Transaction data | ## Request ```json { "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "to": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "value": "0x1" }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Estimated gas amount in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5208" } ``` **Note**: `0x5208` = 21000 gas (standard ETH transfer) ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "to": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "value": "0x1" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); // Estimate simple transfer async function estimateTransfer(to, value) { const gasEstimate = await provider.estimateGas({ to: to, value: parseEther(value) }); console.log('Estimated gas:', gasEstimate.toString()); return gasEstimate; } // Estimate contract call async function estimateContractCall(contract, method, args) { const gasEstimate = await contract[method].estimateGas(...args); console.log('Estimated gas:', gasEstimate.toString()); // Add 20% buffer for safety return gasEstimate * 120n / 100n; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) def estimate_transfer(to, value_in_ether): gas_estimate = w3.eth.estimate_gas({ 'to': to, 'value': w3.to_wei(value_in_ether, 'ether') }) print(f'Estimated gas: {gas_estimate}') return gas_estimate def estimate_contract_call(contract, method, args): func = getattr(contract.functions, method) gas_estimate = func(*args).estimate_gas() # Add 20% buffer return int(gas_estimate * 1.2) # Estimate simple transfer gas = estimate_transfer('0x7507c1dc16935B82698e4C63f2746A2fCf994dF8', 0.1) ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } toAddress := common.HexToAddress("0x7507c1dc16935B82698e4C63f2746A2fCf994dF8") msg := ethereum.CallMsg{ To: &toAddress, Value: big.NewInt(1000000000000000000), } gasLimit, err := client.EstimateGas(context.Background(), msg) if err != nil { log.Fatal(err) } fmt.Printf("Estimated gas: %d\n", gasLimit) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Transaction would fail | | -32602 | Invalid params | Invalid transaction parameters | **Tip**: If estimation fails, the transaction would likely revert if sent. ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_feeHistory - Berachain RPC Method # eth_feeHistory Returns historical gas information on Berachain for fee estimation. ## Use Cases - **Fee prediction** - Estimate future gas prices based on history - **Gas analytics** - Analyze fee trends over time - **Optimal timing** - Find best times for transactions on liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockCount` | `QUANTITY` | Yes | Number of blocks in the range | | `newestBlock` | `QUANTITY\|TAG` | Yes | Highest block of the range | | `rewardPercentiles` | `Array` | Yes | Percentiles to sample for priority fees | ## Request ```json { "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const feeHistory = await provider.send('eth_feeHistory', ['0xa', 'latest', [25, 50, 75]]); console.log('Base fees:', feeHistory.baseFeePerGas.map(f => formatUnits(f, 'gwei'))); console.log('Reward (25th percentile):', feeHistory.reward.map(r => formatUnits(r[0], 'gwei'))); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) fee_history = w3.eth.fee_history(10, 'latest', [25, 50, 75]) print(f'Base fees: {[w3.from_wei(f, "gwei") for f in fee_history["baseFeePerGas"]]}') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee --- ## eth_gasPrice - Berachain RPC Method # eth_gasPrice Returns the current gas price on Berachain in wei. > **Why Berachain?** Build on the Proof-of-Liquidity L1 with $3.2B+ TVL and innovative three-token economics with Proof-of-Liquidity consensus, three-token model (BERA/BGT/HONEY), $142M funding, and unified validator-DeFi incentive alignment. ## Use Cases The `eth_gasPrice` method is essential for: - **Transaction pricing** - Set appropriate gas prices - **Cost estimation** - Calculate transaction costs before sending - **Gas monitoring** - Track network congestion - **DeFi operations** - Optimize costs for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Current gas price in wei (hexadecimal) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x3b9aca00" } ``` **Note**: `0x3b9aca00` = 1 Gwei (1,000,000,000 wei) ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); const gasPrice = feeData.gasPrice; console.log('Gas Price:', formatUnits(gasPrice, 'gwei'), 'Gwei'); // Calculate transaction cost async function estimateTransactionCost(gasLimit) { const feeData = await provider.getFeeData(); const cost = feeData.gasPrice * BigInt(gasLimit); return formatUnits(cost, 'ether'); } const cost = await estimateTransactionCost(21000); console.log('Transfer cost:', cost, 'ETH'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) gas_price = w3.eth.gas_price print(f'Gas Price: {w3.from_wei(gas_price, "gwei")} Gwei') # Calculate transaction cost def estimate_transaction_cost(gas_limit): gas_price = w3.eth.gas_price cost = gas_price * gas_limit return w3.from_wei(cost, 'ether') cost = estimate_transaction_cost(21000) print(f'Transfer cost: {cost} ETH') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } gasPrice, err := client.SuggestGasPrice(context.Background()) if err != nil { log.Fatal(err) } // Convert to Gwei gwei := new(big.Float).Quo( new(big.Float).SetInt(gasPrice), big.NewFloat(1e9), ) fmt.Printf("Gas Price: %f Gwei\n", gwei) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32603 | Internal error | Node error | ## Related Methods - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee (EIP-1559) - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas needed --- ## eth_getBalance - Berachain RPC Method # eth_getBalance Returns the balance of a given address on Berachain. > **Why Berachain?** Build on the Proof-of-Liquidity L1 with $3.2B+ TVL and innovative three-token economics with Proof-of-Liquidity consensus, three-token model (BERA/BGT/HONEY), $142M funding, and unified validator-DeFi incentive alignment. ## Use Cases The `eth_getBalance` method is essential for: - **Wallet applications** - Display user balances - **Transaction validation** - Check if account has sufficient funds - **DeFi applications** - Monitor collateral and liquidity for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives - **Account monitoring** - Track balance changes over time ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address to check balance for | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Integer of the current balance in wei (hexadecimal) | **Note**: 1 native token = 10^18 wei. Convert using `balance / 10^18`. ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1a055690d9db80000" } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8'; const balanceWei = await provider.getBalance(address); const balance = formatEther(balanceWei); console.log(`Balance: ${balance}`); // Get balance at specific block const historicalBalance = await provider.getBalance(address, 1000000); console.log(`Historical balance: ${formatEther(historicalBalance)}`); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8' balance_wei = w3.eth.get_balance(address) balance = w3.from_wei(balance_wei, 'ether') print(f'Balance: {balance}') # Get balance at specific block historical_balance = w3.eth.get_balance(address, block_identifier=1000000) print(f'Historical balance: {w3.from_wei(historical_balance, "ether")}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0x7507c1dc16935B82698e4C63f2746A2fCf994dF8") balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } // Convert to ether fbalance := new(big.Float).SetInt(balance) ethValue := new(big.Float).Quo(fbalance, big.NewFloat(1e18)) fmt.Printf("Balance: %f\n", ethValue) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid address format or block parameter | | -32000 | Execution error | Node execution error | ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_getTransactionCount`](./eth_getTransactionCount) - Get account nonce --- ## eth_getBlockByHash - Berachain RPC Method # eth_getBlockByHash Returns information about a block by hash on Berachain. > **Why Berachain?** Build on the Proof-of-Liquidity L1 with $3.2B+ TVL and innovative three-token economics with Proof-of-Liquidity consensus, three-token model (BERA/BGT/HONEY), $142M funding, and unified validator-DeFi incentive alignment. ## Use Cases The `eth_getBlockByHash` method is essential for: - **Block verification** - Verify block data using its unique hash - **Chain reorganization handling** - Track blocks during reorgs - **Cross-chain bridges** - Verify block finality for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives - **Deterministic queries** - Get consistent block data regardless of chain state ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0x969b796c2c98668e687636319dba231c7f3f77e1c89dab82fba3d17f8f0f9e55", false ], "id": 1 } ``` ## Returns Returns the same block object as `eth_getBlockByNumber`, or `null` if no block is found. | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used | | `transactions` | `Array` | Transaction objects or hashes | ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0x969b796c2c98668e687636319dba231c7f3f77e1c89dab82fba3d17f8f0f9e55", false ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0x969b796c2c98668e687636319dba231c7f3f77e1c89dab82fba3d17f8f0f9e55'; const block = await provider.getBlock(blockHash); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) block_hash = '0x969b796c2c98668e687636319dba231c7f3f77e1c89dab82fba3d17f8f0f9e55' block = w3.eth.get_block(block_hash) print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockHash := common.HexToHash("0x969b796c2c98668e687636319dba231c7f3f77e1c89dab82fba3d17f8f0f9e55") block, err := client.BlockByHash(context.Background(), blockHash) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block hash format | | -32000 | Block not found | Block with this hash does not exist | ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) - Get block by number - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number --- ## eth_getBlockByNumber - Berachain RPC Method # eth_getBlockByNumber Returns information about a block by block number on Berachain. > **Why Berachain?** Build on the Proof-of-Liquidity L1 with $3.2B+ TVL and innovative three-token economics with Proof-of-Liquidity consensus, three-token model (BERA/BGT/HONEY), $142M funding, and unified validator-DeFi incentive alignment. ## Use Cases The `eth_getBlockByNumber` method is essential for: - **Block explorers** - Display complete block information - **Transaction indexers** - Process all transactions in a block - **Analytics platforms** - Analyze blockchain data for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives - **Timestamp verification** - Get block timestamps for time-based logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used by all transactions | | `gasLimit` | `QUANTITY` | Maximum gas allowed in block | | `transactions` | `Array` | Array of transaction objects or hashes | | `baseFeePerGas` | `QUANTITY` | Base fee per gas (EIP-1559) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": { "number": "0x5BAD55", "hash": "0x969b796c2c98668e687636319dba231c7f3f77e1c89dab82fba3d17f8f0f9e55", "parentHash": "0x...", "timestamp": "0x64d8f6d0", "gasUsed": "0x1234", "gasLimit": "0x1c9c380", "transactions": [], "baseFeePerGas": "0x5f5e100" } } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); // Get latest block const block = await provider.getBlock('latest'); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); console.log('Transactions:', block.transactions.length); // Get block with full transactions const blockWithTxs = await provider.getBlock('latest', true); for (const tx of blockWithTxs.prefetchedTransactions) { console.log('Transaction:', tx.hash); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) # Get latest block block = w3.eth.get_block('latest') print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') print(f'Transactions: {len(block.transactions)}') # Get block with full transactions block_full = w3.eth.get_block('latest', full_transactions=True) for tx in block_full.transactions: print(f'Transaction: {tx.hash.hex()}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } // Get latest block block, err := client.BlockByNumber(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) fmt.Printf("Timestamp: %d\n", block.Time()) fmt.Printf("Transactions: %d\n", len(block.Transactions())) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block number or parameter format | | -32000 | Block not found | Block does not exist | ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number - [`eth_getBlockByHash`](./eth_getBlockByHash) - Get block by hash - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_getCode - Berachain RPC Method # eth_getCode Returns the bytecode at a given address on Berachain. > **Why Berachain?** Build on the Proof-of-Liquidity L1 with $3.2B+ TVL and innovative three-token economics with Proof-of-Liquidity consensus, three-token model (BERA/BGT/HONEY), $142M funding, and unified validator-DeFi incentive alignment. ## Use Cases The `eth_getCode` method is essential for: - **Contract verification** - Check if address is a contract - **Security analysis** - Verify deployed bytecode matches expected - **DeFi integrations** - Validate contracts before interactions - **Protocol analysis** - Analyze contract deployments for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Contract bytecode or `0x` if EOA | ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8'; const code = await provider.getCode(address); if (code === '0x') { console.log('Address is an EOA (externally owned account)'); } else { console.log('Address is a contract'); console.log('Bytecode length:', code.length); } // Check if address is a contract async function isContract(address) { const code = await provider.getCode(address); return code !== '0x'; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8' code = w3.eth.get_code(address) if code == b'': print('Address is an EOA') else: print('Address is a contract') print(f'Bytecode length: {len(code.hex())}') # Check if address is a contract def is_contract(address): code = w3.eth.get_code(address) return code != b'' ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0x7507c1dc16935B82698e4C63f2746A2fCf994dF8") code, err := client.CodeAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } if len(code) == 0 { fmt.Println("Address is an EOA") } else { fmt.Printf("Contract bytecode length: %d\n", len(code)) } } ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_getStorageAt`](./eth_getStorageAt) - Get contract storage --- ## eth_getFilterChanges - Berachain RPC Method # eth_getFilterChanges Polling method for a filter on Berachain, returns an array of logs since last poll. ## Use Cases - **Event streaming** - Get new events incrementally - **Real-time monitoring** - Track contract activity for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives - **Efficient indexing** - Process only new events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); // Poll loop async function pollFilter(filterId, interval = 2000) { while (true) { const changes = await provider.send('eth_getFilterChanges', [filterId]); if (changes.length > 0) { console.log('New events:', changes); } await new Promise(r => setTimeout(r, interval)); } } ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter --- ## eth_getFilterLogs - Berachain RPC Method # eth_getFilterLogs Returns an array of all logs matching filter with given ID on Berachain. ## Use Cases - **Historical queries** - Get all matching logs for a filter - **Full event history** - Retrieve complete event data for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const logs = await provider.send('eth_getFilterLogs', [filterId]); console.log('All matching logs:', logs.length); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_getLogs - Berachain RPC Method # eth_getLogs Returns an array of all logs matching a given filter object on Berachain. > **Why Berachain?** Build on the Proof-of-Liquidity L1 with $3.2B+ TVL and innovative three-token economics with Proof-of-Liquidity consensus, three-token model (BERA/BGT/HONEY), $142M funding, and unified validator-DeFi incentive alignment. ## Use Cases The `eth_getLogs` method is essential for: - **Event indexing** - Track contract events for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives - **Token transfers** - Monitor ERC20/ERC721 transfers - **DeFi analytics** - Track swaps, liquidity events, and more - **Notification systems** - Alert on specific on-chain events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block (default: `"latest"`) | | `toBlock` | `QUANTITY\|TAG` | No | Ending block (default: `"latest"`) | | `address` | `DATA\|Array` | No | Contract address(es) to filter | | `topics` | `Array` | No | Array of topic filters | | `blockHash` | `DATA` | No | Filter single block by hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns Array of log objects: | Field | Type | Description | |-------|------|-------------| | `address` | `DATA` | Contract that emitted the log | | `topics` | `Array` | Array of indexed topics | | `data` | `DATA` | Non-indexed log data | | `blockNumber` | `QUANTITY` | Block number | | `transactionHash` | `DATA` | Transaction hash | | `logIndex` | `QUANTITY` | Log index in block | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": [{ "address": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."], "data": "0x...", "blockNumber": "0x5BAD55", "transactionHash": "0x...", "logIndex": "0x0" }] } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); // Get Transfer events const TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'; async function getTransferEvents(tokenAddress, fromBlock, toBlock) { const logs = await provider.getLogs({ address: tokenAddress, topics: [TRANSFER_TOPIC], fromBlock: fromBlock, toBlock: toBlock }); return logs.map(log => ({ from: '0x' + log.topics[1].slice(26), to: '0x' + log.topics[2].slice(26), blockNumber: log.blockNumber, transactionHash: log.transactionHash })); } const events = await getTransferEvents( '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8', 'latest', 'latest' ); console.log('Transfer events:', events); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' def get_transfer_events(token_address, from_block, to_block): logs = w3.eth.get_logs({ 'address': token_address, 'topics': [TRANSFER_TOPIC], 'fromBlock': from_block, 'toBlock': to_block }) events = [] for log in logs: events.append({ 'from': '0x' + log['topics'][1].hex()[26:], 'to': '0x' + log['topics'][2].hex()[26:], 'block': log['blockNumber'], 'tx': log['transactionHash'].hex() }) return events events = get_transfer_events( '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8', 'latest', 'latest' ) print(f'Found {len(events)} transfer events') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0x7507c1dc16935B82698e4C63f2746A2fCf994dF8") transferTopic := common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef") query := ethereum.FilterQuery{ FromBlock: big.NewInt(0), ToBlock: nil, Addresses: []common.Address{contractAddress}, Topics: [][]common.Hash, } logs, err := client.FilterLogs(context.Background(), query) if err != nil { log.Fatal(err) } fmt.Printf("Found %d events\n", len(logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32005 | Query returned more than 10000 results | Reduce block range | | -32602 | Invalid params | Invalid filter parameters | ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create a filter for logs - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for new logs --- ## eth_getStorageAt - Berachain RPC Method # eth_getStorageAt Returns the value from a storage position at a given address on Berachain. ## Use Cases - **Contract analysis** - Read raw storage values - **State verification** - Verify contract state - **Security auditing** - Analyze storage layout for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives - **Protocol monitoring** - Track state changes ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte contract address | | `position` | `QUANTITY` | Yes | Storage slot position | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "0x0", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "0x0", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8'; const slot = 0; const storage = await provider.getStorage(address, slot); console.log('Storage at slot 0:', storage); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8' storage = w3.eth.get_storage_at(address, 0) print(f'Storage at slot 0: {storage.hex()}') ``` ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_call`](./eth_call) - Call contract functions --- ## eth_getTransactionByHash - Berachain RPC Method # eth_getTransactionByHash Returns the information about a transaction by transaction hash on Berachain. > **Why Berachain?** Build on the Proof-of-Liquidity L1 with $3.2B+ TVL and innovative three-token economics with Proof-of-Liquidity consensus, three-token model (BERA/BGT/HONEY), $142M funding, and unified validator-DeFi incentive alignment. ## Use Cases The `eth_getTransactionByHash` method is essential for: - **Transaction tracking** - Get details of pending or confirmed transactions - **Payment verification** - Verify transaction parameters - **Debugging** - Analyze transaction data for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives - **Block explorers** - Display transaction information ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `hash` | `DATA` | Transaction hash | | `from` | `DATA` | Sender address | | `to` | `DATA` | Recipient address | | `value` | `QUANTITY` | Value in wei | | `gas` | `QUANTITY` | Gas provided | | `gasPrice` | `QUANTITY` | Gas price in wei | | `input` | `DATA` | Transaction input data | | `nonce` | `QUANTITY` | Sender's nonce | | `blockHash` | `DATA` | Block hash (null if pending) | | `blockNumber` | `QUANTITY` | Block number (null if pending) | ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const txHash = '0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671'; const tx = await provider.getTransaction(txHash); if (tx) { console.log('From:', tx.from); console.log('To:', tx.to); console.log('Value:', formatEther(tx.value)); console.log('Block:', tx.blockNumber); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671' tx = w3.eth.get_transaction(tx_hash) if tx: print(f'From: {tx["from"]}') print(f'To: {tx["to"]}') print(f'Value: {w3.from_wei(tx["value"], "ether")}') print(f'Block: {tx["blockNumber"]}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671") tx, isPending, err := client.TransactionByHash(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Pending: %v\n", isPending) fmt.Printf("Value: %s\n", tx.Value().String()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash format | ## Related Methods - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction receipt - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionCount - Berachain RPC Method # eth_getTransactionCount Returns the number of transactions sent from an address on Berachain (the nonce). ## Use Cases - **Transaction building** - Get correct nonce for new transactions - **Account analysis** - Count total outgoing transactions - **Nonce management** - Handle pending transaction queues - **Wallet operations** - Prepare transactions for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag (`pending` for next nonce) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8'; const nonce = await provider.getTransactionCount(address); console.log('Nonce:', nonce); // Get pending nonce for new transaction const pendingNonce = await provider.getTransactionCount(address, 'pending'); console.log('Next nonce:', pendingNonce); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8' nonce = w3.eth.get_transaction_count(address) print(f'Nonce: {nonce}') # Get pending nonce pending_nonce = w3.eth.get_transaction_count(address, 'pending') print(f'Next nonce: {pending_nonce}') ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionReceipt - Berachain RPC Method # eth_getTransactionReceipt Returns the receipt of a transaction by transaction hash on Berachain. Receipt is only available for mined transactions. > **Why Berachain?** Build on the Proof-of-Liquidity L1 with $3.2B+ TVL and innovative three-token economics with Proof-of-Liquidity consensus, three-token model (BERA/BGT/HONEY), $142M funding, and unified validator-DeFi incentive alignment. ## Use Cases The `eth_getTransactionReceipt` method is essential for: - **Transaction confirmation** - Verify transaction was mined successfully - **Gas analysis** - Check actual gas used vs estimated - **Event parsing** - Read emitted events from logs - **Status verification** - Confirm success/failure for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `status` | `QUANTITY` | `1` (success) or `0` (failure) | | `transactionHash` | `DATA` | Transaction hash | | `blockHash` | `DATA` | Block hash | | `blockNumber` | `QUANTITY` | Block number | | `gasUsed` | `QUANTITY` | Gas used by this transaction | | `cumulativeGasUsed` | `QUANTITY` | Total gas used in block up to this tx | | `logs` | `Array` | Array of log objects | | `contractAddress` | `DATA` | Created contract address (if deployment) | ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const txHash = '0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671'; const receipt = await provider.getTransactionReceipt(txHash); if (receipt) { console.log('Status:', receipt.status === 1 ? 'Success' : 'Failed'); console.log('Gas Used:', receipt.gasUsed.toString()); console.log('Block:', receipt.blockNumber); console.log('Logs:', receipt.logs.length); // Parse specific events for (const log of receipt.logs) { console.log('Event from:', log.address); } } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671' receipt = w3.eth.get_transaction_receipt(tx_hash) if receipt: status = 'Success' if receipt['status'] == 1 else 'Failed' print(f'Status: {status}') print(f'Gas Used: {receipt["gasUsed"]}') print(f'Block: {receipt["blockNumber"]}') print(f'Logs: {len(receipt["logs"])}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671") receipt, err := client.TransactionReceipt(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Status: %d\n", receipt.Status) fmt.Printf("Gas Used: %d\n", receipt.GasUsed) fmt.Printf("Logs: %d\n", len(receipt.Logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash | **Note**: Returns `null` if transaction is not yet mined. ## Related Methods - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details - [`eth_getLogs`](./eth_getLogs) - Query logs by filter --- ## eth_hashrate - Get node hashrate(Berachain) # eth_hashrate Get node hashrate on the Berachain network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_hashrate](https://ethereum.org/developers/docs/apis/json-rpc/#eth_hashrate) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_hashrate", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_hashrate', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Berachain documentation](/docs/berachain).* --- ## eth_maxPriorityFeePerGas - Berachain RPC Method # eth_maxPriorityFeePerGas Returns the current recommended priority fee per gas on Berachain for EIP-1559 transactions. ## Use Cases - **EIP-1559 transactions** - Set appropriate priority fees - **Transaction acceleration** - Calculate tips for faster inclusion - **Gas optimization** - Balance speed vs cost for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); console.log('Max Priority Fee:', formatUnits(feeData.maxPriorityFeePerGas, 'gwei'), 'Gwei'); console.log('Max Fee Per Gas:', formatUnits(feeData.maxFeePerGas, 'gwei'), 'Gwei'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) priority_fee = w3.eth.max_priority_fee print(f'Max Priority Fee: {w3.from_wei(priority_fee, "gwei")} Gwei') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get legacy gas price - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data --- ## eth_mining - Check if node is mining(Berachain) # eth_mining Check if node is mining on the Berachain network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_mining](https://ethereum.org/developers/docs/apis/json-rpc/#eth_mining) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_mining', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Berachain documentation](/docs/berachain).* --- ## eth_newBlockFilter - Berachain RPC Method # eth_newBlockFilter Creates a filter on Berachain to notify when a new block arrives. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newBlockFilter', []); // Poll for new blocks const newBlocks = await provider.send('eth_getFilterChanges', [filterId]); console.log('New block hashes:', newBlocks); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_blockNumber`](./eth_blockNumber) - Get current block --- ## eth_newFilter - Berachain RPC Method # eth_newFilter Creates a filter object on Berachain to notify when state changes (logs). ## Use Cases - **Event monitoring** - Subscribe to contract events - **Real-time updates** - Track events for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives - **Indexing** - Build event indexes incrementally ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block | | `toBlock` | `QUANTITY\|TAG` | No | Ending block | | `address` | `DATA\|Array` | No | Contract address(es) | | `topics` | `Array` | No | Topic filters | ## Request ```json { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); // Create filter const filterId = await provider.send('eth_newFilter', [{ fromBlock: 'latest', address: '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8', topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'] }]); // Poll for changes const changes = await provider.send('eth_getFilterChanges', [filterId]); console.log('New events:', changes); // Cleanup await provider.send('eth_uninstallFilter', [filterId]); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for changes - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_newPendingTransactionFilter - Berachain RPC Method # eth_newPendingTransactionFilter Creates a filter on Berachain to notify when new pending transactions arrive. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newPendingTransactionFilter', []); // Poll for pending transactions const pendingTxs = await provider.send('eth_getFilterChanges', [filterId]); console.log('Pending transaction hashes:', pendingTxs); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_protocolVersion - Get protocol version(Berachain) # eth_protocolVersion Get protocol version on the Berachain network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_protocolVersion](https://ethereum.org/developers/docs/apis/json-rpc/#eth_protocolversion) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_protocolVersion", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_protocolVersion', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Berachain documentation](/docs/berachain).* --- ## eth_sendRawTransaction - Berachain RPC Method # eth_sendRawTransaction Submits a pre-signed transaction for broadcast to Berachain. > **Why Berachain?** Build on the Proof-of-Liquidity L1 with $3.2B+ TVL and innovative three-token economics with Proof-of-Liquidity consensus, three-token model (BERA/BGT/HONEY), $142M funding, and unified validator-DeFi incentive alignment. ## Use Cases The `eth_sendRawTransaction` method is essential for: - **Broadcasting transactions** - Submit signed transactions to the network - **Wallet operations** - Send native tokens and interact with contracts - **DeFi operations** - Execute swaps, provide liquidity for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives - **Batch operations** - Submit multiple transactions efficiently ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `signedTransactionData` | `DATA` | Yes | The signed transaction data (RLP encoded) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | 32-byte transaction hash | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c808504a817c80082520894..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const wallet = new Wallet('YOUR_PRIVATE_KEY', provider); // Send native tokens async function sendTransaction(to, value) { const tx = await wallet.sendTransaction({ to: to, value: parseEther(value) }); console.log('Transaction hash:', tx.hash); // Wait for confirmation const receipt = await tx.wait(); console.log('Confirmed in block:', receipt.blockNumber); return receipt; } // Send to contract async function sendContractTransaction(contract, method, args, value = '0') { const tx = await contract[method](...args, { value: parseEther(value) }); return await tx.wait(); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) def send_transaction(private_key, to, value_in_ether): account = w3.eth.account.from_key(private_key) # Build transaction tx = { 'nonce': w3.eth.get_transaction_count(account.address), 'to': to, 'value': w3.to_wei(value_in_ether, 'ether'), 'gas': 21000, 'gasPrice': w3.eth.gas_price, 'chainId': w3.eth.chain_id } # Sign transaction signed_tx = account.sign_transaction(tx) # Send transaction tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) print(f'Transaction hash: {tx_hash.hex()}') # Wait for confirmation receipt = w3.eth.wait_for_transaction_receipt(tx_hash) print(f'Confirmed in block: {receipt["blockNumber"]}') return receipt ``` ```go package main "context" "crypto/ecdsa" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY") if err != nil { log.Fatal(err) } publicKey := privateKey.Public() publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey) fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA) nonce, _ := client.PendingNonceAt(context.Background(), fromAddress) value := big.NewInt(1000000000000000000) gasLimit := uint64(21000) gasPrice, _ := client.SuggestGasPrice(context.Background()) toAddress := common.HexToAddress("0x7507c1dc16935B82698e4C63f2746A2fCf994dF8") tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil) chainID, _ := client.NetworkID(context.Background()) signedTx, _ := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey) err = client.SendTransaction(context.Background(), signedTx) if err != nil { log.Fatal(err) } fmt.Printf("Transaction hash: %s\n", signedTx.Hash().Hex()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Nonce too low | Transaction nonce already used | | -32000 | Insufficient funds | Account has insufficient balance | | -32000 | Gas too low | Gas limit insufficient | | -32000 | Replacement underpriced | Gas price too low for replacement | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas required - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction result --- ## eth_sendTransaction - Send transaction (wa... # eth_sendTransaction > **Important**: Dwellir's shared Berachain endpoints do not manage user private keys. JSON-RPC nodes cannot unlock your account, so `eth_sendTransaction` calls will fail. Sign transactions client-side and broadcast them with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Why this method is disabled on shared nodes - [`eth_sendTransaction` requires the node to hold and unlock the `from` account's private key](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction). - Managed infrastructure providers disable it for security reasons rather than storing customer keys on shared servers (for example, [Infura explicitly blocks the method on shared endpoints](https://docs.infura.io/api/networks/ethereum/json-rpc-methods/eth_sendtransaction)). ## Recommended workflow 1. Build the raw transaction locally with your wallet or SDK. 2. Sign the payload client-side (hardware wallet, custodial service, or library). 3. Submit the signed hex string with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Example response from the shared endpoint ```bash curl -s -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"0x0000000000000000000000000000000000000000"}],"id":1}' ``` ```json {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"unknown account"}} ``` Need help? Contact our [support team](mailto:support@dwellir.com) or use the dedicated [`eth_sendRawTransaction`](./eth_sendRawTransaction) guide. --- ## eth_signTransaction - Sign transaction (ra... # eth_signTransaction Signs a transaction using an unlocked account on the node. **Important**: Most RPC providers don't support this method for security reasons, as it requires private keys to be stored on the server. ## Security Considerations - This method requires an unlocked account on the node - Private keys must be available to the RPC server - Most production RPC providers disable this method - Use client-side signing libraries instead for better security ## Parameters 1. `Object` - The transaction object: - `from`: `DATA`, 20 Bytes - The address the transaction is sent from - `to`: `DATA`, 20 Bytes - (optional) The address the transaction is directed to - `gas`: `QUANTITY` - (optional) Integer of the gas provided for the transaction execution - `gasPrice`: `QUANTITY` - (optional) Integer of the gasPrice used for each paid gas - `value`: `QUANTITY` - (optional) Integer of the value sent with this transaction - `data`: `DATA` - (optional) The compiled code of a contract OR the hash of the invoked method signature and encoded parameters ## Returns `DATA` - The signed transaction data, ready for transmission via `eth_sendRawTransaction`. ## Implementation Example ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_signTransaction", "params": [{ "from": "0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a" }], "id": 1 }' ``` ```javascript const response = await fetch('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_signTransaction', params: [{ from: '0x9b2055d370f73ec7d8a03e965129118dc8f5bf83', to: '0xd46e8dd67c5d32be8058bb8eb970870f07244567', gas: '0x76c0', gasPrice: '0x9184e72a000', value: '0x9184e72a' }], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0xf86c808504a817c8008276c094d46e8dd67c5d32be8058bb8eb970870f072445675849184e72a8001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804" } ``` **Note**: This method is typically not available on hosted RPC providers for security reasons. The response shows a signed transaction ready for broadcast. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Berachain documentation](/docs/berachain).* --- ## eth_syncing - Berachain RPC Method # eth_syncing Returns syncing status of Berachain node. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 } ``` ## Returns Returns `false` if not syncing, or an object with sync status. ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const syncing = await provider.send('eth_syncing', []); if (syncing === false) { console.log('Node is fully synced'); } else { console.log('Syncing:', syncing); } ``` ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get current block - [`net_peerCount`](./net_peerCount) - Get peer count --- ## eth_uninstallFilter - Berachain RPC Method # eth_uninstallFilter Uninstalls a filter on Berachain. Should be called when no longer needed. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID to uninstall | ## Request ```json { "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if filter was found and uninstalled | ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const success = await provider.send('eth_uninstallFilter', [filterId]); console.log('Filter removed:', success); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter --- ## Berachain RPC with Dwellir # Berachain - Build on the Proof‑of‑Liquidity EVM Layer 1 ## Why Build on Berachain? ### 🚀 High‑Performance EVM - Built on a modular EVM (Polaris) for efficient execution and developer‑friendly precompiles - Fast finality via CometBFT (BFT consensus), ideal for low‑latency reads and responsive UX - EVM compatibility out of the box — keep using Solidity, Hardhat, Foundry, viem, and ethers.js ### 💧 Proof‑of‑Liquidity Alignment - Separation of gas and governance unlocks healthier incentive design - Liquidity provision powers governance emissions (BGT) to align validators, protocols, and users - Ecosystem‑driven rewards encourage deep liquidity for DeFi building blocks ### 🔗 Interoperability & Modularity - Cosmos SDK foundation with IBC‑friendly architecture for cross‑chain connectivity - Polaris EVM’s modular design enables stateful precompiles and chain‑specific extensions without breaking EVM apps - Drop‑in migration: reuse your contracts, tooling, and workflows ## Quick Start with Berachain Connect to Berachain in seconds with Dwellir's optimized endpoints: ### Installation & Setup ```bash # Check latest block curl -s -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' # Verify chain id curl -s -X POST https://api-berachain-bepolia.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}' ``` ```ts // Mainnet const mainnet = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); console.log(await mainnet.getBlockNumber()); console.log((await mainnet.getNetwork()).chainId); // 80094 // Bepolia testnet const bepolia = new JsonRpcProvider('https://api-berachain-bepolia.n.dwellir.com/YOUR_API_KEY'); console.log(await bepolia.getBlockNumber()); console.log((await bepolia.getNetwork()).chainId); // 80069 ``` ```ts const mainnet = createPublicClient({ transport: http('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'), }); const blockNumber = await mainnet.getBlockNumber(); const balance = await mainnet.getBalance({ address: '0x0000000000000000000000000000000000000000' }); ``` ```py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) assert w3.is_connected() print(w3.eth.chain_id) # 80094 print(w3.eth.block_number) ``` ## Network Information Mainnet Chain ID 80094 (0x138de) Berachain Mainnet Testnet Chain ID 80069 (0x138c5) Bepolia Testnet RPC Standard Ethereum JSON-RPC 2.0 EVM-compatible ## JSON-RPC API Reference Berachain supports the full [Ethereum JSON-RPC API](https://ethereum.org/developers/docs/apis/json-rpc/). ## Common Integration Patterns ### 🔄 Transaction Monitoring Monitor pending and confirmed transactions efficiently: ```javascript async function waitForConfirmations(provider, txHash, confirmations = 1) { const receipt = await provider.waitForTransaction(txHash, confirmations); return receipt; } ``` ### 💰 Gas Optimization Use EIP‑1559 dynamic fees and estimate execution gas: ```javascript const feeData = await provider.getFeeData(); const tx = { to: recipient, value: amount, maxFeePerGas: feeData.maxFeePerGas, maxPriorityFeePerGas: feeData.maxPriorityFeePerGas, gasLimit: await provider.estimateGas({ to: recipient, value: amount }), }; ``` ### 🔍 Event Filtering Query events in bounded ranges to avoid overfetching: ```javascript async function getEvents(contract, filter, fromBlock, toBlock, batchSize = 2000) { const events = []; for (let i = fromBlock; i <= toBlock; i += batchSize) { const batch = await contract.queryFilter(filter, i, Math.min(i + batchSize - 1, toBlock)); events.push(...batch); } return events; } ``` ## Performance Best Practices ### 1. **Batch Requests** Combine independent calls in a single POST to reduce round‑trips: ```javascript const batch = [ { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }, { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 }, { jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 } ]; const res = await fetch('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await res.json(); ``` ### 2. **Connection Pooling** Reuse provider/clients instead of recreating per call: ```ts class BeraProvider { static instance: JsonRpcProvider | null = null; static get() { if (!this.instance) { this.instance = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); } return this.instance; } } ``` ### 3. **Smart Caching** Cache immutable data (e.g., past blocks, ABIs) and debounce hot paths: ```ts const cache = new Map(); async function getBlockCached(n: number) { const k = `block_${n}`; if (!cache.has(k)) { cache.set(k, await BeraProvider.get().getBlock(n)); } return cache.get(k); } ``` ## Migration Guide Moving from Ethereum or another EVM chain typically requires: - Update RPC URL to Berachain: https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY - Verify chain ID via `eth_chainId` (0x138de mainnet) before sending transactions - Re-check gas settings (EIP‑1559) and any hard‑coded addresses ```ts // Before const provider = new JsonRpcProvider('https://eth.example'); // After (Berachain mainnet) const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); ``` ## Resources & Tools - Berachain Docs: https://docs.berachain.com/ - Dwellir Dashboard (API keys, usage): https://dashboard.dwellir.com - Dwellir Support: support@dwellir.com ## Troubleshooting Common Issues - Wrong chain: ensure `eth_chainId` returns `0x138de` (mainnet) or `0x138c5` (Bepolia). - Hex quantities: send and parse `0x`-prefixed hex strings (no leading zeros). - Timeouts/rate limits: implement retries with exponential backoff on HTTP 429 or -32005. ## FAQs - Do I need an API key? Yes, append `/YOUR_API_KEY` to all endpoints. - WebSockets? Use HTTP endpoints above; WebSocket availability may vary. - Explorers/faucets? N/A. ## Smoke Tests - curl: `eth_blockNumber` to both endpoints returns `result: "0x..."`. - ethers v6: `getBlockNumber()` resolves; `getNetwork().chainId` equals 80094 or 80069. - web3.py: `is_connected()` is True; `chain_id` and `block_number` query succeed. --- Start building on Berachain with Dwellir’s reliable RPC. --- ## net_listening - Berachain RPC Method # net_listening Returns `true` if client is actively listening for network connections on Berachain. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if listening | ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const listening = await provider.send('net_listening', []); console.log('Node listening:', listening); ``` ## Related Methods - [`net_peerCount`](./net_peerCount) - Get peer count --- ## net_peerCount - Berachain RPC Method # net_peerCount Returns number of peers currently connected to Berachain client. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Number of connected peers (hexadecimal) | ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const peerCount = await provider.send('net_peerCount', []); console.log('Peer count:', parseInt(peerCount, 16)); ``` ## Related Methods - [`net_listening`](./net_listening) - Check if listening --- ## net_version - Berachain RPC Method # net_version Returns the current network ID on Berachain. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Network ID as a string | ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const networkId = await provider.send('net_version', []); console.log('Network ID:', networkId); ``` ## Related Methods - [`eth_chainId`](./eth_chainId) - Get chain ID --- ## trace_block - Berachain RPC Method # trace_block Returns traces for all transactions in a block on Berachain. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Block analysis** - Inspect all internal transactions in a block - **MEV research** - Analyze transaction ordering and internal calls - **Indexing** - Build comprehensive transaction indexes for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex or tag (`latest`, `earliest`, `pending`) | ## Request ```json { "jsonrpc": "2.0", "method": "trace_block", "params": ["latest"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_block", "params": ["latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('trace_block', ['latest']); console.log('Traces in block:', traces.length); for (const trace of traces.slice(0, 5)) { console.log(` ${trace.action.from} -> ${trace.action.to} (${trace.type})`); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) traces = w3.provider.make_request('trace_block', ['latest']) for trace in traces['result'][:5]: action = trace['action'] print(f'{action["from"]} -> {action.get("to", "CREATE")} ({trace["type"]})') ``` ## Related Methods - [`trace_filter`](./trace_filter) - Filter traces by address or block range - [`trace_transaction`](./trace_transaction) - Trace a specific transaction - [`trace_get`](./trace_get) - Get a specific trace by index --- ## trace_call - Berachain RPC Method # trace_call Traces a call without creating a transaction on Berachain, returning the trace output. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Call simulation** - Preview internal calls before sending a transaction - **Contract interaction analysis** - Understand how contracts interact - **Gas estimation** - Analyze gas usage patterns for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `callObject` | `Object` | Yes | Transaction call object (`from`, `to`, `gas`, `value`, `data`) | | `traceTypes` | `Array` | Yes | Trace types: `["trace"]`, `["vmTrace"]`, `["stateDiff"]`, or combinations | | `blockNumber` | `QUANTITY\|TAG` | No | Block number or tag (default: `latest`) | ## Request ```json { "jsonrpc": "2.0", "method": "trace_call", "params": [ { "to": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "data": "0x70a082310000000000000000000000007507c1dc16935B82698e4C63f2746A2fCf994dF8" }, ["trace"], "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_call", "params": [ {"to": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "data": "0x70a082310000000000000000000000007507c1dc16935B82698e4C63f2746A2fCf994dF8"}, ["trace"], "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const result = await provider.send('trace_call', [ { to: '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8', data: '0x70a082310000000000000000000000007507c1dc16935B82698e4C63f2746A2fCf994dF8' }, ['trace'], 'latest' ]); console.log('Trace output:', result.trace); console.log('VM trace:', result.vmTrace); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) result = w3.provider.make_request('trace_call', [ { 'to': '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8', 'data': '0x70a082310000000000000000000000007507c1dc16935B82698e4C63f2746A2fCf994dF8' }, ['trace'], 'latest' ]) print(f'Trace: {result["result"]["trace"]}') ``` ## Related Methods - [`trace_filter`](./trace_filter) - Filter traces by criteria - [`eth_call`](./eth_call) - Execute call without trace - [`trace_transaction`](./trace_transaction) - Trace a specific transaction --- ## trace_callMany - Berachain RPC Method # trace_callMany Traces multiple calls in sequence on Berachain, where each call can depend on the state changes of the previous one. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Multi-step simulation** - Simulate a sequence of dependent transactions - **Arbitrage analysis** - Test multi-hop swap paths - **Batch operations** - Preview multiple contract interactions for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `calls` | `Array` | Yes | Array of `[callObject, traceTypes]` pairs | | `blockNumber` | `QUANTITY\|TAG` | No | Block number or tag (default: `latest`) | Each element in `calls` is a tuple of: - `callObject` - Transaction call object (`from`, `to`, `gas`, `value`, `data`) - `traceTypes` - Array of trace types: `["trace"]`, `["vmTrace"]`, `["stateDiff"]` ## Request ```json { "jsonrpc": "2.0", "method": "trace_callMany", "params": [ [ [{"to": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "data": "0x70a082310000000000000000000000007507c1dc16935B82698e4C63f2746A2fCf994dF8"}, ["trace"]], [{"to": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "data": "0x18160ddd"}, ["trace"]] ], "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_callMany", "params": [ [ [{"to": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "data": "0x70a082310000000000000000000000007507c1dc16935B82698e4C63f2746A2fCf994dF8"}, ["trace"]], [{"to": "0x7507c1dc16935B82698e4C63f2746A2fCf994dF8", "data": "0x18160ddd"}, ["trace"]] ], "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const results = await provider.send('trace_callMany', [ [ [{ to: '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8', data: '0x70a082310000000000000000000000007507c1dc16935B82698e4C63f2746A2fCf994dF8' }, ['trace']], [{ to: '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8', data: '0x18160ddd' }, ['trace']] ], 'latest' ]); console.log('Call results:', results.length); for (const result of results) { console.log(' Output:', result.output); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) results = w3.provider.make_request('trace_callMany', [ [ [{'to': '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8', 'data': '0x70a082310000000000000000000000007507c1dc16935B82698e4C63f2746A2fCf994dF8'}, ['trace']], [{'to': '0x7507c1dc16935B82698e4C63f2746A2fCf994dF8', 'data': '0x18160ddd'}, ['trace']] ], 'latest' ]) for i, result in enumerate(results['result']): print(f'Call {i}: output={result.get("output", "N/A")}') ``` ## Related Methods - [`trace_call`](./trace_call) - Trace a single call - [`eth_call`](./eth_call) - Execute call without trace --- ## trace_filter - Berachain RPC Method # trace_filter Returns traces matching a filter on Berachain. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Address activity** - Find all internal transactions involving an address - **Contract monitoring** - Track calls to specific contracts - **Forensic analysis** - Investigate transaction patterns for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterObject` | `Object` | Yes | Filter criteria (see below) | ### Filter Object Fields | Field | Type | Description | |-------|------|-------------| | `fromBlock` | `QUANTITY\|TAG` | Start block (hex or tag) | | `toBlock` | `QUANTITY\|TAG` | End block (hex or tag) | | `fromAddress` | `Array` | Filter by sender addresses | | `toAddress` | `Array` | Filter by receiver addresses | | `after` | `QUANTITY` | Offset for pagination | | `count` | `QUANTITY` | Max results to return | ## Request ```json { "jsonrpc": "2.0", "method": "trace_filter", "params": [{ "fromBlock": "latest", "toBlock": "latest", "toAddress": ["0x7507c1dc16935B82698e4C63f2746A2fCf994dF8"], "count": 10 }], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_filter", "params": [{ "fromBlock": "latest", "toBlock": "latest", "toAddress": ["0x7507c1dc16935B82698e4C63f2746A2fCf994dF8"], "count": 10 }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('trace_filter', [{ fromBlock: 'latest', toBlock: 'latest', toAddress: ['0x7507c1dc16935B82698e4C63f2746A2fCf994dF8'], count: 10 }]); console.log('Matching traces:', traces.length); for (const trace of traces) { console.log(` Block ${trace.blockNumber}: ${trace.action.from} -> ${trace.action.to}`); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) traces = w3.provider.make_request('trace_filter', [{ 'fromBlock': 'latest', 'toBlock': 'latest', 'toAddress': ['0x7507c1dc16935B82698e4C63f2746A2fCf994dF8'], 'count': 10 }]) for trace in traces['result']: action = trace['action'] print(f'Block {trace["blockNumber"]}: {action["from"]} -> {action.get("to", "CREATE")}') ``` ## Related Methods - [`trace_block`](./trace_block) - Get all traces in a block - [`trace_transaction`](./trace_transaction) - Get traces for a specific transaction - [`eth_getLogs`](./eth_getLogs) - Filter event logs --- ## trace_get - Berachain RPC Method # trace_get Returns a trace at a specific position within a transaction on Berachain. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Specific trace lookup** - Get a single trace by its position index - **Internal call inspection** - Examine a specific internal call - **Targeted debugging** - Investigate particular call depth for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `indices` | `Array` | Yes | Trace index positions (e.g., `["0x0"]` for the first trace) | ## Request ```json { "jsonrpc": "2.0", "method": "trace_get", "params": ["0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671", ["0x0"]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_get", "params": ["0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671", ["0x0"]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const trace = await provider.send('trace_get', [ '0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671', ['0x0'] ]); console.log('Trace type:', trace.type); console.log('From:', trace.action.from); console.log('To:', trace.action.to); console.log('Value:', trace.action.value); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) trace = w3.provider.make_request('trace_get', [ '0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671', ['0x0'] ]) result = trace['result'] print(f'Type: {result["type"]}') print(f'From: {result["action"]["from"]}') print(f'To: {result["action"]["to"]}') ``` ## Related Methods - [`trace_transaction`](./trace_transaction) - Get all traces for a transaction - [`trace_block`](./trace_block) - Get all traces in a block --- ## trace_replayBlockTransactions - Berachain RPC Method # trace_replayBlockTransactions Replays all transactions in a block on Berachain and returns the requested traces. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Block replay** - Re-execute all transactions with full trace output - **State diff analysis** - Get state changes for every transaction in a block - **VM trace extraction** - Obtain detailed EVM execution traces for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex or tag | | `traceTypes` | `Array` | Yes | Trace types: `["trace"]`, `["vmTrace"]`, `["stateDiff"]`, or combinations | ## Request ```json { "jsonrpc": "2.0", "method": "trace_replayBlockTransactions", "params": ["latest", ["trace"]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_replayBlockTransactions", "params": ["latest", ["trace"]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const results = await provider.send('trace_replayBlockTransactions', [ 'latest', ['trace'] ]); console.log('Transactions replayed:', results.length); for (const result of results.slice(0, 3)) { console.log(` Tx ${result.transactionHash}: ${result.trace.length} traces`); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) results = w3.provider.make_request('trace_replayBlockTransactions', [ 'latest', ['trace'] ]) for tx in results['result'][:3]: print(f'Tx {tx["transactionHash"]}: {len(tx["trace"])} traces') ``` ## Related Methods - [`trace_replayTransaction`](./trace_replayTransaction) - Replay a single transaction - [`trace_block`](./trace_block) - Get traces without replay - [`trace_filter`](./trace_filter) - Filter traces by criteria --- ## trace_replayTransaction - Berachain RPC Method # trace_replayTransaction Replays a transaction on Berachain and returns the requested traces. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction replay** - Re-execute a transaction with full trace output - **State diff extraction** - Get exact state changes from a transaction - **VM trace debugging** - Get opcode-level execution details for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `traceTypes` | `Array` | Yes | Trace types: `["trace"]`, `["vmTrace"]`, `["stateDiff"]`, or combinations | ## Request ```json { "jsonrpc": "2.0", "method": "trace_replayTransaction", "params": ["0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671", ["trace"]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_replayTransaction", "params": ["0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671", ["trace"]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const result = await provider.send('trace_replayTransaction', [ '0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671', ['trace'] ]); console.log('Trace:', result.trace.length, 'entries'); console.log('State diff:', result.stateDiff ? 'present' : 'not requested'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) result = w3.provider.make_request('trace_replayTransaction', [ '0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671', ['trace'] ]) trace = result['result'] print(f'Trace entries: {len(trace["trace"])}') ``` ## Related Methods - [`trace_replayBlockTransactions`](./trace_replayBlockTransactions) - Replay all transactions in a block - [`trace_transaction`](./trace_transaction) - Get traces without replay - [`trace_block`](./trace_block) - Get all traces in a block --- ## trace_transaction - Berachain RPC Method # trace_transaction Returns all traces for a specific transaction on Berachain. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction analysis** - See all internal calls made by a transaction - **Token transfer tracking** - Trace value flows through contracts - **Debugging** - Understand execution flow for liquidity-aligned DeFi (Infrared, Kodiak), yield farming, and validator-integrated liquidity incentives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "trace_transaction", "params": ["0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_transaction", "params": ["0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('trace_transaction', [ '0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671' ]); console.log('Traces:', traces.length); for (const trace of traces) { console.log(` ${trace.action.from} -> ${trace.action.to} (${trace.type})`); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY')) traces = w3.provider.make_request('trace_transaction', [ '0xc5c421e9e1f89c46d6f23e4057f24ed39fe8c8d75f0dc27159b46f8b6ece3671' ]) for trace in traces['result']: action = trace['action'] print(f'{action["from"]} -> {action.get("to", "CREATE")} ({trace["type"]})') ``` ## Related Methods - [`trace_get`](./trace_get) - Get a specific trace by index - [`trace_block`](./trace_block) - Get all traces in a block - [`trace_filter`](./trace_filter) - Filter traces by criteria --- ## web3_clientVersion - Berachain RPC Method # web3_clientVersion Returns the current client version on Berachain. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Client version string | ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); const version = await provider.send('web3_clientVersion', []); console.log('Client version:', version); ``` --- ## web3_sha3 - Berachain RPC Method # web3_sha3 Returns Keccak-256 (not standard SHA3-256) of the given data on Berachain. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `data` | `DATA` | Yes | Data to hash | ## Request ```json { "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Keccak-256 hash of the data | ## Code Examples ```bash curl -X POST https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-berachain-mainnet.n.dwellir.com/YOUR_API_KEY'); // Using RPC const hash = await provider.send('web3_sha3', ['0x68656c6c6f']); console.log('Hash:', hash); // Using ethers directly (faster) const localHash = keccak256(toUtf8Bytes('hello')); console.log('Local hash:', localHash); ``` --- ## author_pendingExtrinsics - Bifrost RPC Method # author_pendingExtrinsics Returns all pending extrinsics in the transaction pool on Bifrost. ## Use Cases - **Mempool monitoring** - Track pending transactions - **Transaction status** - Check if your transaction is pending for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Pool analysis** - Monitor network activity ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "author_pendingExtrinsics", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_pendingExtrinsics", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const pending = await api.rpc.author.pendingExtrinsics(); console.log('Pending extrinsics:', pending.length); pending.forEach((ext, idx) => { console.log(`${idx}: ${ext.method.section}.${ext.method.method}`); }); await api.disconnect(); ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction --- ## author_rotateKeys - Bifrost RPC Method # author_rotateKeys Generate a new set of session keys on Bifrost. This method creates fresh cryptographic keys for validator operations and stores them in the node's keystore. The returned keys must be registered on-chain via `session.setKeys`. ## Use Cases - **Validator setup** - Generate initial session keys for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Key rotation** - Periodically rotate keys for security best practices - **Recovery** - Generate new keys after potential key compromise ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | `Bytes` | Concatenated SCALE-encoded public keys for all session key types | ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_rotateKeys", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Generate new session keys const keys = await api.rpc.author.rotateKeys(); console.log('New session keys:', keys.toHex()); // These keys need to be registered on-chain: // api.tx.session.setKeys(keys, proof) await api.disconnect(); ``` ```python url = 'https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'author_rotateKeys', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json() if 'result' in result: session_keys = result['result'] print(f'New session keys: {session_keys}') print('Register these keys using session.setKeys extrinsic') else: print(f"Error: {result.get('error')}") ``` ## Validator Setup Workflow 1. **Generate keys** - Call `author_rotateKeys` on your validator node 2. **Register on-chain** - Submit `session.setKeys(keys, proof)` extrinsic 3. **Wait for session** - Keys become active in the next session 4. **Verify** - Check `session.nextKeys` storage ## Security Considerations - Only call this method on your own validator node - Session keys are stored in the node's keystore - Rotate keys periodically and after any security incident - Never expose this RPC method publicly ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit setKeys transaction - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - View pending transactions --- ## author_submitAndWatchExtrinsic - Bifrost RPC Method # author_submitAndWatchExtrinsic Submit a signed extrinsic to and subscribe to status updates. This WebSocket method provides real-time feedback on transaction progress from submission through finalization. ## Use Cases - **Transaction tracking** - Monitor extrinsic lifecycle for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **UI feedback** - Show users real-time transaction status - **Confirmation workflows** - Wait for specific finality level before proceeding ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `Bytes` | Yes | SCALE-encoded signed extrinsic | ## Returns Returns a subscription that emits `ExtrinsicStatus` updates: | Status | Description | |--------|-------------| | `future` | In future queue (nonce too high) | | `ready` | In ready queue, waiting for block | | `broadcast` | Broadcast to peers | | `inBlock` | Included in block (hash provided) | | `retracted` | Block retracted (reorg) | | `finalityTimeout` | Finality timeout | | `finalized` | Finalized in block (hash provided) | | `usurped` | Replaced by another extrinsic | | `dropped` | Dropped from pool | | `invalid` | Invalid extrinsic | ## Code Examples ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const keyring = new Keyring({ type: 'sr25519' }); // Create and sign a transfer const sender = keyring.addFromUri('//Alice'); const transfer = api.tx.balances.transferKeepAlive( '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 1000000000000n ); // Submit and watch const unsub = await transfer.signAndSend(sender, ({ status, events }) => { console.log(`Status: ${status.type}`); if (status.isInBlock) { console.log(`Included in block: ${status.asInBlock.toHex()}`); } if (status.isFinalized) { console.log(`Finalized in block: ${status.asFinalized.toHex()}`); unsub(); } }); ``` ```python async def submit_and_watch(signed_extrinsic_hex): uri = 'wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: # Submit and subscribe await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'author_submitAndWatchExtrinsic', 'params': [signed_extrinsic_hex], 'id': 1 })) # Get subscription ID response = json.loads(await ws.recv()) if 'error' in response: print(f"Error: {response['error']}") return sub_id = response['result'] print(f'Watching with subscription: {sub_id}') # Listen for status updates while True: message = json.loads(await ws.recv()) if 'params' in message: status = message['params']['result'] print(f"Status: {status}") # Check for finalization if isinstance(status, dict) and 'finalized' in status: print(f"Finalized in: {status['finalized']}") break # asyncio.run(submit_and_watch('0x...')) ``` ## Status Flow ``` ready → broadcast → inBlock → finalized ↘ retracted (if reorg) ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit without watching (fire-and-forget) - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - View transaction pool - [`payment_queryInfo`](./payment_queryInfo) - Estimate fees before submission --- ## author_submitExtrinsic - Bifrost RPC Method # author_submitExtrinsic Submit a signed extrinsic to Bifrost for inclusion in a block. ## Use Cases - **Transaction submission** - Broadcast signed transactions - **dApp interactions** - Execute on-chain operations for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Automated systems** - Submit programmatic transactions ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `String` | Yes | Hex-encoded signed extrinsic | ## Request ```json { "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": ["0x..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Transaction hash | ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": ["0x..."], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const keyring = new Keyring({ type: 'sr25519' }); const sender = keyring.addFromUri('//Alice'); // Build and sign transaction const transfer = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000); const hash = await transfer.signAndSend(sender); console.log('Transaction hash:', hash.toHex()); await api.disconnect(); ``` ## Related Methods - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - Get pending transactions - [`payment_queryInfo`](./payment_queryInfo) - Estimate fees --- ## beefy_getFinalizedHead - Bifrost RPC Method # beefy_getFinalizedHead Returns the block hash of the latest BEEFY-finalized block on Bifrost. BEEFY (Bridge Efficiency Enabling Finality Yielder) provides additional finality proofs optimized for light clients and bridges. ## Use Cases - **Cross-chain bridges** - Verify finality proofs for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Light clients** - Efficient finality verification without full GRANDPA proofs - **Trustless bridges** - Generate compact finality proofs for external chains ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | `Hash` | Block hash of the latest BEEFY-finalized block | ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "beefy_getFinalizedHead", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get BEEFY finalized head const beefyHead = await api.rpc.beefy.getFinalizedHead(); console.log('BEEFY finalized:', beefyHead.toHex()); // Compare with GRANDPA finalized const grandpaHead = await api.rpc.chain.getFinalizedHead(); console.log('GRANDPA finalized:', grandpaHead.toHex()); await api.disconnect(); ``` ```python url = 'https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'beefy_getFinalizedHead', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json() if 'result' in result: print(f"BEEFY finalized: {result['result']}") else: print(f"Error: {result.get('error')}") ``` ## BEEFY vs GRANDPA Finality | Aspect | GRANDPA | BEEFY | |--------|---------|-------| | **Purpose** | Primary finality | Bridge-optimized finality | | **Proof size** | Larger (full validator set) | Compact (aggregated signatures) | | **Latency** | Immediate | Slightly delayed | | **Use case** | On-chain finality | Cross-chain bridges | ## Availability BEEFY is enabled on relay chains and some parachains. If BEEFY is not enabled, this method will return an error. ## Related Methods - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - GRANDPA finalized head - [`grandpa_roundState`](./grandpa_roundState) - GRANDPA consensus state - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks --- ## chain_getBlock - Bifrost RPC Method # chain_getBlock Retrieves complete block information from Bifrost, including the block header, extrinsics, and justifications. > **Why Bifrost?** Build on Polkadot's largest liquid staking appchain with 60% DOT LST market share and $125M+ TVL with first LST governance on OpenGov, 60% DOT market share, Hyperbridge ETH integration, and 500K DOT treasury support. ## Use Cases The `chain_getBlock` method is essential for: - **Block explorers** - Display complete block information - **Chain analysis** - Analyze block production patterns - **Transaction verification** - Confirm extrinsic inclusion for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Data indexing** - Build historical blockchain databases ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Hex-encoded block hash. If omitted, returns latest block | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getBlock", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `block` | `Object` | Complete block data | | `block.header` | `Object` | Block header information | | `block.header.parentHash` | `String` | Hash of the parent block | | `block.header.number` | `String` | Block number (hex-encoded) | | `block.header.stateRoot` | `String` | Root of the state trie | | `block.header.extrinsicsRoot` | `String` | Root of the extrinsics trie | | `block.extrinsics` | `Array` | Array of extrinsics in the block | | `justifications` | `Array` | Block justifications (if available) | ## Code Examples ```bash # Get latest block curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": [], "id": 1 }' # Get specific block curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get latest block const latestHash = await api.rpc.chain.getBlockHash(); const latestBlock = await api.rpc.chain.getBlock(latestHash); console.log('Latest block:', { number: latestBlock.block.header.number.toNumber(), hash: latestHash.toHex(), extrinsicsCount: latestBlock.block.extrinsics.length }); // Get specific block const blockHash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'; const block = await api.rpc.chain.getBlock(blockHash); console.log('Block extrinsics:', block.block.extrinsics.length); await api.disconnect(); ``` ```python def get_block(block_hash=None): url = 'https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY' params = [block_hash] if block_hash else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getBlock', 'params': params, 'id': 1 } response = requests.post(url, json=payload) data = response.json() if 'error' in data: raise Exception(f"RPC Error: {data['error']}") return data['result'] # Get latest block latest_block = get_block() block_number = int(latest_block['block']['header']['number'], 16) print(f'Latest block number: {block_number}') # Get specific block specific_block = get_block('0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3') print(f"Extrinsics count: {len(specific_block['block']['extrinsics'])}") ``` ## Related Methods - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number - [`chain_getHeader`](./chain_getHeader) - Get block header only - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get finalized block hash --- ## chain_getBlockHash - Bifrost RPC Method # chain_getBlockHash Returns the block hash for a given block number on Bifrost. ## Use Cases - **Historical queries** - Convert block numbers to hashes - **Block navigation** - Navigate blockchain history for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Data indexing** - Build block number to hash mappings ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `Number` | No | Block number. If omitted, returns latest block hash | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getBlockHash", "params": [1000000], "id": 1 } ``` ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlockHash", "params": [1000000], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get hash for specific block number const blockNumber = 1000000; const blockHash = await api.rpc.chain.getBlockHash(blockNumber); console.log(`Block ${blockNumber} hash:`, blockHash.toHex()); await api.disconnect(); ``` ```python def get_block_hash(block_number=None): url = 'https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY' params = [block_number] if block_number is not None else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getBlockHash', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] block_hash = get_block_hash(1000000) print(f'Block hash: {block_hash}') ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get block by hash - [`chain_getHeader`](./chain_getHeader) - Get block header --- ## chain_getFinalizedHead - Bifrost RPC Method # chain_getFinalizedHead Returns the hash of the last finalized block on Bifrost. ## Use Cases - **Confirmed state** - Query state that cannot be reverted - **Transaction confirmation** - Verify transaction finality for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Safe checkpoints** - Use finalized blocks for critical operations ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const finalizedHash = await api.rpc.chain.getFinalizedHead(); console.log('Finalized block hash:', finalizedHash.toHex()); // Get finalized block details const block = await api.rpc.chain.getBlock(finalizedHash); console.log('Finalized block number:', block.block.header.number.toNumber()); await api.disconnect(); ``` ```python def get_finalized_head(): url = 'https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'chain_getFinalizedHead', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] finalized_hash = get_finalized_head() print(f'Finalized block hash: {finalized_hash}') ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get block by hash - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number --- ## chain_getHeader - Bifrost RPC Method # chain_getHeader Returns the block header for a given hash on Bifrost. ## Use Cases - **Lightweight queries** - Get header without full block data - **Chain synchronization** - Track block production for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Parent chain navigation** - Follow parentHash links ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash. If omitted, returns latest header | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getHeader", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 } ``` ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getHeader", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get latest header const header = await api.rpc.chain.getHeader(); console.log('Block number:', header.number.toNumber()); console.log('Parent hash:', header.parentHash.toHex()); await api.disconnect(); ``` ```python def get_header(block_hash=None): url = 'https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY' params = [block_hash] if block_hash else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getHeader', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] header = get_header() print(f"Block number: {int(header['number'], 16)}") ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get full block with extrinsics - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number --- ## chain_subscribeFinalizedHeads - Bifrost RPC Method # chain_subscribeFinalizedHeads Subscribe to receive notifications when blocks are finalized on Bifrost. Finalized blocks are guaranteed to never be reverted, making this essential for applications requiring strong consistency. ## Use Cases - **Exchange deposits** - Only credit funds after finalization for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Bridge operations** - Wait for finality before cross-chain transfers - **Critical state changes** - Ensure irreversibility for important transactions ## Parameters This method takes no parameters. ## Returns Returns a subscription ID. The subscription emits `Header` objects for each finalized block: | Field | Type | Description | |-------|------|-------------| | `parentHash` | `Hash` | Parent block hash | | `number` | `BlockNumber` | Block number | | `stateRoot` | `Hash` | State trie root hash | | `extrinsicsRoot` | `Hash` | Extrinsics trie root hash | | `digest` | `Digest` | Block digest with consensus logs | ## Code Examples ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Subscribe to finalized heads const unsubscribe = await api.rpc.chain.subscribeFinalizedHeads((header) => { console.log(`Finalized block #${header.number}`); console.log(` Hash: ${header.hash.toHex()}`); // Safe to consider this block permanent processConfirmedBlock(header); }); // Later: unsubscribe() ``` ```python async def subscribe_finalized(): uri = 'wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'chain_subscribeFinalizedHeads', 'params': [], 'id': 1 })) response = json.loads(await ws.recv()) sub_id = response['result'] print(f'Subscribed to finalized heads: {sub_id}') while True: message = json.loads(await ws.recv()) if 'params' in message: header = message['params']['result'] block_num = int(header['number'], 16) print(f"Finalized: #{block_num}") asyncio.run(subscribe_finalized()) ``` ## Finality Lag Finalized blocks typically lag behind the best block by a few blocks due to GRANDPA consensus requirements. This is normal and ensures Byzantine fault tolerance. ## Related Methods - [`chain_subscribeNewHeads`](./chain_subscribeNewHeads) - Subscribe to all new blocks (not just finalized) - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get current finalized block hash - [`grandpa_roundState`](./grandpa_roundState) - Monitor GRANDPA consensus progress --- ## chain_subscribeNewHeads - Bifrost RPC Method # chain_subscribeNewHeads Subscribe to receive notifications when new block headers are produced on Bifrost. This WebSocket subscription provides real-time updates for each new block. ## Use Cases - **Block monitoring** - Track new blocks in real-time for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Event indexing** - Trigger processing when new blocks arrive - **Chain synchronization** - Keep external systems in sync with the chain ## Parameters This method takes no parameters. ## Returns Returns a subscription ID. The subscription emits `Header` objects for each new block: | Field | Type | Description | |-------|------|-------------| | `parentHash` | `Hash` | Parent block hash | | `number` | `BlockNumber` | Block number | | `stateRoot` | `Hash` | State trie root hash | | `extrinsicsRoot` | `Hash` | Extrinsics trie root hash | | `digest` | `Digest` | Block digest with consensus logs | ## Code Examples ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Subscribe to new heads const unsubscribe = await api.rpc.chain.subscribeNewHeads((header) => { console.log(`New block #${header.number}`); console.log(` Hash: ${header.hash.toHex()}`); console.log(` Parent: ${header.parentHash.toHex()}`); console.log(` State root: ${header.stateRoot.toHex()}`); }); // Later: unsubscribe() ``` ```python async def subscribe_new_heads(): uri = 'wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: # Subscribe to new heads await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'chain_subscribeNewHeads', 'params': [], 'id': 1 })) # Get subscription ID response = json.loads(await ws.recv()) sub_id = response['result'] print(f'Subscribed with ID: {sub_id}') # Listen for new headers while True: message = json.loads(await ws.recv()) if 'params' in message: header = message['params']['result'] print(f"Block #{int(header['number'], 16)}") print(f" Hash: {header['parentHash']}") asyncio.run(subscribe_new_heads()) ``` ## Subscription vs Polling | Approach | Latency | Resource Usage | Use Case | |----------|---------|----------------|----------| | `subscribeNewHeads` | Immediate | Low (push-based) | Real-time monitoring | | Polling `getHeader` | Block time + poll interval | Higher (repeated requests) | Simple integrations | ## Related Methods - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks only - [`chain_getHeader`](./chain_getHeader) - Get a specific block header - [`chain_getBlock`](./chain_getBlock) - Get full block with extrinsics --- ## grandpa_roundState - Bifrost RPC Method # grandpa_roundState Returns the state of the current GRANDPA finality round on Bifrost. GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) is the finality gadget used by Substrate chains. ## Use Cases - **Finality monitoring** - Track consensus progress for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Validator analysis** - Monitor prevote/precommit participation - **Chain health checks** - Detect finality delays or stalls ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `setId` | `u64` | Current authority set ID | | `best` | `RoundState` | Best round state | | `background` | `Vec` | Background rounds | ### RoundState Structure | Field | Type | Description | |-------|------|-------------| | `round` | `u64` | Round number | | `totalWeight` | `u64` | Total validator weight | | `thresholdWeight` | `u64` | Weight needed for supermajority | | `prevotes` | `Prevotes` | Prevote information | | `precommits` | `Precommits` | Precommit information | ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "grandpa_roundState", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const roundState = await api.rpc.grandpa.roundState(); console.log('Set ID:', roundState.setId.toString()); console.log('Best round:', roundState.best.round.toString()); console.log('Total weight:', roundState.best.totalWeight.toString()); console.log('Threshold:', roundState.best.thresholdWeight.toString()); await api.disconnect(); ``` ```python url = 'https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'grandpa_roundState', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json()['result'] print(f"Set ID: {result['setId']}") print(f"Round: {result['best']['round']}") print(f"Total weight: {result['best']['totalWeight']}") ``` ## Understanding GRANDPA Rounds 1. **Prevote phase** - Validators vote on best block they've seen 2. **Precommit phase** - Validators commit to finalize if supermajority prevoted 3. **Finalization** - Block is finalized when 2/3+ weight precommits ## Related Methods - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get current finalized hash - [`beefy_getFinalizedHead`](./beefy_getFinalizedHead) - BEEFY finality (if enabled) --- ## Bifrost Liquid Staking Parachain RPC Guide ## Why Build on Bifrost? Bifrost is Polkadot's liquid staking hub, issuing omni-chain vTokens that unlock staking liquidity while keeping rewards flowing. Builders target Bifrost because it delivers: ### 🌉 **Omni-Chain Liquidity Routing** - Staking Liquidity Protocol (SLP) mints yield-bearing vTokens (vDOT, vKSM, vETH, vFIL) that stay composable across parachains and EVM networks. - Slot Auction Liquidity Protocol (SALP) releases DOT/KSM crowdloan positions into tradable derivatives, letting users support auctions without sacrificing liquidity. - Liquid staking primitives integrate with major DeFi venues (Pendle, Loop Stake, Talisman, etc.) to optimize leverage and hedging strategies. ### ⚙️ **Protocol-Neutral Architecture** - Dedicated pallets for cross-chain execution (ISMP, CrossInOut, Hyperbridge) make it easy to bridge liquidity between Polkadot, Kusama, and external EVMs. - Governance and fee-share pallets align collators, liquidity providers, and derivative users through on-chain revenue distribution. - Runtime upgrades (v0.21.1 / specVersion 21001) focus on async backing, Hyperbridge routes, and tokenomics 2.0 for sustained reward flows. ### 📈 **Battle-Tested Operations** - Active collator set with ~6 s block time keeps derivatives in sync with relay-chain finality. - Proven SALP campaigns unlock DOT crowdloans while maintaining reward accrual. - Continuous grant support and ecosystem partnerships accelerate tooling and collateral adoption. ## Quick Start with Bifrost Connect to mainnet or the Kusama canary network in seconds using Dwellir-managed infrastructure. :::info Canary Environment The Kusama deployment (Para ID 2001) runs identical pallets ahead of Polkadot releases. Use it for SALP dry-runs, Hyperbridge testing, and upgrade rehearsals before promoting to mainnet Para ID 2030. ::: ### Installation & Setup ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "chain_getHeader", "params": [] }' ``` **Expected output (captured 2025-10-03):** ```json { "jsonrpc": "2.0", "result": { "number": "0x9055f2", "hash": "0xd4b3a0e3b88b7c25215926bbf7c733f5c31e69c0c8c4b4a86d6ec3f3f086e95d", "parentHash": "0x65b246e9b69a61f842104a15307ae906013c56a8bb6c942555b1a71424b4bab3", "stateRoot": "0x220ea5bd35df99176268d8cbcee287a8a81a2e8addfa764661f71af591db0329", "extrinsicsRoot": "0x388e5e2bb951b1dfac3f6a3f0c1d5de1ace6e413008efe48f1a54228dcd049db" }, "id": 1 } ``` ```typescript async function main() { const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const [chain, nodeName, nodeVersion, runtime] = await Promise.all([ api.rpc.system.chain(), api.rpc.system.name(), api.rpc.system.version(), api.rpc.state.getRuntimeVersion() ]); console.log(`Connected to ${chain.toString()} via ${nodeName.toString()} ${nodeVersion.toString()}`); console.log(`Runtime specVersion=${runtime.specVersion.toNumber()} transactionVersion=${runtime.transactionVersion.toNumber()}`); const header = await api.rpc.chain.getHeader(); console.log(`Latest head #${header.number.toString()} (${header.hash.toHex()})`); await api.disconnect(); } main().catch(console.error); ``` ```rust use subxt::{config::substrate::SubstrateConfig, OnlineClient}; #[tokio::main] async fn main() -> Result<(), Box> { let api = OnlineClient::::from_url( "wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY" ).await?; let latest = api.rpc().header(None).await?.expect("header"); println!("Finalized block #{}", latest.number); println!("State root {}", latest.state_root); Ok(()) } ``` ```python from substrateinterface import SubstrateInterface substrate = SubstrateInterface( url="wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY", type_registry_preset="substrate-node-template" ) latest_hash = substrate.get_chain_head() print("Latest head:", latest_hash) runtime = substrate.get_runtime_version() print("specVersion:", runtime['specVersion'], "transactionVersion:", runtime['transactionVersion']) account_info = substrate.query( module='System', storage_function='Account', params=['15mYsj6DpBno58jRoV5HCTiVPFBuWhDLdsWtq3LxwZrfaTEZ'] ) print("Collator free balance:", account_info.value['data']['free']) ``` ## Substrate JSON-RPC API Reference ### Core Method Shortlist | Group | Purpose | Key Methods | |-------|---------|-------------| | `system_*` | Node health, metadata, peer status | [`system_health`](/bifrost/system_health), [`system_version`](/bifrost/system_version), [`system_properties`](/bifrost/system_properties) | | `chain_*` | Headers, blocks, finality tracking | [`chain_getHeader`](/bifrost/chain_getHeader), [`chain_getBlock`](/bifrost/chain_getBlock), [`chain_subscribeNewHeads`](/bifrost/chain_subscribeNewHeads) | | `state_*` | Storage queries and runtime metadata | [`state_getStorage`](/bifrost/state_getStorage), [`state_getKeysPaged`](/bifrost/state_getKeysPaged), [`state_getMetadata`](/bifrost/state_getMetadata) | | `author_*` | Extrinsic submission pipeline | [`author_submitExtrinsic`](/bifrost/author_submitExtrinsic), [`author_pendingExtrinsics`](/bifrost/author_pendingExtrinsics) | | `grandpa_*` | Finality gadget insights | [`grandpa_roundState`](/bifrost/grandpa_roundState) | | `rpc_methods` | Discover supported namespaces | [`rpc_methods`](/bifrost/rpc_methods) | ## Network Information | Parameter | Bifrost (Polkadot Mainnet) | Bifrost (Kusama Canary) | |-----------|----------------------------|-------------------------| | **Relay Chain** | Polkadot | Kusama | | **Parachain ID** | 2030 | 2001 | | **Genesis Hash** | `0x262e1b2ad728475fd6fe88e62d34c200abe6fd693931ddad144059b1eb884e5b` | `0x9f28c6a68e0fc9646eff64935684f6eeeece527e37bbe1f213d22caa1d9d6bed` | | **Runtime (2025-10-03)** | specVersion `21001`, transactionVersion `1` | specVersion `19000`, transactionVersion `1` | | **Unit Symbol** | BNC | BNC | | **Decimals** | 12 | 12 | | **SS58 Prefix** | 6 | 6 | | **Explorer** | bifrost.subscan.io | bifrost-kusama.subscan.io | | **Average Block Time** | ~6 seconds | ~6 seconds | Additional facts: - Collator rotation maintains >16 active authors with refTime utilization under 0.5% per block. - The runtime exposes specialized pallets including `Hyperbridge`, `FlexibleFee`, `Farming`, and `Ismp` for cross-ecosystem liquidity orchestration. ## Common Integration Patterns ### Real-Time Block Streaming ```typescript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); api.rpc.chain.subscribeNewHeads((header) => { console.log(`New Bifrost block #${header.number.toString()} (${header.hash.toHex()})`); }); ``` ### Query Staking Liquidity Positions ```bash # Read total issuance for vDOT (AssetRegistry + Tokens pallet) curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc":"2.0", "id":42, "method":"state_getStorage", "params":[ "0x1bd4a27d04bdb9c3f135c3b09677626d26c37dd72647d0f2788a3341e9ac1371" ] }' ``` ### Estimate Fees for SALP Transfers ```typescript const api = await ApiPromise.create({ provider: new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY') }); const tx = api.tx.crossInOut.swapExactAssetsForAssets( /* asset_in */ { Xcm: { V3: { parents: 1, interior: 'Here' } } }, /* asset_out */ { Token: 'BNC' }, /* amount */ 1_000_000_000_000n, /* min_receive */ 990_000_000_000n ); const info = await api.rpc.payment.queryInfo(tx.toHex()); console.log(`Partial fee: ${info.partialFee.toHuman()}`); console.log(`Weight: ${info.weight.refTime.toString()} refTime`); ``` ## Performance Best Practices - Prefer WebSocket endpoints for subscriptions and long-lived queries; use HTTPS for bursty read-only workloads. - Cache runtime metadata and type registries keyed by `specVersion` (Polkadot `21001`, Kusama `19000` as of 2025-10-03) to avoid repeated handshakes. - Use `state_getKeysPaged` with sized pages (<1024 keys) when scanning liquidity pools or reward ledgers. - Pin to finalized heads for settlement-critical reads; leverage `chain_getFinalizedHead` before fetching block data. - Implement jittered reconnect backoff (250 ms → 8 s) to respect Dwellir rate limiting during failover events. ## Troubleshooting | Symptom | Likely Cause | Resolution | |---------|--------------|------------| | `1010: Invalid Transaction` when submitting vToken extrinsics | Runtime upgrade bumped `specVersion`/`transactionVersion` | Refresh metadata, rebuild the payload, and resubmit with the updated version info | | `Invalid SS58 address` errors | Using Polkadot prefix (`0`) for Bifrost accounts | Re-derive addresses with SS58 prefix `6` before signing or decoding | | `TypeError: Cannot decode storage` | Missing custom pallets (Hyperbridge, FlexibleFee) in type registry | Extend your type bundle with the latest Bifrost runtime metadata | | Persistent WebSocket disconnects | Idle connection without keep-alives | Send periodic heartbeats (e.g., `rpc_methods`) or enable `WsProvider` autoConnect | | `Authoring not allowed for account` on collator nodes | Rotate keys not submitted after upgrade | Call `author_rotateKeys` and `parachainStaking.setKeys` on the canary network, then on mainnet | ## Smoke Tests Run these checks before pushing to production: 1. **Node health** ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"system_health","params":[]}' ``` Verify `isSyncing` is `false` and peer count stays above 8. 2. **Latest header increments** ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":2,"method":"chain_getHeader","params":[]}' ``` Confirm block numbers advance ~every 6 seconds (e.g., #9,053,714 at 2025-10-03 07:42:18 UTC). 3. **Account snapshot** ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":3,"method":"state_getStorage","params":["0x26aa394eea5630e07c48ae0c9558cef7f0d3720dbb6f7b3bb82b41c16dbf8d0887f21b38c918a1962fa4273d0f3c2c23244cc25f029aba80a72f1ac277957bc4"]}' ``` Decode the SCALE payload to check BNC balances (collator `15mYsj6…TEZ` shows active staking reserves). ## Migration Guide (Polkadot/Westend → Bifrost) - **Endpoints:** Swap legacy Polkadot URLs for `https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY`. Use the Kusama canary endpoint for staging. - **Address encoding:** Update wallets and services to SS58 prefix `6` for Bifrost accounts. - **Metadata:** Refresh runtime metadata whenever `specVersion` changes (currently `21001` on Polkadot, `19000` on Kusama). Update custom pallets (Hyperbridge, FlexibleFee, SALP) in your type registry. - **Fee estimation:** Run `payment_queryInfo` for vToken transfers; Bifrost’s flexible-fee pallet introduces dynamic surcharge multipliers. - **Pallet coverage:** Check `rpc_methods` after upgrades to discover new `bifrost_*` runtime APIs (e.g., omnipool analytics, Hyperbridge routing). ## Resources & Tools - Bifrost network explorer — [bifrost.subscan.io](https://bifrost.subscan.io) - Bifrost GitHub releases and runtime notes — [github.com/bifrost-io/bifrost/releases](https://github.com/bifrost-io/bifrost/releases) - Dwellir Dashboard — [dashboard.dwellir.com/register](https://dashboard.dwellir.com/register) - Community updates & integration stories — [parachains.info/details/bifrost_finance_polkadot](https://parachains.info/details/bifrost_finance_polkadot) Plan your integration, mint liquidity-backed vTokens, and rely on Dwellir’s globally distributed RPC edge to keep your Bifrost workloads online. --- ## payment_queryFeeDetails - Bifrost RPC Method # payment_queryFeeDetails Returns a detailed breakdown of fees for a given extrinsic on Bifrost. Unlike `payment_queryInfo` which returns the total fee, this method separates the fee into its component parts. ## Use Cases - **Fee analysis** - Understand fee composition for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Optimization** - Identify which fee component dominates costs - **Debugging** - Diagnose unexpected fee amounts ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `Bytes` | Yes | SCALE-encoded extrinsic (signed or unsigned) | | `blockHash` | `Hash` | No | Block hash for fee calculation context | ## Returns | Field | Type | Description | |-------|------|-------------| | `inclusionFee` | `Option` | Fee details (null for unsigned extrinsics) | ### InclusionFee Structure | Field | Type | Description | |-------|------|-------------| | `baseFee` | `Balance` | Fixed base fee per extrinsic | | `lenFee` | `Balance` | Fee based on encoded extrinsic length | | `adjustedWeightFee` | `Balance` | Fee based on execution weight | ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "payment_queryFeeDetails", "params": ["0x...encodedExtrinsic"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Create a sample transfer const tx = api.tx.balances.transferKeepAlive( '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 1000000000000n ); // Get fee details const feeDetails = await api.rpc.payment.queryFeeDetails(tx.toHex()); if (feeDetails.inclusionFee.isSome) { const fee = feeDetails.inclusionFee.unwrap(); console.log('Base fee:', fee.baseFee.toString()); console.log('Length fee:', fee.lenFee.toString()); console.log('Weight fee:', fee.adjustedWeightFee.toString()); } await api.disconnect(); ``` ```python url = 'https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY' # Replace with actual encoded extrinsic encoded_extrinsic = '0x...' payload = { 'jsonrpc': '2.0', 'method': 'payment_queryFeeDetails', 'params': [encoded_extrinsic], 'id': 1 } response = requests.post(url, json=payload) result = response.json()['result'] if result['inclusionFee']: fee = result['inclusionFee'] print(f"Base fee: {fee['baseFee']}") print(f"Length fee: {fee['lenFee']}") print(f"Weight fee: {fee['adjustedWeightFee']}") ``` ## Fee Components Explained | Component | Calculation | Optimization | |-----------|-------------|--------------| | **Base fee** | Fixed per extrinsic | Batch calls to share base fee | | **Length fee** | `length * lengthToFee` | Minimize call data size | | **Weight fee** | `weight * weightToFee` | Choose efficient operations | ## Related Methods - [`payment_queryInfo`](./payment_queryInfo) - Get total fee estimate - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction - [`state_call`](./state_call) - Call TransactionPaymentApi directly --- ## payment_queryInfo - Bifrost RPC Method # payment_queryInfo Estimates the fee for an extrinsic on Bifrost. ## Use Cases - **Fee estimation** - Calculate transaction costs before sending - **UI display** - Show fees to users for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Transaction planning** - Ensure sufficient funds ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `String` | Yes | Hex-encoded unsigned extrinsic | | `blockHash` | `String` | No | Block hash for fee calculation | ## Request ```json { "jsonrpc": "2.0", "method": "payment_queryInfo", "params": ["0x..."], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `weight` | `Object` | Transaction weight | | `class` | `String` | Dispatch class | | `partialFee` | `String` | Estimated fee | ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "payment_queryInfo", "params": ["0x..."], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Create transfer (unsigned for estimation) const transfer = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000); const info = await transfer.paymentInfo('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'); console.log('Partial fee:', info.partialFee.toHuman()); await api.disconnect(); ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction --- ## rpc_methods - Bifrost RPC Method # rpc_methods Returns a list of all RPC methods available on Bifrost. ## Use Cases - **API discovery** - List all available methods - **Compatibility checking** - Verify method availability for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Documentation** - Auto-generate method lists ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const methods = await api.rpc.rpc.methods(); console.log('Available methods:', methods.methods.length); await api.disconnect(); ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## state_call - Bifrost RPC Method # state_call Calls a runtime API method on Bifrost. ## Use Cases - **Runtime computations** - Execute runtime logic without transactions - **Account queries** - Use AccountNonceApi for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Fee estimation** - Use TransactionPaymentApi ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `method` | `String` | Yes | Runtime API method name | | `data` | `String` | Yes | SCALE-encoded call data | | `blockHash` | `String` | No | Block hash for historical call | ## Request ```json { "jsonrpc": "2.0", "method": "state_call", "params": ["AccountNonceApi_account_nonce", "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"], "id": 1 } ``` ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_call", "params": ["AccountNonceApi_account_nonce", "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get account nonce via runtime API const account = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const result = await api.call.accountNonceApi.accountNonce(account); console.log('Account nonce:', result.toNumber()); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Query storage - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## state_getKeys(Bifrost) ## Description Returns all storage keys with a given prefix. Use this to discover accounts, vToken positions, or other on-chain items before fetching values with `state_getStorage`. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `prefix` | string | Yes | Hex-encoded storage key prefix | | `blockHash` | string | No | Block hash for historical queries | ## Returns Array of matching hex-encoded storage keys. ## Request Example ```json { "jsonrpc": "2.0", "method": "state_getKeys", "params": [ "0x26aa394eea5630e07c48ae0c9558cef7", null ], "id": 1 } ``` ## Response Example ```json { "jsonrpc": "2.0", "result": [ "0x26aa394eea5630e07c48ae0c9558cef7b6a7c9a35a95a160cb4cad330558dfa56d6f646c755b98a7afd0913860592153322b957be394a0619f20b32679ac1014", "0x26aa394eea5630e07c48ae0c9558cef7c8e63e63a001c280f6dc809625f6ce9c53c51e645dd0a2c3e0800a9c53aac6ffe81912f6526f364eb8e4a36c2e304931" ], "id": 1 } ``` ## Code Examples ```python keys = substrate.rpc_request( method='state_getKeys', params=['0x26aa394eea5630e07c48ae0c9558cef7', None] )["result"] print(len(keys)) ``` ```javascript const keyPrefix = api.registry.createType('StorageKey', 'System', 'Account').toHex(); const keys = await api.rpc.state.getKeys(keyPrefix, null); console.log('Found', keys.length, 'System.Account entries'); ``` ## Tips - For large datasets prefer `state_getKeysPaged` to avoid stress-testing nodes. - Combine with Bifrost-specific prefixes (e.g., `Omnipool` or `Farming`) to iterate liquidity pools and reward schedules. --- ## state_getKeysPaged - Bifrost RPC Method # state_getKeysPaged Returns storage keys with pagination on Bifrost. ## Use Cases - **Storage iteration** - Enumerate storage map entries - **Data export** - Bulk export chain data for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Account enumeration** - List all accounts ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `prefix` | `String` | Yes | Storage key prefix | | `count` | `Number` | Yes | Maximum keys to return | | `startKey` | `String` | No | Key to start after | | `blockHash` | `String` | No | Block hash for historical query | ## Request ```json { "jsonrpc": "2.0", "method": "state_getKeysPaged", "params": ["0x...", 100], "id": 1 } ``` ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getKeysPaged", "params": ["0x26aa394eea5630e07c48ae0c9558cef7", 100], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get all accounts (paginated) const keys = await api.rpc.state.getKeysPaged( api.query.system.account.keyPrefix(), 100 ); console.log('Found accounts:', keys.length); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Get storage value - [`state_queryStorageAt`](./state_queryStorageAt) - Batch storage query --- ## state_getMetadata - Bifrost RPC Method # state_getMetadata Returns the runtime metadata on Bifrost. ## Use Cases - **Runtime introspection** - Discover available pallets and calls - **Extrinsic building** - Get call and type information for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Storage key generation** - Build storage keys from metadata - **Client generation** - Auto-generate typed APIs ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash for historical metadata | ## Request ```json { "jsonrpc": "2.0", "method": "state_getMetadata", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getMetadata", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get runtime metadata const metadata = await api.rpc.state.getMetadata(); // List available pallets const pallets = metadata.asLatest.pallets.map(p => p.name.toString()); console.log('Available pallets:', pallets); // Get specific pallet info const systemPallet = metadata.asLatest.pallets.find(p => p.name.toString() === 'System'); console.log('System pallet calls:', systemPallet.calls.isSome ? 'Available' : 'None'); await api.disconnect(); ``` ```python def get_metadata(): url = 'https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'state_getMetadata', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] metadata_hex = get_metadata() print(f'Metadata length: {len(metadata_hex)} bytes') ``` ## Related Methods - [`state_getRuntimeVersion`](./state_getRuntimeVersion) - Get runtime version - [`state_getStorage`](./state_getStorage) - Query storage --- ## state_getRuntimeVersion - Bifrost RPC Method # state_getRuntimeVersion Returns the runtime version on Bifrost. ## Use Cases - **Version checking** - Verify runtime compatibility - **Upgrade detection** - Monitor for runtime upgrades on omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Client compatibility** - Ensure API compatibility ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash for historical version | ## Request ```json { "jsonrpc": "2.0", "method": "state_getRuntimeVersion", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getRuntimeVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const version = await api.rpc.state.getRuntimeVersion(); console.log('Spec name:', version.specName.toString()); console.log('Spec version:', version.specVersion.toNumber()); console.log('Impl version:', version.implVersion.toNumber()); await api.disconnect(); ``` ```python def get_runtime_version(): url = 'https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'state_getRuntimeVersion', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] version = get_runtime_version() print(f"Spec: {version['specName']} v{version['specVersion']}") ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata - [`system_version`](./system_version) - Get node version --- ## state_getStorage - Bifrost RPC Method # state_getStorage Returns a storage entry at a specific key on Bifrost. > **Why Bifrost?** Build on Polkadot's largest liquid staking appchain with 60% DOT LST market share and $125M+ TVL with first LST governance on OpenGov, 60% DOT market share, Hyperbridge ETH integration, and 500K DOT treasury support. ## Use Cases - **State queries** - Read on-chain storage values - **Account balances** - Query account data for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Pallet storage** - Access runtime storage items - **Historical state** - Query state at specific blocks ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `key` | `String` | Yes | Storage key (hex-encoded) | | `blockHash` | `String` | No | Block hash for historical query | ## Request ```json { "jsonrpc": "2.0", "method": "state_getStorage", "params": [""], "id": 1 } ``` ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getStorage", "params": [""], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query account balance const account = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const accountInfo = await api.query.system.account(account); console.log('Free balance:', accountInfo.data.free.toString()); // Query at specific block const blockHash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'; const historicalBalance = await api.query.system.account.at(blockHash, account); console.log('Historical balance:', historicalBalance.data.free.toString()); await api.disconnect(); ``` ```python def get_storage(key, block_hash=None): url = 'https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY' params = [key] if block_hash is None else [key, block_hash] payload = { 'jsonrpc': '2.0', 'method': 'state_getStorage', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] # Query :code storage (runtime wasm) storage_key = '' value = get_storage(storage_key) print(f'Storage value: {value[:66]}...' if value else 'None') ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata - [`state_getKeysPaged`](./state_getKeysPaged) - Enumerate storage keys --- ## state_queryStorageAt - Bifrost RPC Method # state_queryStorageAt Query multiple storage keys at a specific block on Bifrost. ## Use Cases - **Batch queries** - Efficiently query multiple storage items - **Snapshot state** - Get consistent multi-key state for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Data analysis** - Compare storage across blocks ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `keys` | `Array` | Yes | Array of storage keys | | `blockHash` | `String` | No | Block hash for query | ## Request ```json { "jsonrpc": "2.0", "method": "state_queryStorageAt", "params": [[""]], "id": 1 } ``` ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_queryStorageAt", "params": [[""]], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query multiple accounts at once const accounts = ['5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY']; const entries = await api.query.system.account.multi(accounts); entries.forEach((info, idx) => { console.log(`Account ${idx}: ${info.data.free.toString()}`); }); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Single storage query - [`state_getKeysPaged`](./state_getKeysPaged) - Enumerate keys --- ## system_chain - Bifrost RPC Method # system_chain Returns the chain name on Bifrost. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const chain = await api.rpc.system.chain(); console.log('Chain:', chain.toString()); await api.disconnect(); ``` ## Related Methods - [`system_name`](./system_name) - Get node implementation name - [`system_version`](./system_version) - Get node version --- ## system_health - Bifrost RPC Method # system_health Returns the health status of the Bifrost node. ## Use Cases - **Health checks** - Monitor node availability - **Load balancing** - Route traffic based on health for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **Sync status** - Verify node is synced ## Parameters This method accepts no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `peers` | `Number` | Connected peer count | | `isSyncing` | `Boolean` | Whether node is syncing | | `shouldHavePeers` | `Boolean` | Whether node should have peers | ## Request ```json { "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const health = await api.rpc.system.health(); console.log('Peers:', health.peers.toNumber()); console.log('Is syncing:', health.isSyncing.isTrue); await api.disconnect(); ``` ```python def get_health(): url = 'https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'system_health', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] health = get_health() print(f"Peers: {health['peers']}") print(f"Syncing: {health['isSyncing']}") ``` ## Related Methods - [`system_version`](./system_version) - Get node version - [`system_chain`](./system_chain) - Get chain name --- ## system_name - Bifrost RPC Method # system_name Returns the node implementation name on Bifrost. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_name", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_name", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const name = await api.rpc.system.name(); console.log('Node name:', name.toString()); await api.disconnect(); ``` ## Related Methods - [`system_version`](./system_version) - Get node version - [`system_chain`](./system_chain) - Get chain name --- ## system_properties - Bifrost RPC Method # system_properties Returns chain properties including token symbol and decimals on Bifrost. ## Use Cases - **Token formatting** - Get decimals and symbol for omnichain liquid staking (vDOT, vKSM, vGLMR, vMOVR, vASTR), cross-chain vToken governance, and DOT/ETH liquidity bridging - **UI configuration** - Configure wallets and dApps - **Address formatting** - Get SS58 prefix ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_properties", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_properties", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const props = await api.rpc.system.properties(); console.log('Token symbol:', props.tokenSymbol.toString()); console.log('Token decimals:', props.tokenDecimals.toString()); console.log('SS58 prefix:', props.ss58Format.toString()); await api.disconnect(); ``` ## Related Methods - [`system_chain`](./system_chain) - Get chain name - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## system_version - Bifrost RPC Method # system_version Returns the node implementation version on Bifrost. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_version", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_version", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bifrost-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const version = await api.rpc.system.version(); console.log('Version:', version.toString()); await api.disconnect(); ``` ## Related Methods - [`system_chain`](./system_chain) - Get chain name - [`state_getRuntimeVersion`](./state_getRuntimeVersion) - Get runtime version --- ## account_nextIndex - JSON-RPC Method export const S = substrateSamples['bittensor']; # account_nextIndex ## Description Return the next valid account nonce. Use to construct signed extrinsics and avoid “future proof” or “bad nonce” errors. Returns the next valid transaction index (nonce) for an account. Equivalent to `system_accountNextIndex`. ## Code Examples --- ## archive_v1_body - JSON-RPC Method export const S = substrateSamples['bittensor']; # archive_v1_body ## Description Query historical blocks, storage, and diffs via the archive service. Build fast historical analytics without re‑executing the chain. Returns a block body by height from the archive service. May be disabled on public RPC. ## Code Examples --- ## archive_v1_call - JSON-RPC Method export const S = substrateSamples['bittensor']; # archive_v1_call ## Description Query historical blocks, storage, and diffs via the archive service. Build fast historical analytics without re‑executing the chain. Performs runtime calls against archived state. Availability depends on node configuration. ## Code Examples --- ## archive_v1_finalizedHeight - JSON-RPC Method export const S = substrateSamples['bittensor']; # archive_v1_finalizedHeight ## Description Query historical blocks, storage, and diffs via the archive service. Build fast historical analytics without re‑executing the chain. Returns the latest finalized height in the archive. ## Code Examples --- ## archive_v1_genesisHash - JSON-RPC Method export const S = substrateSamples['bittensor']; # archive_v1_genesisHash ## Description Query historical blocks, storage, and diffs via the archive service. Build fast historical analytics without re‑executing the chain. Returns the genesis block hash reported by the archive service. ## Code Examples --- ## archive_v1_hashByHeight - JSON-RPC Method export const S = substrateSamples['bittensor']; # archive_v1_hashByHeight ## Description Query historical blocks, storage, and diffs via the archive service. Build fast historical analytics without re‑executing the chain. Returns the block hash for a block height. ## Code Examples --- ## archive_v1_header - JSON-RPC Method export const S = substrateSamples['bittensor']; # archive_v1_header ## Description Query historical blocks, storage, and diffs via the archive service. Build fast historical analytics without re‑executing the chain. Returns a block header for a given height. ## Code Examples --- ## archive_v1_stopStorage - JSON-RPC Method export const S = substrateSamples['bittensor']; # archive_v1_stopStorage ## Description Query historical blocks, storage, and diffs via the archive service. Build fast historical analytics without re‑executing the chain. Stops an archive storage streaming operation. ## Code Examples --- ## archive_v1_storage - JSON-RPC Method export const S = substrateSamples['bittensor']; # archive_v1_storage ## Description Query historical blocks, storage, and diffs via the archive service. Build fast historical analytics without re‑executing the chain. Reads storage at a key for a given block height from the archive. ## Code Examples --- ## archive_v1_storageDiff - JSON-RPC Method export const S = substrateSamples['bittensor']; # archive_v1_storageDiff ## Description Query historical blocks, storage, and diffs via the archive service. Build fast historical analytics without re‑executing the chain. Streams storage changes for keys over a range via archive. ## Code Examples --- ## archive_v1_storageDiff_stopStorageDiff - J... export const S = substrateSamples['bittensor']; # archive_v1_storageDiff_stopStorageDiff ## Description Query historical blocks, storage, and diffs via the archive service. Build fast historical analytics without re‑executing the chain. Stops an archive storage diff stream. ## Code Examples --- ## author_hasKey - JSON-RPC Method export const S = substrateSamples['bittensor']; # author_hasKey Checks if the node has a given public key in its keystore. Typically disabled on shared RPC providers. > Note: Expect an error or false on shared/public nodes. ## Code Examples --- ## author_pendingExtrinsics - Bittensor RPC Method # author_pendingExtrinsics Returns all pending extrinsics in the transaction pool on Bittensor. ## Use Cases - **Mempool monitoring** - Track pending transactions - **Transaction status** - Check if your transaction is pending for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Pool analysis** - Monitor network activity ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "author_pendingExtrinsics", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_pendingExtrinsics", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const pending = await api.rpc.author.pendingExtrinsics(); console.log('Pending extrinsics:', pending.length); pending.forEach((ext, idx) => { console.log(`${idx}: ${ext.method.section}.${ext.method.method}`); }); await api.disconnect(); ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction --- ## author_rotateKeys - Bittensor RPC Method # author_rotateKeys Generate a new set of session keys on Bittensor. This method creates fresh cryptographic keys for validator operations and stores them in the node's keystore. The returned keys must be registered on-chain via `session.setKeys`. ## Use Cases - **Validator setup** - Generate initial session keys for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Key rotation** - Periodically rotate keys for security best practices - **Recovery** - Generate new keys after potential key compromise ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | `Bytes` | Concatenated SCALE-encoded public keys for all session key types | ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_rotateKeys", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Generate new session keys const keys = await api.rpc.author.rotateKeys(); console.log('New session keys:', keys.toHex()); // These keys need to be registered on-chain: // api.tx.session.setKeys(keys, proof) await api.disconnect(); ``` ```python url = 'https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'author_rotateKeys', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json() if 'result' in result: session_keys = result['result'] print(f'New session keys: {session_keys}') print('Register these keys using session.setKeys extrinsic') else: print(f"Error: {result.get('error')}") ``` ## Validator Setup Workflow 1. **Generate keys** - Call `author_rotateKeys` on your validator node 2. **Register on-chain** - Submit `session.setKeys(keys, proof)` extrinsic 3. **Wait for session** - Keys become active in the next session 4. **Verify** - Check `session.nextKeys` storage ## Security Considerations - Only call this method on your own validator node - Session keys are stored in the node's keystore - Rotate keys periodically and after any security incident - Never expose this RPC method publicly ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit setKeys transaction - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - View pending transactions --- ## author_submitAndWatchExtrinsic - Bittensor RPC Method # author_submitAndWatchExtrinsic Submit a signed extrinsic to and subscribe to status updates. This WebSocket method provides real-time feedback on transaction progress from submission through finalization. ## Use Cases - **Transaction tracking** - Monitor extrinsic lifecycle for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **UI feedback** - Show users real-time transaction status - **Confirmation workflows** - Wait for specific finality level before proceeding ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `Bytes` | Yes | SCALE-encoded signed extrinsic | ## Returns Returns a subscription that emits `ExtrinsicStatus` updates: | Status | Description | |--------|-------------| | `future` | In future queue (nonce too high) | | `ready` | In ready queue, waiting for block | | `broadcast` | Broadcast to peers | | `inBlock` | Included in block (hash provided) | | `retracted` | Block retracted (reorg) | | `finalityTimeout` | Finality timeout | | `finalized` | Finalized in block (hash provided) | | `usurped` | Replaced by another extrinsic | | `dropped` | Dropped from pool | | `invalid` | Invalid extrinsic | ## Code Examples ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const keyring = new Keyring({ type: 'sr25519' }); // Create and sign a transfer const sender = keyring.addFromUri('//Alice'); const transfer = api.tx.balances.transferKeepAlive( '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 1000000000000n ); // Submit and watch const unsub = await transfer.signAndSend(sender, ({ status, events }) => { console.log(`Status: ${status.type}`); if (status.isInBlock) { console.log(`Included in block: ${status.asInBlock.toHex()}`); } if (status.isFinalized) { console.log(`Finalized in block: ${status.asFinalized.toHex()}`); unsub(); } }); ``` ```python async def submit_and_watch(signed_extrinsic_hex): uri = 'wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: # Submit and subscribe await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'author_submitAndWatchExtrinsic', 'params': [signed_extrinsic_hex], 'id': 1 })) # Get subscription ID response = json.loads(await ws.recv()) if 'error' in response: print(f"Error: {response['error']}") return sub_id = response['result'] print(f'Watching with subscription: {sub_id}') # Listen for status updates while True: message = json.loads(await ws.recv()) if 'params' in message: status = message['params']['result'] print(f"Status: {status}") # Check for finalization if isinstance(status, dict) and 'finalized' in status: print(f"Finalized in: {status['finalized']}") break # asyncio.run(submit_and_watch('0x...')) ``` ## Status Flow ``` ready → broadcast → inBlock → finalized ↘ retracted (if reorg) ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit without watching (fire-and-forget) - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - View transaction pool - [`payment_queryInfo`](./payment_queryInfo) - Estimate fees before submission --- ## author_submitExtrinsic - Bittensor RPC Method # author_submitExtrinsic Submit a signed extrinsic to Bittensor for inclusion in a block. ## Use Cases - **Transaction submission** - Broadcast signed transactions - **dApp interactions** - Execute on-chain operations for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Automated systems** - Submit programmatic transactions ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `String` | Yes | Hex-encoded signed extrinsic | ## Request ```json { "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": ["0x..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Transaction hash | ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": ["0x..."], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const keyring = new Keyring({ type: 'sr25519' }); const sender = keyring.addFromUri('//Alice'); // Build and sign transaction const transfer = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000); const hash = await transfer.signAndSend(sender); console.log('Transaction hash:', hash.toHex()); await api.disconnect(); ``` ## Related Methods - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - Get pending transactions - [`payment_queryInfo`](./payment_queryInfo) - Estimate fees --- ## beefy_getFinalizedHead - Bittensor RPC Method # beefy_getFinalizedHead Returns the block hash of the latest BEEFY-finalized block on Bittensor. BEEFY (Bridge Efficiency Enabling Finality Yielder) provides additional finality proofs optimized for light clients and bridges. ## Use Cases - **Cross-chain bridges** - Verify finality proofs for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Light clients** - Efficient finality verification without full GRANDPA proofs - **Trustless bridges** - Generate compact finality proofs for external chains ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | `Hash` | Block hash of the latest BEEFY-finalized block | ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "beefy_getFinalizedHead", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get BEEFY finalized head const beefyHead = await api.rpc.beefy.getFinalizedHead(); console.log('BEEFY finalized:', beefyHead.toHex()); // Compare with GRANDPA finalized const grandpaHead = await api.rpc.chain.getFinalizedHead(); console.log('GRANDPA finalized:', grandpaHead.toHex()); await api.disconnect(); ``` ```python url = 'https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'beefy_getFinalizedHead', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json() if 'result' in result: print(f"BEEFY finalized: {result['result']}") else: print(f"Error: {result.get('error')}") ``` ## BEEFY vs GRANDPA Finality | Aspect | GRANDPA | BEEFY | |--------|---------|-------| | **Purpose** | Primary finality | Bridge-optimized finality | | **Proof size** | Larger (full validator set) | Compact (aggregated signatures) | | **Latency** | Immediate | Slightly delayed | | **Use case** | On-chain finality | Cross-chain bridges | ## Availability BEEFY is enabled on relay chains and some parachains. If BEEFY is not enabled, this method will return an error. ## Related Methods - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - GRANDPA finalized head - [`grandpa_roundState`](./grandpa_roundState) - GRANDPA consensus state - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks --- ## chainHead_v1_body - JSON-RPC Method export const S = substrateSamples['bittensor']; # chainHead_v1_body ## Description Use the modern follow API to stream headers, bodies, and storage with cursors. Experimental and typically disabled on shared providers. Returns a block body within a follow operation. Experimental; may be disabled. ## Code Examples --- ## chainHead_v1_call - JSON-RPC Method export const S = substrateSamples['bittensor']; # chainHead_v1_call ## Description Use the modern follow API to stream headers, bodies, and storage with cursors. Experimental and typically disabled on shared providers. Performs runtime API calls tied to a follow operation. Experimental; may be disabled on public RPC. ## Code Examples --- ## chainHead_v1_continue - JSON-RPC Method export const S = substrateSamples['bittensor']; # chainHead_v1_continue ## Description Use the modern follow API to stream headers, bodies, and storage with cursors. Experimental and typically disabled on shared providers. Continues a follow operation using a cursor or operation ID. ## Code Examples --- ## chainHead_v1_follow - JSON-RPC Method export const S = substrateSamples['bittensor']; # chainHead_v1_follow Starts a follow operation to stream headers/storage with fine-grained control. Public RPCs may disable or return internal errors. ## Code Examples --- ## chainHead_v1_header - JSON-RPC Method export const S = substrateSamples['bittensor']; # chainHead_v1_header ## Description Use the modern follow API to stream headers, bodies, and storage with cursors. Experimental and typically disabled on shared providers. Returns a block header within a follow operation. Experimental; may be disabled. ## Code Examples --- ## chainHead_v1_stopOperation - JSON-RPC Method export const S = substrateSamples['bittensor']; # chainHead_v1_stopOperation ## Description Use the modern follow API to stream headers, bodies, and storage with cursors. Experimental and typically disabled on shared providers. Stops a follow operation by its operation ID. ## Code Examples --- ## chainHead_v1_storage - JSON-RPC Method export const S = substrateSamples['bittensor']; # chainHead_v1_storage ## Description Use the modern follow API to stream headers, bodies, and storage with cursors. Experimental and typically disabled on shared providers. Returns storage changes within a follow operation. Experimental; may be disabled. ## Code Examples --- ## chainHead_v1_unfollow - JSON-RPC Method export const S = substrateSamples['bittensor']; # chainHead_v1_unfollow ## Description Use the modern follow API to stream headers, bodies, and storage with cursors. Experimental and typically disabled on shared providers. Stops a follow operation. Provide the operation ID returned by `chainHead_v1_follow`. ## Code Examples --- ## chainSpec_v1_chainName - JSON-RPC Method export const S = substrateSamples['bittensor']; # chainSpec_v1_chainName ## Description Read static chain specification data such as chain name, ss58 properties, and genesis hash. Use this to configure clients (address format, token info) or verify you are talking to the expected network. Returns the chain name from the runtime's ChainSpec. ## Code Examples --- ## chainSpec_v1_genesisHash - JSON-RPC Method export const S = substrateSamples['bittensor']; # chainSpec_v1_genesisHash ## Description Read static chain specification data such as chain name, ss58 properties, and genesis hash. Use this to configure clients (address format, token info) or verify you are talking to the expected network. Returns the genesis block hash from the ChainSpec. ## Code Examples --- ## chainSpec_v1_properties - JSON-RPC Method export const S = substrateSamples['bittensor']; # chainSpec_v1_properties ## Description Read static chain specification data such as chain name, ss58 properties, and genesis hash. Use this to configure clients (address format, token info) or verify you are talking to the expected network. Returns chain properties as defined in the ChainSpec. ## Code Examples --- ## chain_getBlock - Bittensor RPC Method # chain_getBlock Retrieves complete block information from Bittensor, including the block header, extrinsics, and justifications. > **Why Bittensor?** Build on the decentralized AI network with $3.9B+ market cap powering 80+ AI subnets with Yuma Consensus for AI model evaluation, subnet-based specialization, dual Substrate+EVM support, and incentivized AI compute marketplace. ## Use Cases The `chain_getBlock` method is essential for: - **Block explorers** - Display complete block information - **Chain analysis** - Analyze block production patterns - **Transaction verification** - Confirm extrinsic inclusion for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Data indexing** - Build historical blockchain databases ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Hex-encoded block hash. If omitted, returns latest block | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getBlock", "params": ["0x2f0555cc76fc2840a25a6f3a0f0e6d0b1a6dd2e0cecc9e4c2e9e6f3a8d2e5c1b"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `block` | `Object` | Complete block data | | `block.header` | `Object` | Block header information | | `block.header.parentHash` | `String` | Hash of the parent block | | `block.header.number` | `String` | Block number (hex-encoded) | | `block.header.stateRoot` | `String` | Root of the state trie | | `block.header.extrinsicsRoot` | `String` | Root of the extrinsics trie | | `block.extrinsics` | `Array` | Array of extrinsics in the block | | `justifications` | `Array` | Block justifications (if available) | ## Code Examples ```bash # Get latest block curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": [], "id": 1 }' # Get specific block curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": ["0x2f0555cc76fc2840a25a6f3a0f0e6d0b1a6dd2e0cecc9e4c2e9e6f3a8d2e5c1b"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get latest block const latestHash = await api.rpc.chain.getBlockHash(); const latestBlock = await api.rpc.chain.getBlock(latestHash); console.log('Latest block:', { number: latestBlock.block.header.number.toNumber(), hash: latestHash.toHex(), extrinsicsCount: latestBlock.block.extrinsics.length }); // Get specific block const blockHash = '0x2f0555cc76fc2840a25a6f3a0f0e6d0b1a6dd2e0cecc9e4c2e9e6f3a8d2e5c1b'; const block = await api.rpc.chain.getBlock(blockHash); console.log('Block extrinsics:', block.block.extrinsics.length); await api.disconnect(); ``` ```python def get_block(block_hash=None): url = 'https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY' params = [block_hash] if block_hash else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getBlock', 'params': params, 'id': 1 } response = requests.post(url, json=payload) data = response.json() if 'error' in data: raise Exception(f"RPC Error: {data['error']}") return data['result'] # Get latest block latest_block = get_block() block_number = int(latest_block['block']['header']['number'], 16) print(f'Latest block number: {block_number}') # Get specific block specific_block = get_block('0x2f0555cc76fc2840a25a6f3a0f0e6d0b1a6dd2e0cecc9e4c2e9e6f3a8d2e5c1b') print(f"Extrinsics count: {len(specific_block['block']['extrinsics'])}") ``` ## Related Methods - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number - [`chain_getHeader`](./chain_getHeader) - Get block header only - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get finalized block hash --- ## chain_getBlockHash - Bittensor RPC Method # chain_getBlockHash Returns the block hash for a given block number on Bittensor. ## Use Cases - **Historical queries** - Convert block numbers to hashes - **Block navigation** - Navigate blockchain history for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Data indexing** - Build block number to hash mappings ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `Number` | No | Block number. If omitted, returns latest block hash | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getBlockHash", "params": [1000000], "id": 1 } ``` ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlockHash", "params": [1000000], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get hash for specific block number const blockNumber = 1000000; const blockHash = await api.rpc.chain.getBlockHash(blockNumber); console.log(`Block ${blockNumber} hash:`, blockHash.toHex()); await api.disconnect(); ``` ```python def get_block_hash(block_number=None): url = 'https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY' params = [block_number] if block_number is not None else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getBlockHash', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] block_hash = get_block_hash(1000000) print(f'Block hash: {block_hash}') ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get block by hash - [`chain_getHeader`](./chain_getHeader) - Get block header --- ## chain_getFinalizedHead - Bittensor RPC Method # chain_getFinalizedHead Returns the hash of the last finalized block on Bittensor. ## Use Cases - **Confirmed state** - Query state that cannot be reverted - **Transaction confirmation** - Verify transaction finality for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Safe checkpoints** - Use finalized blocks for critical operations ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const finalizedHash = await api.rpc.chain.getFinalizedHead(); console.log('Finalized block hash:', finalizedHash.toHex()); // Get finalized block details const block = await api.rpc.chain.getBlock(finalizedHash); console.log('Finalized block number:', block.block.header.number.toNumber()); await api.disconnect(); ``` ```python def get_finalized_head(): url = 'https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'chain_getFinalizedHead', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] finalized_hash = get_finalized_head() print(f'Finalized block hash: {finalized_hash}') ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get block by hash - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number --- ## chain_getHead - JSON-RPC Method export const S = substrateSamples['bittensor']; # chain_getHead ## Description Return the best (non-finalized) block hash. Use for low‑latency reads when finality is not required. Returns the block hash of the current best block (not necessarily finalized). ## Code Examples --- ## chain_getHeader - Bittensor RPC Method # chain_getHeader Returns the block header for a given hash on Bittensor. ## Use Cases - **Lightweight queries** - Get header without full block data - **Chain synchronization** - Track block production for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Parent chain navigation** - Follow parentHash links ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash. If omitted, returns latest header | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getHeader", "params": ["0x2f0555cc76fc2840a25a6f3a0f0e6d0b1a6dd2e0cecc9e4c2e9e6f3a8d2e5c1b"], "id": 1 } ``` ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getHeader", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get latest header const header = await api.rpc.chain.getHeader(); console.log('Block number:', header.number.toNumber()); console.log('Parent hash:', header.parentHash.toHex()); await api.disconnect(); ``` ```python def get_header(block_hash=None): url = 'https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY' params = [block_hash] if block_hash else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getHeader', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] header = get_header() print(f"Block number: {int(header['number'], 16)}") ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get full block with extrinsics - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number --- ## chain_getRuntimeVersion - JSON-RPC Method export const S = substrateSamples['bittensor']; # chain_getRuntimeVersion Returns the current runtime specification and transaction version for the node. As a developer, you use this to: - Detect runtime upgrades and adjust clients accordingly (e.g., refresh metadata). - Ensure your transaction building/signing logic matches the node’s transactionVersion. - Gate feature flags or migrations based on specName/specVersion (e.g., API changes between releases). ## Code Examples --- ## chain_subscribeAllHeads - JSON-RPC Method export const S = substrateSamples['bittensor']; # chain_subscribeAllHeads ## Description Subscribe to real‑time chain updates over WebSocket. Use to stream new or finalized heads or runtime version changes into your app. Broadcasts every imported block header (finalized and non-finalized). Requires WebSocket. --- ## chain_subscribeFinalizedHeads - Bittensor RPC Method # chain_subscribeFinalizedHeads Subscribe to receive notifications when blocks are finalized on Bittensor. Finalized blocks are guaranteed to never be reverted, making this essential for applications requiring strong consistency. ## Use Cases - **Exchange deposits** - Only credit funds after finalization for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Bridge operations** - Wait for finality before cross-chain transfers - **Critical state changes** - Ensure irreversibility for important transactions ## Parameters This method takes no parameters. ## Returns Returns a subscription ID. The subscription emits `Header` objects for each finalized block: | Field | Type | Description | |-------|------|-------------| | `parentHash` | `Hash` | Parent block hash | | `number` | `BlockNumber` | Block number | | `stateRoot` | `Hash` | State trie root hash | | `extrinsicsRoot` | `Hash` | Extrinsics trie root hash | | `digest` | `Digest` | Block digest with consensus logs | ## Code Examples ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Subscribe to finalized heads const unsubscribe = await api.rpc.chain.subscribeFinalizedHeads((header) => { console.log(`Finalized block #${header.number}`); console.log(` Hash: ${header.hash.toHex()}`); // Safe to consider this block permanent processConfirmedBlock(header); }); // Later: unsubscribe() ``` ```python async def subscribe_finalized(): uri = 'wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'chain_subscribeFinalizedHeads', 'params': [], 'id': 1 })) response = json.loads(await ws.recv()) sub_id = response['result'] print(f'Subscribed to finalized heads: {sub_id}') while True: message = json.loads(await ws.recv()) if 'params' in message: header = message['params']['result'] block_num = int(header['number'], 16) print(f"Finalized: #{block_num}") asyncio.run(subscribe_finalized()) ``` ## Finality Lag Finalized blocks typically lag behind the best block by a few blocks due to GRANDPA consensus requirements. This is normal and ensures Byzantine fault tolerance. ## Related Methods - [`chain_subscribeNewHeads`](./chain_subscribeNewHeads) - Subscribe to all new blocks (not just finalized) - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get current finalized block hash - [`grandpa_roundState`](./grandpa_roundState) - Monitor GRANDPA consensus progress --- ## chain_subscribeNewHeads - Bittensor RPC Method # chain_subscribeNewHeads Subscribe to receive notifications when new block headers are produced on Bittensor. This WebSocket subscription provides real-time updates for each new block. ## Use Cases - **Block monitoring** - Track new blocks in real-time for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Event indexing** - Trigger processing when new blocks arrive - **Chain synchronization** - Keep external systems in sync with the chain ## Parameters This method takes no parameters. ## Returns Returns a subscription ID. The subscription emits `Header` objects for each new block: | Field | Type | Description | |-------|------|-------------| | `parentHash` | `Hash` | Parent block hash | | `number` | `BlockNumber` | Block number | | `stateRoot` | `Hash` | State trie root hash | | `extrinsicsRoot` | `Hash` | Extrinsics trie root hash | | `digest` | `Digest` | Block digest with consensus logs | ## Code Examples ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Subscribe to new heads const unsubscribe = await api.rpc.chain.subscribeNewHeads((header) => { console.log(`New block #${header.number}`); console.log(` Hash: ${header.hash.toHex()}`); console.log(` Parent: ${header.parentHash.toHex()}`); console.log(` State root: ${header.stateRoot.toHex()}`); }); // Later: unsubscribe() ``` ```python async def subscribe_new_heads(): uri = 'wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: # Subscribe to new heads await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'chain_subscribeNewHeads', 'params': [], 'id': 1 })) # Get subscription ID response = json.loads(await ws.recv()) sub_id = response['result'] print(f'Subscribed with ID: {sub_id}') # Listen for new headers while True: message = json.loads(await ws.recv()) if 'params' in message: header = message['params']['result'] print(f"Block #{int(header['number'], 16)}") print(f" Hash: {header['parentHash']}") asyncio.run(subscribe_new_heads()) ``` ## Subscription vs Polling | Approach | Latency | Resource Usage | Use Case | |----------|---------|----------------|----------| | `subscribeNewHeads` | Immediate | Low (push-based) | Real-time monitoring | | Polling `getHeader` | Block time + poll interval | Higher (repeated requests) | Simple integrations | ## Related Methods - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks only - [`chain_getHeader`](./chain_getHeader) - Get a specific block header - [`chain_getBlock`](./chain_getBlock) - Get full block with extrinsics --- ## chain_subscribeRuntimeVersion - JSON-RPC M... export const S = substrateSamples['bittensor']; # chain_subscribeRuntimeVersion ## Description Subscribe to real‑time chain updates over WebSocket. Use to stream new or finalized heads or runtime version changes into your app. Emits runtime version updates. Requires WebSocket. --- ## chain_unsubscribeAllHeads - JSON-RPC Method export const S = substrateSamples['bittensor']; # chain_unsubscribeAllHeads ## Description Cancel a previously created WebSocket subscription. Always unsubscribe to avoid leaking server resources in long‑running apps. Cancels a subscription started with `chain_subscribeAllHeads`. Provide the numeric subscription ID. --- ## chain_unsubscribeFinalisedHeads - JSON-RPC... export const S = substrateSamples['bittensor']; # chain_unsubscribeFinalisedHeads British spelling variant alias for unsubscribing from finalized heads. Provide subscription ID. --- ## chain_unsubscribeFinalizedHeads - JSON-RPC... export const S = substrateSamples['bittensor']; # chain_unsubscribeFinalizedHeads ## Description Cancel a previously created WebSocket subscription. Always unsubscribe to avoid leaking server resources in long‑running apps. Cancels a subscription started with `chain_subscribeFinalizedHeads`. --- ## chain_unsubscribeNewHead - JSON-RPC Method export const S = substrateSamples['bittensor']; # chain_unsubscribeNewHead ## Description Cancel a previously created WebSocket subscription. Always unsubscribe to avoid leaking server resources in long‑running apps. Cancels a subscription started with `chain_subscribeNewHead` (singular alias). Provide subscription ID. --- ## chain_unsubscribeNewHeads - JSON-RPC Method export const S = substrateSamples['bittensor']; # chain_unsubscribeNewHeads ## Description Cancel a previously created WebSocket subscription. Always unsubscribe to avoid leaking server resources in long‑running apps. Cancels a subscription started with `chain_subscribeNewHeads`. --- ## chain_unsubscribeRuntimeVersion - JSON-RPC... export const S = substrateSamples['bittensor']; # chain_unsubscribeRuntimeVersion ## Description Cancel a previously created WebSocket subscription. Always unsubscribe to avoid leaking server resources in long‑running apps. Cancels a subscription started with `chain_subscribeRuntimeVersion`. --- ## childstate_getKeys - JSON-RPC Method export const S = substrateSamples['bittensor']; # childstate_getKeys ## Description Read from child tries (nested storage) including listing keys and fetching values. Useful for pallets that isolate state in child trees. Returns child storage keys for a given child storage root and key prefix. ## Code Examples --- ## childstate_getKeysPaged - JSON-RPC Method export const S = substrateSamples['bittensor']; # childstate_getKeysPaged ## Description Read from child tries (nested storage) including listing keys and fetching values. Useful for pallets that isolate state in child trees. Returns child storage keys for a given child root and key prefix, paginated. ## Code Examples --- ## childstate_getKeysPagedAt - JSON-RPC Method export const S = substrateSamples['bittensor']; # childstate_getKeysPagedAt ## Description Read from child tries (nested storage) including listing keys and fetching values. Useful for pallets that isolate state in child trees. Returns child storage keys at a given block hash. ## Code Examples --- ## childstate_getStorage - JSON-RPC Method export const S = substrateSamples['bittensor']; # childstate_getStorage ## Description Read from child tries (nested storage) including listing keys and fetching values. Useful for pallets that isolate state in child trees. Returns the SCALE-encoded value for a child storage key. ## Code Examples --- ## childstate_getStorageEntries - JSON-RPC Me... export const S = substrateSamples['bittensor']; # childstate_getStorageEntries ## Description Read from child tries (nested storage) including listing keys and fetching values. Useful for pallets that isolate state in child trees. Returns multiple child storage entries for the specified keys. ## Code Examples --- ## childstate_getStorageHash - JSON-RPC Method export const S = substrateSamples['bittensor']; # childstate_getStorageHash ## Description Read from child tries (nested storage) including listing keys and fetching values. Useful for pallets that isolate state in child trees. Returns the storage hash for a child storage key. ## Code Examples --- ## childstate_getStorageSize - JSON-RPC Method export const S = substrateSamples['bittensor']; # childstate_getStorageSize ## Description Read from child tries (nested storage) including listing keys and fetching values. Useful for pallets that isolate state in child trees. Returns the length (in bytes) of a child storage value. ## Code Examples --- ## debug_getBadBlocks - JSON-RPC Method export const S = substrateSamples['bittensor']; # debug_getBadBlocks ## Description Interact with Substrate JSON‑RPC. This method is commonly used to build reliable indexers, developer tooling, and responsive UIs. Lists problematic blocks seen by the node. Often disabled on public RPC. ## Code Examples --- ## debug_getRawBlock - JSON-RPC Method export const S = substrateSamples['bittensor']; # debug_getRawBlock ## Description Fetch raw SCALE‑encoded headers, blocks, or receipts for deep debugging or tooling. Usually disabled on public RPC. Returns the raw SCALE-encoded block data for a given hash. ## Code Examples --- ## debug_getRawHeader - JSON-RPC Method export const S = substrateSamples['bittensor']; # debug_getRawHeader ## Description Fetch raw SCALE‑encoded headers, blocks, or receipts for deep debugging or tooling. Usually disabled on public RPC. Returns the raw SCALE-encoded header data for a given hash. ## Code Examples --- ## debug_getRawReceipts - JSON-RPC Method export const S = substrateSamples['bittensor']; # debug_getRawReceipts ## Description Fetch raw SCALE‑encoded headers, blocks, or receipts for deep debugging or tooling. Usually disabled on public RPC. Returns raw receipts for a block. Applies to Frontier EVM context. ## Code Examples --- ## debug_getRawTransaction - JSON-RPC Method export const S = substrateSamples['bittensor']; # debug_getRawTransaction ## Description Fetch raw SCALE‑encoded headers, blocks, or receipts for deep debugging or tooling. Usually disabled on public RPC. Returns raw transaction bytes for a given transaction hash in the EVM layer. ## Code Examples --- ## delegateInfo_getDelegate - JSON-RPC Method export const S = substrateSamples['bittensor']; # delegateInfo_getDelegate ## Description Bittensor delegation data: delegates and who delegated to whom. Use to show staking/delegation relationships in UIs. Returns SCALE-encoded information for a specific delegate. ## Code Examples --- ## delegateInfo_getDelegated - JSON-RPC Method export const S = substrateSamples['bittensor']; # delegateInfo_getDelegated ## Description Bittensor delegation data: delegates and who delegated to whom. Use to show staking/delegation relationships in UIs. Returns SCALE-encoded information about delegations to a given account. ## Code Examples --- ## delegateInfo_getDelegates - JSON-RPC Method export const S = substrateSamples['bittensor']; # delegateInfo_getDelegates Returns SCALE-encoded delegate list. > The output is a byte array (SCALE). Use Bittensor runtime types to decode. ## Code Examples --- ## eth_accounts - Bittensor RPC Method # eth_accounts Returns a list of addresses owned by the client on Bittensor. > **Why Bittensor?** Build on the decentralized AI network with $3.9B+ market cap powering 80+ AI subnets with Yuma Consensus for AI model evaluation, subnet-based specialization, dual Substrate+EVM support, and incentivized AI compute marketplace. ## Important Note On public RPC endpoints like Dwellir, `eth_accounts` returns an empty array because the node does not hold any private keys. This method is primarily useful for: - Local development nodes (Ganache, Hardhat, Anvil) - Private nodes with managed accounts - Wallet provider connections (MetaMask injects accounts) ## When to Use This Method `eth_accounts` is relevant for AI/ML developers, subnet operators, and teams building decentralized machine learning applications in specific scenarios: - **Development Testing** — Retrieve test accounts from local nodes - **Wallet Detection** — Check if a wallet provider has connected accounts - **Client Verification** — Confirm node account access capabilities ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `Array` | List of 20-byte account addresses owned by the client | **Return format**: Array of `0x` prefixed hexadecimal addresses (typically empty for public nodes) ## Request ```json { "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 } ``` ## Response ### Successful Response (Public Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [] } ``` ### Successful Response (Local Development Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [ "0x407d73d8a49eeb85d32cf465507dd71d507100c1", "0x85d32cf465507dd71d507100c1407d73d8a49eeb" ] } ``` ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_accounts', params: [], id: 1 }) }); const { result } = await response.json(); console.log('Accounts:', result); // Using ethers.js const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const accounts = await provider.listAccounts(); console.log('Accounts:', accounts); ``` ```python def get_accounts(): response = requests.post( 'https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_accounts', 'params': [], 'id': 1 } ) return response.json()['result'] accounts = get_accounts() print(f'Accounts: {accounts}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY')) print(f'Accounts: {w3.eth.accounts}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/rpc" ) func main() { client, err := rpc.Dial("https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } var accounts []string err = client.CallContext(context.Background(), &accounts, "eth_accounts") if err != nil { log.Fatal(err) } fmt.Printf("Accounts: %v\n", accounts) } ``` ## Common Use Cases ### 1. Development Environment Detection Check if running against a development node with test accounts: ```javascript async function isDevEnvironment(provider) { const accounts = await provider.listAccounts(); return accounts.length > 0; } const isDev = await isDevEnvironment(provider); if (isDev) { console.log('Development environment detected'); } ``` ### 2. Wallet Connection Check Verify wallet provider has connected accounts: ```javascript async function checkWalletConnection() { if (typeof window.ethereum === 'undefined') { return { connected: false, reason: 'No wallet detected' }; } const accounts = await window.ethereum.request({ method: 'eth_accounts' }); return { connected: accounts.length > 0, accounts: accounts }; } ``` ### 3. Fallback Account Selection Use first available account or request connection: ```javascript async function getActiveAccount() { // Check existing connections let accounts = await window.ethereum.request({ method: 'eth_accounts' }); // Request connection if no accounts if (accounts.length === 0) { accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); } return accounts[0] || null; } ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32601 | Method not found | Node may not support this method | | -32603 | Internal error | Retry with exponential backoff | ```javascript async function safeGetAccounts(provider) { try { const accounts = await provider.listAccounts(); return { success: true, accounts }; } catch (error) { if (error.code === -32601) { console.warn('eth_accounts not supported on this node'); return { success: false, accounts: [], reason: 'unsupported' }; } throw error; } } ``` ## Related Methods - [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102) — Request wallet connection (browser wallets) - [`eth_getBalance`](./eth_getBalance) — Get account balance - [`eth_getTransactionCount`](./eth_getTransactionCount) — Get account nonce --- ## eth_blockNumber - Bittensor RPC Method # eth_blockNumber Returns the number of the most recent block on Bittensor. > **Why Bittensor?** Build on the decentralized AI network with $3.9B+ market cap powering 80+ AI subnets with Yuma Consensus for AI model evaluation, subnet-based specialization, dual Substrate+EVM support, and incentivized AI compute marketplace. ## When to Use This Method `eth_blockNumber` is fundamental for AI/ML developers, subnet operators, and teams building decentralized machine learning applications: - **Syncing Applications** — Keep your dApp in sync with the latest Bittensor blockchain state - **Transaction Monitoring** — Verify confirmations by comparing block numbers - **Event Filtering** — Set the correct block range for querying logs on decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Health Checks** — Monitor node connectivity and sync status ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `QUANTITY` | Hexadecimal string representing the current block number | **Return format**: `0x` prefixed hexadecimal (e.g., `0x5BAD55` = 6,008,149 in decimal) ## Request ```json { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } ``` ## Response ### Successful Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5BAD55" } ``` ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error" } } ``` ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }) }); const { result } = await response.json(); const blockNumber = parseInt(result, 16); console.log('Bittensor block:', blockNumber); // Using ethers.js const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const blockNumber = await provider.getBlockNumber(); console.log('Bittensor block:', blockNumber); ``` ```python def get_block_number(): response = requests.post( 'https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_blockNumber', 'params': [], 'id': 1 } ) result = response.json()['result'] return int(result, 16) block_number = get_block_number() print(f'Bittensor block: {block_number}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY')) print(f'Bittensor block: {w3.eth.block_number}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockNumber, err := client.BlockNumber(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Bittensor block: %d\n", blockNumber) } ``` ## Common Use Cases ### 1. Block Confirmation Counter Monitor transaction confirmations on Bittensor: ```javascript async function getConfirmations(provider, txHash) { const tx = await provider.getTransaction(txHash); if (!tx || !tx.blockNumber) return 0; const currentBlock = await provider.getBlockNumber(); return currentBlock - tx.blockNumber + 1; } // Wait for specific confirmations async function waitForConfirmations(provider, txHash, confirmations = 6) { let currentConfirmations = 0; while (currentConfirmations < confirmations) { currentConfirmations = await getConfirmations(provider, txHash); console.log(`Confirmations: ${currentConfirmations}/${confirmations}`); await new Promise(r => setTimeout(r, 2000)); } return true; } ``` ### 2. Event Log Filtering Query events from recent blocks on Bittensor: ```javascript async function getRecentEvents(provider, contract, eventName, blockRange = 100) { const currentBlock = await provider.getBlockNumber(); const fromBlock = currentBlock - blockRange; const filter = contract.filters[eventName](); const events = await contract.queryFilter(filter, fromBlock, currentBlock); return events; } ``` ### 3. Node Health Monitoring Check if your Bittensor node is synced: ```javascript async function checkNodeHealth(provider) { try { const blockNumber = await provider.getBlockNumber(); const block = await provider.getBlock(blockNumber); const now = Date.now() / 1000; const blockAge = now - block.timestamp; if (blockAge > 60) { console.warn(`Node may be behind. Last block was ${blockAge}s ago`); return false; } console.log(`Node healthy. Latest block: ${blockNumber}`); return true; } catch (error) { console.error('Node unreachable:', error); return false; } } ``` ## Performance Optimization ### Caching Strategy Cache block numbers to reduce API calls: ```javascript class BlockNumberCache { constructor(ttl = 2000) { this.cache = null; this.timestamp = 0; this.ttl = ttl; } async get(provider) { const now = Date.now(); if (this.cache && (now - this.timestamp) < this.ttl) { return this.cache; } this.cache = await provider.getBlockNumber(); this.timestamp = now; return this.cache; } invalidate() { this.cache = null; this.timestamp = 0; } } const blockCache = new BlockNumberCache(); ``` ### Batch Requests Combine with other calls for efficiency: ```javascript const batch = [ { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }, { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 }, { jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 } ]; const response = await fetch('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await response.json(); ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32603 | Internal error | Retry with exponential backoff | | -32005 | Rate limit exceeded | Implement rate limiting client-side | | -32000 | Execution reverted | Check node sync status | ```javascript async function safeGetBlockNumber(provider, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await provider.getBlockNumber(); } catch (error) { if (error.code === -32005) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } else if (i === maxRetries - 1) { throw error; } } } } ``` ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) — Get full block details by number - [`eth_getBlockByHash`](./eth_getBlockByHash) — Get block details by hash - [`eth_syncing`](./eth_syncing) — Check if node is still syncing --- ## eth_call - Bittensor RPC Method # eth_call Executes a new message call immediately without creating a transaction on Bittensor. Used for reading smart contract state. > **Why Bittensor?** Build on the decentralized AI network with $3.9B+ market cap powering 80+ AI subnets with Yuma Consensus for AI model evaluation, subnet-based specialization, dual Substrate+EVM support, and incentivized AI compute marketplace. ## Use Cases The `eth_call` method is essential for: - **Reading contract state** - Query view/pure functions - **Simulating transactions** - Test execution without gas costs - **DeFi integrations** - Check prices, balances, allowances for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Complex queries** - Execute multi-step contract logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | 20-byte address executing the call | | `to` | `DATA` | Yes | 20-byte contract address | | `gas` | `QUANTITY` | No | Gas limit for the call | | `gasPrice` | `QUANTITY` | No | Gas price in wei | | `value` | `QUANTITY` | No | Value to send in wei | | `data` | `DATA` | Yes | Encoded function call data | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_call", "params": [ { "to": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "data": "0x70a08231000000000000000000000000" }, "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | The return value of the executed contract function | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000" } ``` ## Code Examples ```bash # Call ERC20 balanceOf function curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{ "to": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "data": "0x70a08231000000000000000000000000" }, "latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); // ERC20 ABI for common functions const ERC20_ABI = [ "function balanceOf(address owner) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function totalSupply() view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)" ]; // Read ERC20 token balance async function getTokenBalance(tokenAddress, walletAddress) { const contract = new Contract(tokenAddress, ERC20_ABI, provider); const balance = await contract.balanceOf(walletAddress); const decimals = await contract.decimals(); const symbol = await contract.symbol(); return { raw: balance.toString(), formatted: (Number(balance) / Math.pow(10, decimals)).toFixed(4), symbol: symbol }; } // Direct eth_call async function directCall(to, data) { const result = await provider.call({ to, data }); return result; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY')) def get_erc20_balance(token_address, wallet_address): # balanceOf(address) selector function_signature = "balanceOf(address)" function_selector = w3.keccak(text=function_signature)[:4].hex() # Encode address parameter encoded_address = wallet_address[2:].lower().zfill(64) data = function_selector + encoded_address # Make the call result = w3.eth.call({ 'to': token_address, 'data': data }) return int(result.hex(), 16) balance = get_erc20_balance( '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY' ) print(f'Balance: {balance}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY") data := common.FromHex("0x70a08231000000000000000000000000") msg := ethereum.CallMsg{ To: &contractAddress, Data: data, } result, err := client.CallContract(context.Background(), msg, nil) if err != nil { log.Fatal(err) } fmt.Printf("Result: 0x%x\n", result) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Contract function reverted | | -32602 | Invalid parameters | Invalid data encoding | | -32015 | VM execution error | Contract logic error | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas for transaction - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send actual transaction --- ## eth_chainId - Bittensor RPC Method # eth_chainId Returns the chain ID used for transaction signing on Bittensor. > **Why Bittensor?** Build on the decentralized AI network with $3.9B+ market cap powering 80+ AI subnets with Yuma Consensus for AI model evaluation, subnet-based specialization, dual Substrate+EVM support, and incentivized AI compute marketplace. ## Use Cases The `eth_chainId` method is essential for: - **Transaction signing** - Ensure transactions are signed for the correct network - **Network verification** - Confirm connection to the expected chain - **Multi-chain apps** - Handle different networks programmatically - **Wallet integration** - Validate network before transactions ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Chain ID in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1" } ``` ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const network = await provider.getNetwork(); console.log('Chain ID:', network.chainId); // Verify network before transaction async function verifyNetwork(expectedChainId) { const network = await provider.getNetwork(); if (network.chainId !== BigInt(expectedChainId)) { throw new Error(`Wrong network. Expected ${expectedChainId}, got ${network.chainId}`); } return true; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY')) chain_id = w3.eth.chain_id print(f'Chain ID: {chain_id}') # Verify network def verify_network(expected_chain_id): chain_id = w3.eth.chain_id if chain_id != expected_chain_id: raise ValueError(f'Wrong network. Expected {expected_chain_id}, got {chain_id}') return True ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } chainID, err := client.ChainID(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Chain ID: %d\n", chainID) } ``` ## Related Methods - [`net_version`](./net_version) - Get network version - [`eth_syncing`](./eth_syncing) - Check sync status --- ## eth_coinbase - Get coinbase address(Bittensor) # eth_coinbase Get coinbase address on the Bittensor network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_coinbase](https://ethereum.org/developers/docs/apis/json-rpc/#eth_coinbase) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_coinbase", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_coinbase', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Bittensor documentation](/docs/bittensor).* --- ## eth_estimateGas - Bittensor RPC Method # eth_estimateGas Estimates the gas necessary to execute a transaction on Bittensor. > **Why Bittensor?** Build on the decentralized AI network with $3.9B+ market cap powering 80+ AI subnets with Yuma Consensus for AI model evaluation, subnet-based specialization, dual Substrate+EVM support, and incentivized AI compute marketplace. ## Use Cases The `eth_estimateGas` method is essential for: - **Transaction preparation** - Set appropriate gas limits - **Cost estimation** - Calculate transaction costs before sending - **Error detection** - Identify reverts before spending gas - **DeFi operations** - Estimate costs for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | Sender address | | `to` | `DATA` | No | Recipient address | | `gas` | `QUANTITY` | No | Gas limit | | `gasPrice` | `QUANTITY` | No | Gas price | | `value` | `QUANTITY` | No | Value in wei | | `data` | `DATA` | No | Transaction data | ## Request ```json { "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "to": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "value": "0x1" }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Estimated gas amount in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5208" } ``` **Note**: `0x5208` = 21000 gas (standard ETH transfer) ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "to": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "value": "0x1" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); // Estimate simple transfer async function estimateTransfer(to, value) { const gasEstimate = await provider.estimateGas({ to: to, value: parseEther(value) }); console.log('Estimated gas:', gasEstimate.toString()); return gasEstimate; } // Estimate contract call async function estimateContractCall(contract, method, args) { const gasEstimate = await contract[method].estimateGas(...args); console.log('Estimated gas:', gasEstimate.toString()); // Add 20% buffer for safety return gasEstimate * 120n / 100n; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY')) def estimate_transfer(to, value_in_ether): gas_estimate = w3.eth.estimate_gas({ 'to': to, 'value': w3.to_wei(value_in_ether, 'ether') }) print(f'Estimated gas: {gas_estimate}') return gas_estimate def estimate_contract_call(contract, method, args): func = getattr(contract.functions, method) gas_estimate = func(*args).estimate_gas() # Add 20% buffer return int(gas_estimate * 1.2) # Estimate simple transfer gas = estimate_transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 0.1) ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } toAddress := common.HexToAddress("5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY") msg := ethereum.CallMsg{ To: &toAddress, Value: big.NewInt(1000000000000000000), } gasLimit, err := client.EstimateGas(context.Background(), msg) if err != nil { log.Fatal(err) } fmt.Printf("Estimated gas: %d\n", gasLimit) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Transaction would fail | | -32602 | Invalid params | Invalid transaction parameters | **Tip**: If estimation fails, the transaction would likely revert if sent. ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_feeHistory - Bittensor RPC Method # eth_feeHistory Returns historical gas information on Bittensor for fee estimation. ## Use Cases - **Fee prediction** - Estimate future gas prices based on history - **Gas analytics** - Analyze fee trends over time - **Optimal timing** - Find best times for transactions on decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockCount` | `QUANTITY` | Yes | Number of blocks in the range | | `newestBlock` | `QUANTITY\|TAG` | Yes | Highest block of the range | | `rewardPercentiles` | `Array` | Yes | Percentiles to sample for priority fees | ## Request ```json { "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const feeHistory = await provider.send('eth_feeHistory', ['0xa', 'latest', [25, 50, 75]]); console.log('Base fees:', feeHistory.baseFeePerGas.map(f => formatUnits(f, 'gwei'))); console.log('Reward (25th percentile):', feeHistory.reward.map(r => formatUnits(r[0], 'gwei'))); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY')) fee_history = w3.eth.fee_history(10, 'latest', [25, 50, 75]) print(f'Base fees: {[w3.from_wei(f, "gwei") for f in fee_history["baseFeePerGas"]]}') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee --- ## eth_gasPrice - Bittensor RPC Method # eth_gasPrice Returns the current gas price on Bittensor in wei. > **Why Bittensor?** Build on the decentralized AI network with $3.9B+ market cap powering 80+ AI subnets with Yuma Consensus for AI model evaluation, subnet-based specialization, dual Substrate+EVM support, and incentivized AI compute marketplace. ## Use Cases The `eth_gasPrice` method is essential for: - **Transaction pricing** - Set appropriate gas prices - **Cost estimation** - Calculate transaction costs before sending - **Gas monitoring** - Track network congestion - **DeFi operations** - Optimize costs for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Current gas price in wei (hexadecimal) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x3b9aca00" } ``` **Note**: `0x3b9aca00` = 1 Gwei (1,000,000,000 wei) ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); const gasPrice = feeData.gasPrice; console.log('Gas Price:', formatUnits(gasPrice, 'gwei'), 'Gwei'); // Calculate transaction cost async function estimateTransactionCost(gasLimit) { const feeData = await provider.getFeeData(); const cost = feeData.gasPrice * BigInt(gasLimit); return formatUnits(cost, 'ether'); } const cost = await estimateTransactionCost(21000); console.log('Transfer cost:', cost, 'ETH'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY')) gas_price = w3.eth.gas_price print(f'Gas Price: {w3.from_wei(gas_price, "gwei")} Gwei') # Calculate transaction cost def estimate_transaction_cost(gas_limit): gas_price = w3.eth.gas_price cost = gas_price * gas_limit return w3.from_wei(cost, 'ether') cost = estimate_transaction_cost(21000) print(f'Transfer cost: {cost} ETH') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } gasPrice, err := client.SuggestGasPrice(context.Background()) if err != nil { log.Fatal(err) } // Convert to Gwei gwei := new(big.Float).Quo( new(big.Float).SetInt(gasPrice), big.NewFloat(1e9), ) fmt.Printf("Gas Price: %f Gwei\n", gwei) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32603 | Internal error | Node error | ## Related Methods - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee (EIP-1559) - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas needed --- ## eth_getBalance - Bittensor RPC Method # eth_getBalance Returns the balance of a given address on Bittensor. > **Why Bittensor?** Build on the decentralized AI network with $3.9B+ market cap powering 80+ AI subnets with Yuma Consensus for AI model evaluation, subnet-based specialization, dual Substrate+EVM support, and incentivized AI compute marketplace. ## Use Cases The `eth_getBalance` method is essential for: - **Wallet applications** - Display user balances - **Transaction validation** - Check if account has sufficient funds - **DeFi applications** - Monitor collateral and liquidity for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Account monitoring** - Track balance changes over time ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address to check balance for | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Integer of the current balance in wei (hexadecimal) | **Note**: 1 native token = 10^18 wei. Convert using `balance / 10^18`. ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1a055690d9db80000" } ``` ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const balanceWei = await provider.getBalance(address); const balance = formatEther(balanceWei); console.log(`Balance: ${balance}`); // Get balance at specific block const historicalBalance = await provider.getBalance(address, 1000000); console.log(`Historical balance: ${formatEther(historicalBalance)}`); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY' balance_wei = w3.eth.get_balance(address) balance = w3.from_wei(balance_wei, 'ether') print(f'Balance: {balance}') # Get balance at specific block historical_balance = w3.eth.get_balance(address, block_identifier=1000000) print(f'Historical balance: {w3.from_wei(historical_balance, "ether")}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY") balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } // Convert to ether fbalance := new(big.Float).SetInt(balance) ethValue := new(big.Float).Quo(fbalance, big.NewFloat(1e18)) fmt.Printf("Balance: %f\n", ethValue) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid address format or block parameter | | -32000 | Execution error | Node execution error | ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_getTransactionCount`](./eth_getTransactionCount) - Get account nonce --- ## eth_getBlockByHash - Bittensor RPC Method # eth_getBlockByHash Returns information about a block by hash on Bittensor. > **Why Bittensor?** Build on the decentralized AI network with $3.9B+ market cap powering 80+ AI subnets with Yuma Consensus for AI model evaluation, subnet-based specialization, dual Substrate+EVM support, and incentivized AI compute marketplace. ## Use Cases The `eth_getBlockByHash` method is essential for: - **Block verification** - Verify block data using its unique hash - **Chain reorganization handling** - Track blocks during reorgs - **Cross-chain bridges** - Verify block finality for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Deterministic queries** - Get consistent block data regardless of chain state ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0x2f0555cc76fc2840a25a6f3a0f0e6d0b1a6dd2e0cecc9e4c2e9e6f3a8d2e5c1b", false ], "id": 1 } ``` ## Returns Returns the same block object as `eth_getBlockByNumber`, or `null` if no block is found. | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used | | `transactions` | `Array` | Transaction objects or hashes | ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0x2f0555cc76fc2840a25a6f3a0f0e6d0b1a6dd2e0cecc9e4c2e9e6f3a8d2e5c1b", false ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0x2f0555cc76fc2840a25a6f3a0f0e6d0b1a6dd2e0cecc9e4c2e9e6f3a8d2e5c1b'; const block = await provider.getBlock(blockHash); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY')) block_hash = '0x2f0555cc76fc2840a25a6f3a0f0e6d0b1a6dd2e0cecc9e4c2e9e6f3a8d2e5c1b' block = w3.eth.get_block(block_hash) print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockHash := common.HexToHash("0x2f0555cc76fc2840a25a6f3a0f0e6d0b1a6dd2e0cecc9e4c2e9e6f3a8d2e5c1b") block, err := client.BlockByHash(context.Background(), blockHash) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block hash format | | -32000 | Block not found | Block with this hash does not exist | ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) - Get block by number - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number --- ## eth_getBlockByNumber - Bittensor RPC Method # eth_getBlockByNumber Returns information about a block by block number on Bittensor. > **Why Bittensor?** Build on the decentralized AI network with $3.9B+ market cap powering 80+ AI subnets with Yuma Consensus for AI model evaluation, subnet-based specialization, dual Substrate+EVM support, and incentivized AI compute marketplace. ## Use Cases The `eth_getBlockByNumber` method is essential for: - **Block explorers** - Display complete block information - **Transaction indexers** - Process all transactions in a block - **Analytics platforms** - Analyze blockchain data for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Timestamp verification** - Get block timestamps for time-based logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used by all transactions | | `gasLimit` | `QUANTITY` | Maximum gas allowed in block | | `transactions` | `Array` | Array of transaction objects or hashes | | `baseFeePerGas` | `QUANTITY` | Base fee per gas (EIP-1559) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": { "number": "0x5BAD55", "hash": "0x2f0555cc76fc2840a25a6f3a0f0e6d0b1a6dd2e0cecc9e4c2e9e6f3a8d2e5c1b", "parentHash": "0x...", "timestamp": "0x64d8f6d0", "gasUsed": "0x1234", "gasLimit": "0x1c9c380", "transactions": [], "baseFeePerGas": "0x5f5e100" } } ``` ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); // Get latest block const block = await provider.getBlock('latest'); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); console.log('Transactions:', block.transactions.length); // Get block with full transactions const blockWithTxs = await provider.getBlock('latest', true); for (const tx of blockWithTxs.prefetchedTransactions) { console.log('Transaction:', tx.hash); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY')) # Get latest block block = w3.eth.get_block('latest') print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') print(f'Transactions: {len(block.transactions)}') # Get block with full transactions block_full = w3.eth.get_block('latest', full_transactions=True) for tx in block_full.transactions: print(f'Transaction: {tx.hash.hex()}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } // Get latest block block, err := client.BlockByNumber(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) fmt.Printf("Timestamp: %d\n", block.Time()) fmt.Printf("Transactions: %d\n", len(block.Transactions())) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block number or parameter format | | -32000 | Block not found | Block does not exist | ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number - [`eth_getBlockByHash`](./eth_getBlockByHash) - Get block by hash - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_getCode - Bittensor RPC Method # eth_getCode Returns the bytecode at a given address on Bittensor. > **Why Bittensor?** Build on the decentralized AI network with $3.9B+ market cap powering 80+ AI subnets with Yuma Consensus for AI model evaluation, subnet-based specialization, dual Substrate+EVM support, and incentivized AI compute marketplace. ## Use Cases The `eth_getCode` method is essential for: - **Contract verification** - Check if address is a contract - **Security analysis** - Verify deployed bytecode matches expected - **DeFi integrations** - Validate contracts before interactions - **Protocol analysis** - Analyze contract deployments for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Contract bytecode or `0x` if EOA | ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const code = await provider.getCode(address); if (code === '0x') { console.log('Address is an EOA (externally owned account)'); } else { console.log('Address is a contract'); console.log('Bytecode length:', code.length); } // Check if address is a contract async function isContract(address) { const code = await provider.getCode(address); return code !== '0x'; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY' code = w3.eth.get_code(address) if code == b'': print('Address is an EOA') else: print('Address is a contract') print(f'Bytecode length: {len(code.hex())}') # Check if address is a contract def is_contract(address): code = w3.eth.get_code(address) return code != b'' ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY") code, err := client.CodeAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } if len(code) == 0 { fmt.Println("Address is an EOA") } else { fmt.Printf("Contract bytecode length: %d\n", len(code)) } } ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_getStorageAt`](./eth_getStorageAt) - Get contract storage --- ## eth_getFilterChanges - Bittensor RPC Method # eth_getFilterChanges Polling method for a filter on Bittensor, returns an array of logs since last poll. ## Use Cases - **Event streaming** - Get new events incrementally - **Real-time monitoring** - Track contract activity for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Efficient indexing** - Process only new events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); // Poll loop async function pollFilter(filterId, interval = 2000) { while (true) { const changes = await provider.send('eth_getFilterChanges', [filterId]); if (changes.length > 0) { console.log('New events:', changes); } await new Promise(r => setTimeout(r, interval)); } } ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter --- ## eth_getFilterLogs - Bittensor RPC Method # eth_getFilterLogs Returns an array of all logs matching filter with given ID on Bittensor. ## Use Cases - **Historical queries** - Get all matching logs for a filter - **Full event history** - Retrieve complete event data for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const logs = await provider.send('eth_getFilterLogs', [filterId]); console.log('All matching logs:', logs.length); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_getLogs - Bittensor RPC Method # eth_getLogs Returns an array of all logs matching a given filter object on Bittensor. > **Why Bittensor?** Build on the decentralized AI network with $3.9B+ market cap powering 80+ AI subnets with Yuma Consensus for AI model evaluation, subnet-based specialization, dual Substrate+EVM support, and incentivized AI compute marketplace. ## Use Cases The `eth_getLogs` method is essential for: - **Event indexing** - Track contract events for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Token transfers** - Monitor ERC20/ERC721 transfers - **DeFi analytics** - Track swaps, liquidity events, and more - **Notification systems** - Alert on specific on-chain events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block (default: `"latest"`) | | `toBlock` | `QUANTITY\|TAG` | No | Ending block (default: `"latest"`) | | `address` | `DATA\|Array` | No | Contract address(es) to filter | | `topics` | `Array` | No | Array of topic filters | | `blockHash` | `DATA` | No | Filter single block by hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "topics": [""] }], "id": 1 } ``` ## Returns Array of log objects: | Field | Type | Description | |-------|------|-------------| | `address` | `DATA` | Contract that emitted the log | | `topics` | `Array` | Array of indexed topics | | `data` | `DATA` | Non-indexed log data | | `blockNumber` | `QUANTITY` | Block number | | `transactionHash` | `DATA` | Transaction hash | | `logIndex` | `QUANTITY` | Log index in block | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": [{ "address": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "topics": ["", "0x...", "0x..."], "data": "0x...", "blockNumber": "0x5BAD55", "transactionHash": "0x...", "logIndex": "0x0" }] } ``` ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "topics": [""] }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); // Get Transfer events const TRANSFER_TOPIC = ''; async function getTransferEvents(tokenAddress, fromBlock, toBlock) { const logs = await provider.getLogs({ address: tokenAddress, topics: [TRANSFER_TOPIC], fromBlock: fromBlock, toBlock: toBlock }); return logs.map(log => ({ from: '0x' + log.topics[1].slice(26), to: '0x' + log.topics[2].slice(26), blockNumber: log.blockNumber, transactionHash: log.transactionHash })); } const events = await getTransferEvents( '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 'latest', 'latest' ); console.log('Transfer events:', events); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY')) TRANSFER_TOPIC = '' def get_transfer_events(token_address, from_block, to_block): logs = w3.eth.get_logs({ 'address': token_address, 'topics': [TRANSFER_TOPIC], 'fromBlock': from_block, 'toBlock': to_block }) events = [] for log in logs: events.append({ 'from': '0x' + log['topics'][1].hex()[26:], 'to': '0x' + log['topics'][2].hex()[26:], 'block': log['blockNumber'], 'tx': log['transactionHash'].hex() }) return events events = get_transfer_events( '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 'latest', 'latest' ) print(f'Found {len(events)} transfer events') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY") transferTopic := common.HexToHash("") query := ethereum.FilterQuery{ FromBlock: big.NewInt(0), ToBlock: nil, Addresses: []common.Address{contractAddress}, Topics: [][]common.Hash, } logs, err := client.FilterLogs(context.Background(), query) if err != nil { log.Fatal(err) } fmt.Printf("Found %d events\n", len(logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32005 | Query returned more than 10000 results | Reduce block range | | -32602 | Invalid params | Invalid filter parameters | ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create a filter for logs - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for new logs --- ## eth_getStorageAt - Bittensor RPC Method # eth_getStorageAt Returns the value from a storage position at a given address on Bittensor. ## Use Cases - **Contract analysis** - Read raw storage values - **State verification** - Verify contract state - **Security auditing** - Analyze storage layout for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Protocol monitoring** - Track state changes ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte contract address | | `position` | `QUANTITY` | Yes | Storage slot position | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "0x0", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "0x0", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const slot = 0; const storage = await provider.getStorage(address, slot); console.log('Storage at slot 0:', storage); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY' storage = w3.eth.get_storage_at(address, 0) print(f'Storage at slot 0: {storage.hex()}') ``` ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_call`](./eth_call) - Call contract functions --- ## eth_getTransactionByHash - Bittensor RPC Method # eth_getTransactionByHash Returns the information about a transaction by transaction hash on Bittensor. > **Why Bittensor?** Build on the decentralized AI network with $3.9B+ market cap powering 80+ AI subnets with Yuma Consensus for AI model evaluation, subnet-based specialization, dual Substrate+EVM support, and incentivized AI compute marketplace. ## Use Cases The `eth_getTransactionByHash` method is essential for: - **Transaction tracking** - Get details of pending or confirmed transactions - **Payment verification** - Verify transaction parameters - **Debugging** - Analyze transaction data for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Block explorers** - Display transaction information ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": [""], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `hash` | `DATA` | Transaction hash | | `from` | `DATA` | Sender address | | `to` | `DATA` | Recipient address | | `value` | `QUANTITY` | Value in wei | | `gas` | `QUANTITY` | Gas provided | | `gasPrice` | `QUANTITY` | Gas price in wei | | `input` | `DATA` | Transaction input data | | `nonce` | `QUANTITY` | Sender's nonce | | `blockHash` | `DATA` | Block hash (null if pending) | | `blockNumber` | `QUANTITY` | Block number (null if pending) | ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": [""], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const txHash = ''; const tx = await provider.getTransaction(txHash); if (tx) { console.log('From:', tx.from); console.log('To:', tx.to); console.log('Value:', formatEther(tx.value)); console.log('Block:', tx.blockNumber); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY')) tx_hash = '' tx = w3.eth.get_transaction(tx_hash) if tx: print(f'From: {tx["from"]}') print(f'To: {tx["to"]}') print(f'Value: {w3.from_wei(tx["value"], "ether")}') print(f'Block: {tx["blockNumber"]}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("") tx, isPending, err := client.TransactionByHash(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Pending: %v\n", isPending) fmt.Printf("Value: %s\n", tx.Value().String()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash format | ## Related Methods - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction receipt - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionCount - Bittensor RPC Method # eth_getTransactionCount Returns the number of transactions sent from an address on Bittensor (the nonce). ## Use Cases - **Transaction building** - Get correct nonce for new transactions - **Account analysis** - Count total outgoing transactions - **Nonce management** - Handle pending transaction queues - **Wallet operations** - Prepare transactions for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag (`pending` for next nonce) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const nonce = await provider.getTransactionCount(address); console.log('Nonce:', nonce); // Get pending nonce for new transaction const pendingNonce = await provider.getTransactionCount(address, 'pending'); console.log('Next nonce:', pendingNonce); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY' nonce = w3.eth.get_transaction_count(address) print(f'Nonce: {nonce}') # Get pending nonce pending_nonce = w3.eth.get_transaction_count(address, 'pending') print(f'Next nonce: {pending_nonce}') ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionReceipt - Bittensor RPC Method # eth_getTransactionReceipt Returns the receipt of a transaction by transaction hash on Bittensor. Receipt is only available for mined transactions. > **Why Bittensor?** Build on the decentralized AI network with $3.9B+ market cap powering 80+ AI subnets with Yuma Consensus for AI model evaluation, subnet-based specialization, dual Substrate+EVM support, and incentivized AI compute marketplace. ## Use Cases The `eth_getTransactionReceipt` method is essential for: - **Transaction confirmation** - Verify transaction was mined successfully - **Gas analysis** - Check actual gas used vs estimated - **Event parsing** - Read emitted events from logs - **Status verification** - Confirm success/failure for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": [""], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `status` | `QUANTITY` | `1` (success) or `0` (failure) | | `transactionHash` | `DATA` | Transaction hash | | `blockHash` | `DATA` | Block hash | | `blockNumber` | `QUANTITY` | Block number | | `gasUsed` | `QUANTITY` | Gas used by this transaction | | `cumulativeGasUsed` | `QUANTITY` | Total gas used in block up to this tx | | `logs` | `Array` | Array of log objects | | `contractAddress` | `DATA` | Created contract address (if deployment) | ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": [""], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const txHash = ''; const receipt = await provider.getTransactionReceipt(txHash); if (receipt) { console.log('Status:', receipt.status === 1 ? 'Success' : 'Failed'); console.log('Gas Used:', receipt.gasUsed.toString()); console.log('Block:', receipt.blockNumber); console.log('Logs:', receipt.logs.length); // Parse specific events for (const log of receipt.logs) { console.log('Event from:', log.address); } } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY')) tx_hash = '' receipt = w3.eth.get_transaction_receipt(tx_hash) if receipt: status = 'Success' if receipt['status'] == 1 else 'Failed' print(f'Status: {status}') print(f'Gas Used: {receipt["gasUsed"]}') print(f'Block: {receipt["blockNumber"]}') print(f'Logs: {len(receipt["logs"])}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("") receipt, err := client.TransactionReceipt(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Status: %d\n", receipt.Status) fmt.Printf("Gas Used: %d\n", receipt.GasUsed) fmt.Printf("Logs: %d\n", len(receipt.Logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash | **Note**: Returns `null` if transaction is not yet mined. ## Related Methods - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details - [`eth_getLogs`](./eth_getLogs) - Query logs by filter --- ## eth_hashrate - Get node hashrate(Bittensor) # eth_hashrate Get node hashrate on the Bittensor network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_hashrate](https://ethereum.org/developers/docs/apis/json-rpc/#eth_hashrate) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_hashrate", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_hashrate', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Bittensor documentation](/docs/bittensor).* --- ## eth_maxPriorityFeePerGas - Bittensor RPC Method # eth_maxPriorityFeePerGas Returns the current recommended priority fee per gas on Bittensor for EIP-1559 transactions. ## Use Cases - **EIP-1559 transactions** - Set appropriate priority fees - **Transaction acceleration** - Calculate tips for faster inclusion - **Gas optimization** - Balance speed vs cost for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); console.log('Max Priority Fee:', formatUnits(feeData.maxPriorityFeePerGas, 'gwei'), 'Gwei'); console.log('Max Fee Per Gas:', formatUnits(feeData.maxFeePerGas, 'gwei'), 'Gwei'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY')) priority_fee = w3.eth.max_priority_fee print(f'Max Priority Fee: {w3.from_wei(priority_fee, "gwei")} Gwei') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get legacy gas price - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data --- ## eth_mining - Check if node is mining(Bittensor) # eth_mining Check if node is mining on the Bittensor network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_mining](https://ethereum.org/developers/docs/apis/json-rpc/#eth_mining) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_mining', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Bittensor documentation](/docs/bittensor).* --- ## eth_newBlockFilter - Bittensor RPC Method # eth_newBlockFilter Creates a filter on Bittensor to notify when a new block arrives. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newBlockFilter', []); // Poll for new blocks const newBlocks = await provider.send('eth_getFilterChanges', [filterId]); console.log('New block hashes:', newBlocks); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_blockNumber`](./eth_blockNumber) - Get current block --- ## eth_newFilter - Bittensor RPC Method # eth_newFilter Creates a filter object on Bittensor to notify when state changes (logs). ## Use Cases - **Event monitoring** - Subscribe to contract events - **Real-time updates** - Track events for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Indexing** - Build event indexes incrementally ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block | | `toBlock` | `QUANTITY\|TAG` | No | Ending block | | `address` | `DATA\|Array` | No | Contract address(es) | | `topics` | `Array` | No | Topic filters | ## Request ```json { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "topics": [""] }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); // Create filter const filterId = await provider.send('eth_newFilter', [{ fromBlock: 'latest', address: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', topics: [''] }]); // Poll for changes const changes = await provider.send('eth_getFilterChanges', [filterId]); console.log('New events:', changes); // Cleanup await provider.send('eth_uninstallFilter', [filterId]); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for changes - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_newPendingTransactionFilter - Bittensor RPC Method # eth_newPendingTransactionFilter Creates a filter on Bittensor to notify when new pending transactions arrive. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newPendingTransactionFilter', []); // Poll for pending transactions const pendingTxs = await provider.send('eth_getFilterChanges', [filterId]); console.log('Pending transaction hashes:', pendingTxs); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_protocolVersion - Get protocol version(Bittensor) # eth_protocolVersion Get protocol version on the Bittensor network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_protocolVersion](https://ethereum.org/developers/docs/apis/json-rpc/#eth_protocolversion) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_protocolVersion", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_protocolVersion', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Bittensor documentation](/docs/bittensor).* --- ## eth_sendRawTransaction - Bittensor RPC Method # eth_sendRawTransaction Submits a pre-signed transaction for broadcast to Bittensor. > **Why Bittensor?** Build on the decentralized AI network with $3.9B+ market cap powering 80+ AI subnets with Yuma Consensus for AI model evaluation, subnet-based specialization, dual Substrate+EVM support, and incentivized AI compute marketplace. ## Use Cases The `eth_sendRawTransaction` method is essential for: - **Broadcasting transactions** - Submit signed transactions to the network - **Wallet operations** - Send native tokens and interact with contracts - **DeFi operations** - Execute swaps, provide liquidity for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Batch operations** - Submit multiple transactions efficiently ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `signedTransactionData` | `DATA` | Yes | The signed transaction data (RLP encoded) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | 32-byte transaction hash | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c808504a817c80082520894..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const wallet = new Wallet('YOUR_PRIVATE_KEY', provider); // Send native tokens async function sendTransaction(to, value) { const tx = await wallet.sendTransaction({ to: to, value: parseEther(value) }); console.log('Transaction hash:', tx.hash); // Wait for confirmation const receipt = await tx.wait(); console.log('Confirmed in block:', receipt.blockNumber); return receipt; } // Send to contract async function sendContractTransaction(contract, method, args, value = '0') { const tx = await contract[method](...args, { value: parseEther(value) }); return await tx.wait(); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY')) def send_transaction(private_key, to, value_in_ether): account = w3.eth.account.from_key(private_key) # Build transaction tx = { 'nonce': w3.eth.get_transaction_count(account.address), 'to': to, 'value': w3.to_wei(value_in_ether, 'ether'), 'gas': 21000, 'gasPrice': w3.eth.gas_price, 'chainId': w3.eth.chain_id } # Sign transaction signed_tx = account.sign_transaction(tx) # Send transaction tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) print(f'Transaction hash: {tx_hash.hex()}') # Wait for confirmation receipt = w3.eth.wait_for_transaction_receipt(tx_hash) print(f'Confirmed in block: {receipt["blockNumber"]}') return receipt ``` ```go package main "context" "crypto/ecdsa" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY") if err != nil { log.Fatal(err) } publicKey := privateKey.Public() publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey) fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA) nonce, _ := client.PendingNonceAt(context.Background(), fromAddress) value := big.NewInt(1000000000000000000) gasLimit := uint64(21000) gasPrice, _ := client.SuggestGasPrice(context.Background()) toAddress := common.HexToAddress("5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY") tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil) chainID, _ := client.NetworkID(context.Background()) signedTx, _ := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey) err = client.SendTransaction(context.Background(), signedTx) if err != nil { log.Fatal(err) } fmt.Printf("Transaction hash: %s\n", signedTx.Hash().Hex()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Nonce too low | Transaction nonce already used | | -32000 | Insufficient funds | Account has insufficient balance | | -32000 | Gas too low | Gas limit insufficient | | -32000 | Replacement underpriced | Gas price too low for replacement | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas required - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction result --- ## eth_sendTransaction - Send transaction (wa...(Bittensor) # eth_sendTransaction > **Important**: Dwellir's shared Bittensor endpoints do not manage user private keys. JSON-RPC nodes cannot unlock your account, so `eth_sendTransaction` calls will fail. Sign transactions client-side and broadcast them with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Why this method is disabled on shared nodes - [`eth_sendTransaction` requires the node to hold and unlock the `from` account's private key](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction). - Managed infrastructure providers disable it for security reasons rather than storing customer keys on shared servers (for example, [Infura explicitly blocks the method on shared endpoints](https://docs.infura.io/api/networks/ethereum/json-rpc-methods/eth_sendtransaction)). ## Recommended workflow 1. Build the raw transaction locally with your wallet or SDK. 2. Sign the payload client-side (hardware wallet, custodial service, or library). 3. Submit the signed hex string with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Example response from the shared endpoint ```bash curl -s -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"0x0000000000000000000000000000000000000000"}],"id":1}' ``` ```json {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"unknown account"}} ``` Need help? Contact our [support team](mailto:support@dwellir.com) or use the dedicated [`eth_sendRawTransaction`](./eth_sendRawTransaction) guide. --- ## eth_signTransaction - Sign transaction (ra...(Bittensor) # eth_signTransaction Signs a transaction using an unlocked account on the node. **Important**: Most RPC providers don't support this method for security reasons, as it requires private keys to be stored on the server. ## Security Considerations - This method requires an unlocked account on the node - Private keys must be available to the RPC server - Most production RPC providers disable this method - Use client-side signing libraries instead for better security ## Parameters 1. `Object` - The transaction object: - `from`: `DATA`, 20 Bytes - The address the transaction is sent from - `to`: `DATA`, 20 Bytes - (optional) The address the transaction is directed to - `gas`: `QUANTITY` - (optional) Integer of the gas provided for the transaction execution - `gasPrice`: `QUANTITY` - (optional) Integer of the gasPrice used for each paid gas - `value`: `QUANTITY` - (optional) Integer of the value sent with this transaction - `data`: `DATA` - (optional) The compiled code of a contract OR the hash of the invoked method signature and encoded parameters ## Returns `DATA` - The signed transaction data, ready for transmission via `eth_sendRawTransaction`. ## Implementation Example ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_signTransaction", "params": [{ "from": "0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a" }], "id": 1 }' ``` ```javascript const response = await fetch('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_signTransaction', params: [{ from: '0x9b2055d370f73ec7d8a03e965129118dc8f5bf83', to: '0xd46e8dd67c5d32be8058bb8eb970870f07244567', gas: '0x76c0', gasPrice: '0x9184e72a000', value: '0x9184e72a' }], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0xf86c808504a817c8008276c094d46e8dd67c5d32be8058bb8eb970870f072445675849184e72a8001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804" } ``` **Note**: This method is typically not available on hosted RPC providers for security reasons. The response shows a signed transaction ready for broadcast. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Bittensor documentation](/docs/bittensor).* --- ## eth_syncing - Bittensor RPC Method # eth_syncing Returns syncing status of Bittensor node. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 } ``` ## Returns Returns `false` if not syncing, or an object with sync status. ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const syncing = await provider.send('eth_syncing', []); if (syncing === false) { console.log('Node is fully synced'); } else { console.log('Syncing:', syncing); } ``` ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get current block - [`net_peerCount`](./net_peerCount) - Get peer count --- ## eth_uninstallFilter - Bittensor RPC Method # eth_uninstallFilter Uninstalls a filter on Bittensor. Should be called when no longer needed. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID to uninstall | ## Request ```json { "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if filter was found and uninstalled | ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const success = await provider.send('eth_uninstallFilter', [filterId]); console.log('Filter removed:', success); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter --- ## grandpa_roundState - Bittensor RPC Method # grandpa_roundState Returns the state of the current GRANDPA finality round on Bittensor. GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) is the finality gadget used by Substrate chains. ## Use Cases - **Finality monitoring** - Track consensus progress for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Validator analysis** - Monitor prevote/precommit participation - **Chain health checks** - Detect finality delays or stalls ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `setId` | `u64` | Current authority set ID | | `best` | `RoundState` | Best round state | | `background` | `Vec` | Background rounds | ### RoundState Structure | Field | Type | Description | |-------|------|-------------| | `round` | `u64` | Round number | | `totalWeight` | `u64` | Total validator weight | | `thresholdWeight` | `u64` | Weight needed for supermajority | | `prevotes` | `Prevotes` | Prevote information | | `precommits` | `Precommits` | Precommit information | ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "grandpa_roundState", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const roundState = await api.rpc.grandpa.roundState(); console.log('Set ID:', roundState.setId.toString()); console.log('Best round:', roundState.best.round.toString()); console.log('Total weight:', roundState.best.totalWeight.toString()); console.log('Threshold:', roundState.best.thresholdWeight.toString()); await api.disconnect(); ``` ```python url = 'https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'grandpa_roundState', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json()['result'] print(f"Set ID: {result['setId']}") print(f"Round: {result['best']['round']}") print(f"Total weight: {result['best']['totalWeight']}") ``` ## Understanding GRANDPA Rounds 1. **Prevote phase** - Validators vote on best block they've seen 2. **Precommit phase** - Validators commit to finalize if supermajority prevoted 3. **Finalization** - Block is finalized when 2/3+ weight precommits ## Related Methods - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get current finalized hash - [`beefy_getFinalizedHead`](./beefy_getFinalizedHead) - BEEFY finality (if enabled) --- ## Bittensor - Decentralized Machine Learning Network export const S = substrateSamples['bittensor']; # Bittensor - Decentralized Machine Learning Network ## Description Interact with Substrate JSON‑RPC. This method is commonly used to build reliable indexers, developer tooling, and responsive UIs. ## Why Build on Bittensor? Bittensor is a revolutionary blockchain that creates a decentralized marketplace for machine learning models and computational intelligence. Built on Substrate, Bittensor enables: ### 🤖 **AI-Native Blockchain** - **Decentralized ML** - Train and serve models in a trustless environment - **Incentivized Intelligence** - Earn TAO tokens for contributing compute and models - **Collaborative Learning** - Models improve through network-wide collaboration ### 🔬 **Advanced Capabilities** - **Neural Mining** - Mine TAO tokens by running AI models - **36+ Subnets** - Specialized networks for different AI tasks (expanding to 1024) - **Yuma Consensus** - Novel consensus mechanism for ML validation ### 💡 **Innovation Platform** - **Open AI Marketplace** - Access diverse AI models and services - **Composable Intelligence** - Build complex AI systems from network primitives - **Research Network** - Contribute to cutting-edge ML research ## Quick Start with Bittensor Connect to Bittensor in seconds with Dwellir's optimized endpoints: ### Installation & Setup ```javascript // Connect to Bittensor mainnet const provider = new JsonRpcProvider( '${S.rpcBase}' ); // Get the latest block const block = await provider.getBlock('latest'); console.log('Latest block:', block.number); // Query account balance const balance = await provider.getBalance('0x...'); console.log('Balance:', balance.toString()); ``` ```javascript const Web3 = require('web3'); // Connect to Bittensor mainnet const web3 = new Web3( '${S.rpcBase}' ); // Get chain ID to verify connection const chainId = await web3.eth.getChainId(); console.log('Connected to Bittensor:', chainId); // Get gas price for optimal transaction pricing const gasPrice = await web3.eth.getGasPrice(); console.log('Current gas price:', gasPrice); ``` ```python from web3 import Web3 # Connect to Bittensor mainnet w3 = Web3(Web3.HTTPProvider( '${S.rpcBase}' )) # Check connection if w3.is_connected(): print("Connected to Bittensor") # Get latest block latest_block = w3.eth.block_number print(f"Latest block: {latest_block}") # Get account balance balance = w3.eth.get_balance('0x...') print(f"Balance: {balance} TAO") ``` ## Network Information Chain ID N/A Substrate-based Block Time 12 seconds Average Native Token TAO 21M max supply Consensus Yuma ML Validation ## JSON-RPC API Reference Bittensor exposes both an Ethereum-compatible JSON-RPC (via Frontier) and native Substrate RPC. Use either or both depending on your integration. ### Substrate API ### EVM API #### Custom RPC Extensions Bittensor nodes also expose custom RPC namespaces for chain‑specific AI/ML data: - `subnetInfo_*` — subnet configuration, hyperparameters, metagraphs - `neuronInfo_*` — neuron and mechagraph data - `delegateInfo_*` — delegation and delegate details - `swap_*` — TAO/ALPHA swap simulation helpers These are implemented by the chain and surfaced over JSON‑RPC; see the runtime and node RPC code for details. Refer to the links in the Resources section below. ## Common Integration Patterns ### 🧠 **Subnet Interaction** Connect to Bittensor subnets for specialized AI tasks: ```javascript // Query subnet information async function getSubnetInfo(subnetId) { const result = await provider.call({ to: SUBNET_REGISTRY_ADDRESS, data: encodeSubnetQuery(subnetId) }); return decodeSubnetInfo(result); } // Register as miner async function registerMiner(subnetId, modelEndpoint) { const tx = { to: SUBNET_REGISTRY_ADDRESS, data: encodeMinerRegistration(subnetId, modelEndpoint), value: REGISTRATION_FEE }; const receipt = await signer.sendTransaction(tx); return receipt; } ``` ### 💰 **TAO Token Operations** Manage TAO tokens and staking: ```javascript // Stake TAO tokens async function stakeTAO(amount, validatorAddress) { const stakingContract = new Contract( STAKING_CONTRACT_ADDRESS, STAKING_ABI, signer ); const tx = await stakingContract.stake( validatorAddress, { value: parseEther(amount) } ); return tx.wait(); } // Query staking rewards async function getStakingRewards(address) { const rewards = await stakingContract.pendingRewards(address); return formatUnits(rewards, 9); // TAO has 9 decimals } ``` ### 🔍 **Model Validation** Validate AI model outputs on-chain: ```javascript // Submit model output for validation async function submitModelOutput(subnetId, taskId, output) { const validationContract = new Contract( VALIDATION_CONTRACT_ADDRESS, VALIDATION_ABI, signer ); const proof = generateProof(output); const tx = await validationContract.submitOutput( subnetId, taskId, output, proof ); return tx.wait(); } ``` ## Performance Best Practices ### 1. **Efficient Querying** Optimize queries for Bittensor's unique architecture: ```javascript // Batch subnet queries async function batchSubnetQueries(subnetIds) { const queries = subnetIds.map(id => ({ to: SUBNET_REGISTRY_ADDRESS, data: encodeSubnetQuery(id) })); const results = await Promise.all( queries.map(q => provider.call(q)) ); return results.map(decodeSubnetInfo); } ``` ### 2. **Caching Strategy** Cache frequently accessed subnet and model data: ```javascript class SubnetCache { constructor(ttl = 60000) { // 1 minute TTL this.cache = new Map(); this.ttl = ttl; } async get(subnetId, fetcher) { const key = `subnet_${subnetId}`; const cached = this.cache.get(key); if (cached && Date.now() - cached.timestamp < this.ttl) { return cached.data; } const data = await fetcher(subnetId); this.cache.set(key, { data, timestamp: Date.now() }); return data; } } ``` ### 3. **Connection Management** Maintain persistent connections for real-time updates: ```javascript // WebSocket connection for real-time updates const wsProvider = new WebSocketProvider( '${S.wsBase}' ); // Subscribe to subnet events wsProvider.on('subnet_update', (event) => { console.log('Subnet updated:', event); }); ``` ## Troubleshooting Common Issues ### Error: "Invalid subnet ID" Ensure you're using valid subnet identifiers: ```javascript // Validate subnet ID before operations async function validateSubnet(subnetId) { const exists = await provider.call({ to: SUBNET_REGISTRY_ADDRESS, data: encodeSubnetExists(subnetId) }); if (!exists) { throw new Error(`Subnet ${subnetId} does not exist`); } return true; } ``` ### Error: "Insufficient stake" Check staking requirements before operations: ```javascript // Check minimum stake requirement async function checkStakeRequirement(operation) { const required = await getMinimumStake(operation); const current = await getUserStake(address); if (current < required) { throw new Error(`Need ${required - current} more TAO staked`); } } ``` ## Resources & Tools ### Official Resources - [Bittensor Documentation](https://docs.bittensor.com) - [Taostats Explorer](https://taostats.io) - [Bittensor GitHub](https://github.com/opentensor/bittensor) ### Developer Tools - [Bittensor SDK](https://pypi.org/project/bittensor/) - [Subnet Template](https://github.com/opentensor/subnet-template) ### Need Help? - 📧 **Email**: support@dwellir.com - 📚 **Docs**: You're here! - 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com) --- *Start building on Bittensor with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)* --- ## net_listening - Bittensor RPC Method # net_listening Returns `true` if client is actively listening for network connections on Bittensor. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if listening | ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const listening = await provider.send('net_listening', []); console.log('Node listening:', listening); ``` ## Related Methods - [`net_peerCount`](./net_peerCount) - Get peer count --- ## net_peerCount - Bittensor RPC Method # net_peerCount Returns number of peers currently connected to Bittensor client. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Number of connected peers (hexadecimal) | ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const peerCount = await provider.send('net_peerCount', []); console.log('Peer count:', parseInt(peerCount, 16)); ``` ## Related Methods - [`net_listening`](./net_listening) - Check if listening --- ## net_version - Bittensor RPC Method # net_version Returns the current network ID on Bittensor. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Network ID as a string | ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const networkId = await provider.send('net_version', []); console.log('Network ID:', networkId); ``` ## Related Methods - [`eth_chainId`](./eth_chainId) - Get chain ID --- ## neuronInfo_getNeuron - JSON-RPC Method export const S = substrateSamples['bittensor']; # neuronInfo_getNeuron ## Description Bittensor neuron information (lite and detailed) per subnet, including UIDs and attributes. Use to index participants and build explorer views. Returns detailed neuron info for a neuron `uid` in a subnet `netuid`. ## Code Examples --- ## neuronInfo_getNeuronLite - JSON-RPC Method export const S = substrateSamples['bittensor']; # neuronInfo_getNeuronLite ## Description Bittensor neuron information (lite and detailed) per subnet, including UIDs and attributes. Use to index participants and build explorer views. Returns compact neuron info for a single neuron (uid) in a subnet. ## Parameters | Param | Type | Description | | --- | --- | --- | | `netuid` | number | Subnet id (e.g., 1) | | `uid` | number | Neuron id within subnet (e.g., 0) | | `at` | string? | Optional block hash | ## Code Examples --- ## neuronInfo_getNeurons - JSON-RPC Method export const S = substrateSamples['bittensor']; # neuronInfo_getNeurons ## Description Bittensor neuron information (lite and detailed) per subnet, including UIDs and attributes. Use to index participants and build explorer views. Returns detailed neuron info for all neurons in a subnet. ## Code Examples --- ## neuronInfo_getNeuronsLite - JSON-RPC Method export const S = substrateSamples['bittensor']; # neuronInfo_getNeuronsLite ## Description Bittensor neuron information (lite and detailed) per subnet, including UIDs and attributes. Use to index participants and build explorer views. Returns compact neuron info for all neurons in a subnet. ## Code Examples --- ## offchain_localStorageClear - JSON-RPC Method export const S = substrateSamples['bittensor']; # offchain_localStorageClear Clears an offchain local storage key. Requires administrative access to the node and is not available on shared public RPC. ## Code Examples --- ## offchain_localStorageGet - JSON-RPC Method export const S = substrateSamples['bittensor']; # offchain_localStorageGet Reads an offchain local storage key (if allowed). > Public RPC nodes often disable offchain access; expect null. ## Code Examples --- ## offchain_localStorageSet - JSON-RPC Method export const S = substrateSamples['bittensor']; # offchain_localStorageSet ## Description Access local offchain storage APIs (admin‑only). Useful for off‑chain workers and node‑local caching on self‑hosted nodes. Sets an offchain local storage key. Restricted to self-hosted nodes with offchain RPC enabled. ## Code Examples --- ## payment_queryFeeDetails - Bittensor RPC Method # payment_queryFeeDetails Returns a detailed breakdown of fees for a given extrinsic on Bittensor. Unlike `payment_queryInfo` which returns the total fee, this method separates the fee into its component parts. ## Use Cases - **Fee analysis** - Understand fee composition for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Optimization** - Identify which fee component dominates costs - **Debugging** - Diagnose unexpected fee amounts ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `Bytes` | Yes | SCALE-encoded extrinsic (signed or unsigned) | | `blockHash` | `Hash` | No | Block hash for fee calculation context | ## Returns | Field | Type | Description | |-------|------|-------------| | `inclusionFee` | `Option` | Fee details (null for unsigned extrinsics) | ### InclusionFee Structure | Field | Type | Description | |-------|------|-------------| | `baseFee` | `Balance` | Fixed base fee per extrinsic | | `lenFee` | `Balance` | Fee based on encoded extrinsic length | | `adjustedWeightFee` | `Balance` | Fee based on execution weight | ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "payment_queryFeeDetails", "params": ["0x...encodedExtrinsic"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Create a sample transfer const tx = api.tx.balances.transferKeepAlive( '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 1000000000000n ); // Get fee details const feeDetails = await api.rpc.payment.queryFeeDetails(tx.toHex()); if (feeDetails.inclusionFee.isSome) { const fee = feeDetails.inclusionFee.unwrap(); console.log('Base fee:', fee.baseFee.toString()); console.log('Length fee:', fee.lenFee.toString()); console.log('Weight fee:', fee.adjustedWeightFee.toString()); } await api.disconnect(); ``` ```python url = 'https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY' # Replace with actual encoded extrinsic encoded_extrinsic = '0x...' payload = { 'jsonrpc': '2.0', 'method': 'payment_queryFeeDetails', 'params': [encoded_extrinsic], 'id': 1 } response = requests.post(url, json=payload) result = response.json()['result'] if result['inclusionFee']: fee = result['inclusionFee'] print(f"Base fee: {fee['baseFee']}") print(f"Length fee: {fee['lenFee']}") print(f"Weight fee: {fee['adjustedWeightFee']}") ``` ## Fee Components Explained | Component | Calculation | Optimization | |-----------|-------------|--------------| | **Base fee** | Fixed per extrinsic | Batch calls to share base fee | | **Length fee** | `length * lengthToFee` | Minimize call data size | | **Weight fee** | `weight * weightToFee` | Choose efficient operations | ## Related Methods - [`payment_queryInfo`](./payment_queryInfo) - Get total fee estimate - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction - [`state_call`](./state_call) - Call TransactionPaymentApi directly --- ## payment_queryInfo - Bittensor RPC Method # payment_queryInfo Estimates the fee for an extrinsic on Bittensor. ## Use Cases - **Fee estimation** - Calculate transaction costs before sending - **UI display** - Show fees to users for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Transaction planning** - Ensure sufficient funds ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `String` | Yes | Hex-encoded unsigned extrinsic | | `blockHash` | `String` | No | Block hash for fee calculation | ## Request ```json { "jsonrpc": "2.0", "method": "payment_queryInfo", "params": ["0x..."], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `weight` | `Object` | Transaction weight | | `class` | `String` | Dispatch class | | `partialFee` | `String` | Estimated fee | ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "payment_queryInfo", "params": ["0x..."], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Create transfer (unsigned for estimation) const transfer = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000); const info = await transfer.paymentInfo('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'); console.log('Partial fee:', info.partialFee.toHuman()); await api.disconnect(); ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction --- ## rpc_methods - Bittensor RPC Method # rpc_methods Returns a list of all RPC methods available on Bittensor. ## Use Cases - **API discovery** - List all available methods - **Compatibility checking** - Verify method availability for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Documentation** - Auto-generate method lists ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const methods = await api.rpc.rpc.methods(); console.log('Available methods:', methods.methods.length); await api.disconnect(); ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## state_call - Bittensor RPC Method # state_call Calls a runtime API method on Bittensor. ## Use Cases - **Runtime computations** - Execute runtime logic without transactions - **Account queries** - Use AccountNonceApi for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Fee estimation** - Use TransactionPaymentApi ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `method` | `String` | Yes | Runtime API method name | | `data` | `String` | Yes | SCALE-encoded call data | | `blockHash` | `String` | No | Block hash for historical call | ## Request ```json { "jsonrpc": "2.0", "method": "state_call", "params": ["AccountNonceApi_account_nonce", "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"], "id": 1 } ``` ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_call", "params": ["AccountNonceApi_account_nonce", "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get account nonce via runtime API const account = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const result = await api.call.accountNonceApi.accountNonce(account); console.log('Account nonce:', result.toNumber()); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Query storage - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## state_callAt - JSON-RPC Method export const S = substrateSamples['bittensor']; # state_callAt ## Description Execute runtime API methods (off‑chain calls) with SCALE parameters. Use to retrieve data exposed via runtime APIs (e.g., metadata) without submitting extrinsics. Executes a runtime API by name with SCALE-encoded input at a given block hash. ## Code Examples --- ## state_getChildReadProof - JSON-RPC Method export const S = substrateSamples['bittensor']; # state_getChildReadProof Returns read proofs for child storage keys at a block. Child trie usage is runtime-specific and may return empty results. > Replace parameters with a real child storage root and keys for meaningful proofs. ## Code Examples --- ## state_getKeys - JSON-RPC Method(Bittensor) export const S = substrateSamples['bittensor']; # state_getKeys ## Description Enumerate storage keys for a prefix. Use for pagination when exploring large maps, then query values with state_getStorage. Returns storage keys for the given key prefix. ## Code Examples --- ## state_getKeysPaged - Bittensor RPC Method # state_getKeysPaged Returns storage keys with pagination on Bittensor. ## Use Cases - **Storage iteration** - Enumerate storage map entries - **Data export** - Bulk export chain data for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Account enumeration** - List all accounts ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `prefix` | `String` | Yes | Storage key prefix | | `count` | `Number` | Yes | Maximum keys to return | | `startKey` | `String` | No | Key to start after | | `blockHash` | `String` | No | Block hash for historical query | ## Request ```json { "jsonrpc": "2.0", "method": "state_getKeysPaged", "params": ["0x...", 100], "id": 1 } ``` ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getKeysPaged", "params": ["0x26aa394eea5630e07c48ae0c9558cef7", 100], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get all accounts (paginated) const keys = await api.rpc.state.getKeysPaged( api.query.system.account.keyPrefix(), 100 ); console.log('Found accounts:', keys.length); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Get storage value - [`state_queryStorageAt`](./state_queryStorageAt) - Batch storage query --- ## state_getKeysPagedAt - JSON-RPC Method export const S = substrateSamples['bittensor']; # state_getKeysPagedAt ## Description Enumerate storage keys for a prefix. Use for pagination when exploring large maps, then query values with state_getStorage. Returns storage keys with a given prefix, paginated, at a specific block hash. ## Code Examples --- ## state_getMetadata - Bittensor RPC Method # state_getMetadata Returns the runtime metadata on Bittensor. ## Use Cases - **Runtime introspection** - Discover available pallets and calls - **Extrinsic building** - Get call and type information for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Storage key generation** - Build storage keys from metadata - **Client generation** - Auto-generate typed APIs ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash for historical metadata | ## Request ```json { "jsonrpc": "2.0", "method": "state_getMetadata", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getMetadata", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get runtime metadata const metadata = await api.rpc.state.getMetadata(); // List available pallets const pallets = metadata.asLatest.pallets.map(p => p.name.toString()); console.log('Available pallets:', pallets); // Get specific pallet info const systemPallet = metadata.asLatest.pallets.find(p => p.name.toString() === 'System'); console.log('System pallet calls:', systemPallet.calls.isSome ? 'Available' : 'None'); await api.disconnect(); ``` ```python def get_metadata(): url = 'https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'state_getMetadata', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] metadata_hex = get_metadata() print(f'Metadata length: {len(metadata_hex)} bytes') ``` ## Related Methods - [`state_getRuntimeVersion`](./state_getRuntimeVersion) - Get runtime version - [`state_getStorage`](./state_getStorage) - Query storage --- ## state_getPairs - JSON-RPC Method export const S = substrateSamples['bittensor']; # state_getPairs Returns the storage key/value pairs for a specified key prefix. > Note: Returns an array of [key, value] pairs (SCALE-encoded values). ## Code Examples --- ## state_getReadProof - JSON-RPC Method export const S = substrateSamples['bittensor']; # state_getReadProof ## Description Generate Merkle proofs for storage keys at a block. Use to verify state off‑chain or in trust‑minimized bridges. Returns a proof for storage entries at a given block. ## Code Examples --- ## state_getRuntimeVersion - Bittensor RPC Method # state_getRuntimeVersion Returns the runtime version on Bittensor. ## Use Cases - **Version checking** - Verify runtime compatibility - **Upgrade detection** - Monitor for runtime upgrades on decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Client compatibility** - Ensure API compatibility ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash for historical version | ## Request ```json { "jsonrpc": "2.0", "method": "state_getRuntimeVersion", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getRuntimeVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const version = await api.rpc.state.getRuntimeVersion(); console.log('Spec name:', version.specName.toString()); console.log('Spec version:', version.specVersion.toNumber()); console.log('Impl version:', version.implVersion.toNumber()); await api.disconnect(); ``` ```python def get_runtime_version(): url = 'https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'state_getRuntimeVersion', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] version = get_runtime_version() print(f"Spec: {version['specName']} v{version['specVersion']}") ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata - [`system_version`](./system_version) - Get node version --- ## state_getStorage - Bittensor RPC Method # state_getStorage Returns a storage entry at a specific key on Bittensor. > **Why Bittensor?** Build on the decentralized AI network with $3.9B+ market cap powering 80+ AI subnets with Yuma Consensus for AI model evaluation, subnet-based specialization, dual Substrate+EVM support, and incentivized AI compute marketplace. ## Use Cases - **State queries** - Read on-chain storage values - **Account balances** - Query account data for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Pallet storage** - Access runtime storage items - **Historical state** - Query state at specific blocks ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `key` | `String` | Yes | Storage key (hex-encoded) | | `blockHash` | `String` | No | Block hash for historical query | ## Request ```json { "jsonrpc": "2.0", "method": "state_getStorage", "params": [""], "id": 1 } ``` ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getStorage", "params": [""], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query account balance const account = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const accountInfo = await api.query.system.account(account); console.log('Free balance:', accountInfo.data.free.toString()); // Query at specific block const blockHash = '0x2f0555cc76fc2840a25a6f3a0f0e6d0b1a6dd2e0cecc9e4c2e9e6f3a8d2e5c1b'; const historicalBalance = await api.query.system.account.at(blockHash, account); console.log('Historical balance:', historicalBalance.data.free.toString()); await api.disconnect(); ``` ```python def get_storage(key, block_hash=None): url = 'https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY' params = [key] if block_hash is None else [key, block_hash] payload = { 'jsonrpc': '2.0', 'method': 'state_getStorage', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] # Query :code storage (runtime wasm) storage_key = '' value = get_storage(storage_key) print(f'Storage value: {value[:66]}...' if value else 'None') ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata - [`state_getKeysPaged`](./state_getKeysPaged) - Enumerate storage keys --- ## state_getStorageAt - JSON-RPC Method export const S = substrateSamples['bittensor']; # state_getStorageAt ## Description Read SCALE‑encoded storage for a key (optionally at a specific block). Use to fetch on‑chain state deterministically and to implement historical reads. Returns the storage value for a key at a given block hash. ## Code Examples --- ## state_getStorageHash - JSON-RPC Method export const S = substrateSamples['bittensor']; # state_getStorageHash ## Description Read SCALE‑encoded storage for a key (optionally at a specific block). Use to fetch on‑chain state deterministically and to implement historical reads. Returns the STORAGE HASH for a given key at the best block. ## Code Examples --- ## state_getStorageHashAt - JSON-RPC Method export const S = substrateSamples['bittensor']; # state_getStorageHashAt ## Description Read SCALE‑encoded storage for a key (optionally at a specific block). Use to fetch on‑chain state deterministically and to implement historical reads. Returns the storage hash for a key at the given block hash. ## Code Examples --- ## state_getStorageSize - JSON-RPC Method export const S = substrateSamples['bittensor']; # state_getStorageSize ## Description Read SCALE‑encoded storage for a key (optionally at a specific block). Use to fetch on‑chain state deterministically and to implement historical reads. Returns the size (in bytes) of the storage value for the given key. ## Code Examples --- ## state_getStorageSizeAt - JSON-RPC Method export const S = substrateSamples['bittensor']; # state_getStorageSizeAt ## Description Read SCALE‑encoded storage for a key (optionally at a specific block). Use to fetch on‑chain state deterministically and to implement historical reads. Returns the size (in bytes) of the storage value for the key at the given block. ## Code Examples --- ## state_queryStorage - JSON-RPC Method export const S = substrateSamples['bittensor']; # state_queryStorage Returns storage changes for the provided keys over a block range [from, to]. > If there are no changes in the range, the result array may be empty. ## Code Examples --- ## state_queryStorageAt - Bittensor RPC Method # state_queryStorageAt Query multiple storage keys at a specific block on Bittensor. ## Use Cases - **Batch queries** - Efficiently query multiple storage items - **Snapshot state** - Get consistent multi-key state for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Data analysis** - Compare storage across blocks ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `keys` | `Array` | Yes | Array of storage keys | | `blockHash` | `String` | No | Block hash for query | ## Request ```json { "jsonrpc": "2.0", "method": "state_queryStorageAt", "params": [[""]], "id": 1 } ``` ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_queryStorageAt", "params": [[""]], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query multiple accounts at once const accounts = ['5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY']; const entries = await api.query.system.account.multi(accounts); entries.forEach((info, idx) => { console.log(`Account ${idx}: ${info.data.free.toString()}`); }); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Single storage query - [`state_getKeysPaged`](./state_getKeysPaged) - Enumerate keys --- ## state_subscribeRuntimeVersion - JSON-RPC M... export const S = substrateSamples['bittensor']; # state_subscribeRuntimeVersion ## Description Subscribe to storage or runtime version updates over WebSocket. Drive live UIs that react to on‑chain changes. Subscribes to runtime version updates. Requires WebSocket. ## Code Examples > Not supported over HTTP; use WebSocket. {`import { ApiPromise, WsProvider } from '@polkadot/api'; const api = await ApiPromise.create({ provider: new WsProvider('${S.wsBase}') }); const unsub = await api.rpc.state.subscribeRuntimeVersion((v) => { console.log('runtime version:', v.toHuman()); }); // Later: await unsub();`} --- ## state_subscribeStorage - JSON-RPC Method export const S = substrateSamples['bittensor']; # state_subscribeStorage ## Description Subscribe to storage or runtime version updates over WebSocket. Drive live UIs that react to on‑chain changes. Subscribes to storage changes for the provided keys. Requires WebSocket endpoint. ## Code Examples > Not supported over HTTP; use WebSocket. {`import { ApiPromise, WsProvider } from '@polkadot/api'; const api = await ApiPromise.create({ provider: new WsProvider('${S.wsBase}') }); const unsub = await api.rpc.state.subscribeStorage([[ '${S.storageCodeKey}' ]], (changes) => { console.log('storage changed:', changes.toHuman()); }); // Later: await unsub();`} --- ## state_traceBlock - JSON-RPC Method export const S = substrateSamples['bittensor']; # state_traceBlock Traces a block execution. Typically restricted; may require node flags. > If disabled, the node may return an error or null. ## Code Examples --- ## state_unsubscribeRuntimeVersion - JSON-RPC... export const S = substrateSamples['bittensor']; # state_unsubscribeRuntimeVersion Cancels a subscription started with [state_subscribeRuntimeVersion](./state_subscribeRuntimeVersion). Provide the subscription ID returned by the subscribe call. This is a WebSocket-only method. --- ## state_unsubscribeStorage - JSON-RPC Method export const S = substrateSamples['bittensor']; # state_unsubscribeStorage Cancels a subscription started with [state_subscribeStorage](./state_subscribeStorage). Provide the subscription ID returned by the subscribe call. WebSocket-only. --- ## subnetInfo_getAllDynamicInfo - JSON-RPC Me... export const S = substrateSamples['bittensor']; # subnetInfo_getAllDynamicInfo ## Description Bittensor‑specific APIs to inspect subnets: hyperparameters, dynamic state, metagraphs, mechagraphs, and pruning hints. Use to build subnet dashboards and analytics. Returns dynamic info for all subnets (SCALE-encoded bytes). ## Code Examples --- ## subnetInfo_getAllMechagraphs - JSON-RPC Me... export const S = substrateSamples['bittensor']; # subnetInfo_getAllMechagraphs ## Description Bittensor‑specific APIs to inspect subnets: hyperparameters, dynamic state, metagraphs, mechagraphs, and pruning hints. Use to build subnet dashboards and analytics. Returns mechagraphs for all subnets. ## Code Examples --- ## subnetInfo_getAllMetagraphs - JSON-RPC Method export const S = substrateSamples['bittensor']; # subnetInfo_getAllMetagraphs ## Description Bittensor‑specific APIs to inspect subnets: hyperparameters, dynamic state, metagraphs, mechagraphs, and pruning hints. Use to build subnet dashboards and analytics. Returns metagraphs for all subnets. ## Code Examples --- ## subnetInfo_getColdkeyAutoStakeHotkey - JSO... export const S = substrateSamples['bittensor']; # subnetInfo_getColdkeyAutoStakeHotkey ## Description Bittensor‑specific APIs to inspect subnets: hyperparameters, dynamic state, metagraphs, mechagraphs, and pruning hints. Use to build subnet dashboards and analytics. Returns the hotkey auto-staked for a given coldkey and subnet. ## Code Examples --- ## subnetInfo_getDynamicInfo - JSON-RPC Method export const S = substrateSamples['bittensor']; # subnetInfo_getDynamicInfo ## Description Bittensor‑specific APIs to inspect subnets: hyperparameters, dynamic state, metagraphs, mechagraphs, and pruning hints. Use to build subnet dashboards and analytics. Returns dynamic info for a given `netuid`. ## Code Examples --- ## subnetInfo_getLockCost - JSON-RPC Method export const S = substrateSamples['bittensor']; # subnetInfo_getLockCost ## Description Bittensor‑specific APIs to inspect subnets: hyperparameters, dynamic state, metagraphs, mechagraphs, and pruning hints. Use to build subnet dashboards and analytics. Returns the current network lock cost (TAO). ## Code Examples --- ## subnetInfo_getMechagraph - JSON-RPC Method export const S = substrateSamples['bittensor']; # subnetInfo_getMechagraph ## Description Bittensor‑specific APIs to inspect subnets: hyperparameters, dynamic state, metagraphs, mechagraphs, and pruning hints. Use to build subnet dashboards and analytics. Returns mechagraph information for the given `netuid` and `mecid`. ## Code Examples --- ## subnetInfo_getMetagraph - JSON-RPC Method export const S = substrateSamples['bittensor']; # subnetInfo_getMetagraph ## Description Bittensor‑specific APIs to inspect subnets: hyperparameters, dynamic state, metagraphs, mechagraphs, and pruning hints. Use to build subnet dashboards and analytics. Returns the metagraph for a subnet `netuid`. ## Code Examples --- ## subnetInfo_getSelectiveMechagraph - JSON-R... export const S = substrateSamples['bittensor']; # subnetInfo_getSelectiveMechagraph ## Description Bittensor‑specific APIs to inspect subnets: hyperparameters, dynamic state, metagraphs, mechagraphs, and pruning hints. Use to build subnet dashboards and analytics. Returns mechagraph entries filtered by indexes for a subnet. ## Code Examples --- ## subnetInfo_getSelectiveMetagraph - JSON-RP... export const S = substrateSamples['bittensor']; # subnetInfo_getSelectiveMetagraph ## Description Bittensor‑specific APIs to inspect subnets: hyperparameters, dynamic state, metagraphs, mechagraphs, and pruning hints. Use to build subnet dashboards and analytics. Returns metagraph entries filtered by indexes for a subnet. ## Code Examples --- ## subnetInfo_getSubnetHyperparams - JSON-RPC... export const S = substrateSamples['bittensor']; # subnetInfo_getSubnetHyperparams ## Description Bittensor‑specific APIs to inspect subnets: hyperparameters, dynamic state, metagraphs, mechagraphs, and pruning hints. Use to build subnet dashboards and analytics. Returns SCALE-encoded hyperparameters for the specified subnet id. ## Code Examples --- ## subnetInfo_getSubnetHyperparamsV2 - JSON-R... export const S = substrateSamples['bittensor']; # subnetInfo_getSubnetHyperparamsV2 ## Description Bittensor‑specific APIs to inspect subnets: hyperparameters, dynamic state, metagraphs, mechagraphs, and pruning hints. Use to build subnet dashboards and analytics. Returns updated hyperparameters for a subnet (SCALE bytes). ## Code Examples --- ## subnetInfo_getSubnetInfo - JSON-RPC Method export const S = substrateSamples['bittensor']; # subnetInfo_getSubnetInfo ## Description Bittensor‑specific APIs to inspect subnets: hyperparameters, dynamic state, metagraphs, mechagraphs, and pruning hints. Use to build subnet dashboards and analytics. Returns SCALE-encoded info for the subnet identified by `netuid`. ## Parameters | Param | Type | Description | | --- | --- | --- | | `netuid` | number | Subnet id (e.g., 1) | | `at` | string? | Optional block hash | ## Code Examples --- ## subnetInfo_getSubnetInfo_v2 - JSON-RPC Method export const S = substrateSamples['bittensor']; # subnetInfo_getSubnetInfo_v2 ## Description Bittensor‑specific APIs to inspect subnets: hyperparameters, dynamic state, metagraphs, mechagraphs, and pruning hints. Use to build subnet dashboards and analytics. Returns V2 subnet info for `netuid`. ## Code Examples --- ## subnetInfo_getSubnetState - JSON-RPC Method export const S = substrateSamples['bittensor']; # subnetInfo_getSubnetState ## Description Bittensor‑specific APIs to inspect subnets: hyperparameters, dynamic state, metagraphs, mechagraphs, and pruning hints. Use to build subnet dashboards and analytics. Returns subnet state for `netuid`. ## Code Examples --- ## subnetInfo_getSubnetToPrune - JSON-RPC Method export const S = substrateSamples['bittensor']; # subnetInfo_getSubnetToPrune ## Description Bittensor‑specific APIs to inspect subnets: hyperparameters, dynamic state, metagraphs, mechagraphs, and pruning hints. Use to build subnet dashboards and analytics. Returns an optional netuid scheduled to prune. ## Code Examples --- ## subnetInfo_getSubnetsInfo - JSON-RPC Method export const S = substrateSamples['bittensor']; # subnetInfo_getSubnetsInfo ## Description Bittensor‑specific APIs to inspect subnets: hyperparameters, dynamic state, metagraphs, mechagraphs, and pruning hints. Use to build subnet dashboards and analytics. Returns SCALE-encoded information for all subnets. ## JavaScript (fetch) ## Decoding The result is SCALE-encoded bytes. Use polkadot.js with Bittensor type definitions to decode into rich structures (e.g., metagraphs, hyperparameters). See Bittensor runtime docs for exact types. ## Code Examples --- ## subnetInfo_getSubnetsInfo_v2 - JSON-RPC Me... export const S = substrateSamples['bittensor']; # subnetInfo_getSubnetsInfo_v2 ## Description Bittensor‑specific APIs to inspect subnets: hyperparameters, dynamic state, metagraphs, mechagraphs, and pruning hints. Use to build subnet dashboards and analytics. Returns V2 info for all subnets (SCALE bytes). ## Code Examples --- ## subscribe_newHead - JSON-RPC Method export const S = substrateSamples['bittensor']; # subscribe_newHead ## Description Interact with Substrate JSON‑RPC. This method is commonly used to build reliable indexers, developer tooling, and responsive UIs. Alias for subscribing to new heads. Use `chain_subscribeNewHeads` in modern clients. WebSocket-only. --- ## swap_currentAlphaPrice - JSON-RPC Method export const S = substrateSamples['bittensor']; # swap_currentAlphaPrice ## Description Bittensor swap helpers for TAO/ALPHA (price/simulation). Useful for quoting or UX previews; may be disabled on some nodes. Returns the current ALPHA price used by the swap pallet (may return null if not configured). ## Code Examples --- ## swap_simSwapAlphaForTao - JSON-RPC Method export const S = substrateSamples['bittensor']; # swap_simSwapAlphaForTao ## Description Bittensor swap helpers for TAO/ALPHA (price/simulation). Useful for quoting or UX previews; may be disabled on some nodes. Simulates a swap from ALPHA to TAO. May return null if disabled. ## Code Examples --- ## swap_simSwapTaoForAlpha - JSON-RPC Method export const S = substrateSamples['bittensor']; # swap_simSwapTaoForAlpha ## Description Bittensor swap helpers for TAO/ALPHA (price/simulation). Useful for quoting or UX previews; may be disabled on some nodes. Simulates a swap from TAO to ALPHA. May return null if disabled or illiquid. ## Code Examples --- ## system_accountNextIndex - JSON-RPC Method export const S = substrateSamples['bittensor']; # system_accountNextIndex ## Description Return the next valid account nonce. Use to construct signed extrinsics and avoid “future proof” or “bad nonce” errors. Returns the next valid transaction index (nonce) for an account. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `accountId` | string | Yes | Hex-encoded AccountId (32 bytes typical); example uses `${S.accountId}` | ## Code Examples --- ## system_addLogFilter - JSON-RPC Method export const S = substrateSamples['bittensor']; # system_addLogFilter ## Description Interact with Substrate JSON‑RPC. This method is commonly used to build reliable indexers, developer tooling, and responsive UIs. Adds a log filter to the running node. Administrative action; disabled on public RPC. ## Code Examples --- ## system_addReservedPeer - JSON-RPC Method export const S = substrateSamples['bittensor']; # system_addReservedPeer ## Description Interact with Substrate JSON‑RPC. This method is commonly used to build reliable indexers, developer tooling, and responsive UIs. Adds a reserved peer. Administrative action; disabled on public RPC. ## Code Examples --- ## system_chain - Bittensor RPC Method # system_chain Returns the chain name on Bittensor. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const chain = await api.rpc.system.chain(); console.log('Chain:', chain.toString()); await api.disconnect(); ``` ## Related Methods - [`system_name`](./system_name) - Get node implementation name - [`system_version`](./system_version) - Get node version --- ## system_chainType - JSON-RPC Method export const S = substrateSamples['bittensor']; # system_chainType ## Description Returns the network environment type reported by the node (for example, `Development`, `Local`, or `Live`). When to use it: - Gate behavior by environment (e.g., hide faucets or disable dangerous actions on `Live`). - Verify you are connected to the expected environment in CI, staging, or production. - Surface readable environment context in UIs and logs. It returns a short string such as `Live` for mainnet. ## Code Examples --- ## system_health - Bittensor RPC Method # system_health Returns the health status of the Bittensor node. ## Use Cases - **Health checks** - Monitor node availability - **Load balancing** - Route traffic based on health for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **Sync status** - Verify node is synced ## Parameters This method accepts no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `peers` | `Number` | Connected peer count | | `isSyncing` | `Boolean` | Whether node is syncing | | `shouldHavePeers` | `Boolean` | Whether node should have peers | ## Request ```json { "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const health = await api.rpc.system.health(); console.log('Peers:', health.peers.toNumber()); console.log('Is syncing:', health.isSyncing.isTrue); await api.disconnect(); ``` ```python def get_health(): url = 'https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'system_health', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] health = get_health() print(f"Peers: {health['peers']}") print(f"Syncing: {health['isSyncing']}") ``` ## Related Methods - [`system_version`](./system_version) - Get node version - [`system_chain`](./system_chain) - Get chain name --- ## system_localListenAddresses - JSON-RPC Method export const S = substrateSamples['bittensor']; # system_localListenAddresses ## Description Interact with Substrate JSON‑RPC. This method is commonly used to build reliable indexers, developer tooling, and responsive UIs. Returns multiaddr listen addresses the node is bound to. ## Code Examples --- ## system_localPeerId - JSON-RPC Method export const S = substrateSamples['bittensor']; # system_localPeerId ## Description Interact with Substrate JSON‑RPC. This method is commonly used to build reliable indexers, developer tooling, and responsive UIs. Returns the libp2p PeerId of the node. ## Code Examples --- ## system_name - Bittensor RPC Method # system_name Returns the node implementation name on Bittensor. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_name", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_name", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const name = await api.rpc.system.name(); console.log('Node name:', name.toString()); await api.disconnect(); ``` ## Related Methods - [`system_version`](./system_version) - Get node version - [`system_chain`](./system_chain) - Get chain name --- ## system_nodeRoles - JSON-RPC Method export const S = substrateSamples['bittensor']; # system_nodeRoles ## Description Interact with Substrate JSON‑RPC. This method is commonly used to build reliable indexers, developer tooling, and responsive UIs. Returns the configured node roles. ## Code Examples --- ## system_peers - JSON-RPC Method export const S = substrateSamples['bittensor']; # system_peers ## Description Returns a list of peers the node is currently connected to. When to use it: - Debug connectivity issues or peer churn. - Build network monitoring and operator dashboards. - Adapt UI behavior when the node is isolated or not fully peered. Note: On shared public RPC, the peer list may be masked or empty. ## Code Examples --- ## system_properties - Bittensor RPC Method # system_properties Returns chain properties including token symbol and decimals on Bittensor. ## Use Cases - **Token formatting** - Get decimals and symbol for decentralized AI inference, subnet-specific AI models, TAO staking, and cross-subnet AI collaboration - **UI configuration** - Configure wallets and dApps - **Address formatting** - Get SS58 prefix ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_properties", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_properties", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const props = await api.rpc.system.properties(); console.log('Token symbol:', props.tokenSymbol.toString()); console.log('Token decimals:', props.tokenDecimals.toString()); console.log('SS58 prefix:', props.ss58Format.toString()); await api.disconnect(); ``` ## Related Methods - [`system_chain`](./system_chain) - Get chain name - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## system_removeReservedPeer - JSON-RPC Method export const S = substrateSamples['bittensor']; # system_removeReservedPeer ## Description Interact with Substrate JSON‑RPC. This method is commonly used to build reliable indexers, developer tooling, and responsive UIs. Removes a peer from the reserved list. ## Code Examples --- ## system_reservedPeers - JSON-RPC Method export const S = substrateSamples['bittensor']; # system_reservedPeers ## Description Interact with Substrate JSON‑RPC. This method is commonly used to build reliable indexers, developer tooling, and responsive UIs. Returns the current reserved peer list. ## Code Examples --- ## system_resetLogFilter - JSON-RPC Method export const S = substrateSamples['bittensor']; # system_resetLogFilter ## Description Interact with Substrate JSON‑RPC. This method is commonly used to build reliable indexers, developer tooling, and responsive UIs. Resets the log filter to defaults. ## Code Examples --- ## system_syncState - JSON-RPC Method export const S = substrateSamples['bittensor']; # system_syncState ## Description Returns the node's sync progress (starting block, current, and highest). When to use it: - Health checks to ensure a node is caught up before serving traffic. - Gate API calls until the node is fully synced. - Display progress bars in admin panels or dashboards. ## Code Examples --- ## system_unstable_networkState - JSON-RPC Me... export const S = substrateSamples['bittensor']; # system_unstable_networkState ## Description Interact with Substrate JSON‑RPC. This method is commonly used to build reliable indexers, developer tooling, and responsive UIs. Returns diagnostic network information; API subject to change. ## Code Examples --- ## system_version - Bittensor RPC Method # system_version Returns the node implementation version on Bittensor. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_version", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_version", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const version = await api.rpc.system.version(); console.log('Version:', version.toString()); await api.disconnect(); ``` ## Related Methods - [`system_chain`](./system_chain) - Get chain name - [`state_getRuntimeVersion`](./state_getRuntimeVersion) - Get runtime version --- ## transactionWatch_v1_submitAndWatch - JSON-... export const S = substrateSamples['bittensor']; # transactionWatch_v1_submitAndWatch Submits a signed extrinsic and subscribes to status updates. Typically requires a self-hosted node. ## Code Examples --- ## transactionWatch_v1_unwatch - JSON-RPC Method export const S = substrateSamples['bittensor']; # transactionWatch_v1_unwatch ## Description Interact with Substrate JSON‑RPC. This method is commonly used to build reliable indexers, developer tooling, and responsive UIs. Cancels a transaction watch started by `transactionWatch_v1_submitAndWatch`. ## Code Examples --- ## transaction_v1_broadcast - JSON-RPC Method export const S = substrateSamples['bittensor']; # transaction_v1_broadcast ## Description Interact with Substrate JSON‑RPC. This method is commonly used to build reliable indexers, developer tooling, and responsive UIs. Broadcasts a transaction to peers. Requires node privileges. ## Code Examples --- ## transaction_v1_stop - JSON-RPC Method export const S = substrateSamples['bittensor']; # transaction_v1_stop ## Description Interact with Substrate JSON‑RPC. This method is commonly used to build reliable indexers, developer tooling, and responsive UIs. Stops a transaction processing job started previously. ## Code Examples --- ## unsubscribe_newHead - JSON-RPC Method export const S = substrateSamples['bittensor']; # unsubscribe_newHead ## Description Interact with Substrate JSON‑RPC. This method is commonly used to build reliable indexers, developer tooling, and responsive UIs. Alias for unsubscribing from new head notifications. Use `chain_unsubscribeNewHeads` for modern clients. --- ## web3_clientVersion - Bittensor RPC Method # web3_clientVersion Returns the current client version on Bittensor. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Client version string | ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); const version = await provider.send('web3_clientVersion', []); console.log('Client version:', version); ``` --- ## web3_sha3 - Bittensor RPC Method # web3_sha3 Returns Keccak-256 (not standard SHA3-256) of the given data on Bittensor. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `data` | `DATA` | Yes | Data to hash | ## Request ```json { "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Keccak-256 hash of the data | ## Code Examples ```bash curl -X POST https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bittensor-mainnet.n.dwellir.com/YOUR_API_KEY'); // Using RPC const hash = await provider.send('web3_sha3', ['0x68656c6c6f']); console.log('Hash:', hash); // Using ethers directly (faster) const localHash = keccak256(toUtf8Bytes('hello')); console.log('Local hash:', localHash); ``` --- ## debug_traceBlock - Blast RPC Method # debug_traceBlock Traces all transactions in a block on Blast by block RLP. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Analyze transaction execution step-by-step - **Smart contract analysis** - Debug contract interactions - **Security auditing** - Trace internal calls for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockRlp` | `DATA` | Yes | RLP-encoded block data | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Use debug_traceBlockByNumber instead (more practical) const traces = await provider.send('debug_traceBlockByNumber', ['latest', {}]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by block number - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by block hash --- ## debug_traceBlockByHash - Blast RPC Method # debug_traceBlockByHash Traces all transactions in a block on Blast by block hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0x645a6a1b48a2c3312d7bc389eb4f548acfbce860916e6894bd7b611d26f3de0f", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0x645a6a1b48a2c3312d7bc389eb4f548acfbce860916e6894bd7b611d26f3de0f", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0x645a6a1b48a2c3312d7bc389eb4f548acfbce860916e6894bd7b611d26f3de0f'; const traces = await provider.send('debug_traceBlockByHash', [blockHash, { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by number - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceBlockByNumber - Blast RPC Method # debug_traceBlockByNumber Traces all transactions in a block on Blast by block number. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('debug_traceBlockByNumber', ['latest', { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by hash - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceCall - Blast RPC Method # debug_traceCall Traces a call without creating a transaction on Blast. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction simulation** - Debug before sending - **Gas analysis** - Analyze gas usage per opcode - **Contract debugging** - Step through execution for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `call` | `Object` | Yes | Call object (same as eth_call) | | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ { "to": "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "data": "0x70a08231000000000000000000000000A8b2218036Eab12e58e02f88E8825723aB4C5E5f" }, "latest", {} ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ {"to": "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "data": "0x70a08231000000000000000000000000A8b2218036Eab12e58e02f88E8825723aB4C5E5f"}, "latest", {"tracer": "callTracer"} ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const trace = await provider.send('debug_traceCall', [ { to: '0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f', data: '0x70a08231000000000000000000000000A8b2218036Eab12e58e02f88E8825723aB4C5E5f' }, 'latest', { tracer: 'callTracer' } ]); console.log('Trace:', trace); ``` ## Related Methods - [`eth_call`](./eth_call) - Execute call without trace - [`debug_traceTransaction`](./debug_traceTransaction) - Trace actual transaction --- ## debug_traceTransaction - Blast RPC Method # debug_traceTransaction Traces a transaction execution on Blast by transaction hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Understand exactly what happened - **Failure analysis** - Find where and why a transaction reverted - **Gas optimization** - Analyze gas usage for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Tracer Options - `{}` - Default opcode tracer (verbose) - `{ tracer: "callTracer" }` - Call tree tracer - `{ tracer: "prestateTracer" }` - Pre-state tracer ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x56f0fad1416d7e1ce20a18fc488c0d850c24b0bd4297f51bb901eeb24346bbe2", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x56f0fad1416d7e1ce20a18fc488c0d850c24b0bd4297f51bb901eeb24346bbe2", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x56f0fad1416d7e1ce20a18fc488c0d850c24b0bd4297f51bb901eeb24346bbe2'; // Call tracer - shows internal calls const callTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'callTracer' } ]); console.log('Type:', callTrace.type); console.log('From:', callTrace.from); console.log('To:', callTrace.to); console.log('Gas used:', parseInt(callTrace.gasUsed, 16)); // Prestate tracer - shows state before execution const prestateTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'prestateTracer' } ]); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x56f0fad1416d7e1ce20a18fc488c0d850c24b0bd4297f51bb901eeb24346bbe2' # Call tracer trace = w3.provider.make_request('debug_traceTransaction', [ tx_hash, {'tracer': 'callTracer'} ]) print(f'Trace type: {trace["result"]["type"]}') print(f'Gas used: {int(trace["result"]["gasUsed"], 16)}') ``` ## Related Methods - [`debug_traceCall`](./debug_traceCall) - Trace without executing - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace entire block --- ## eth_accounts - Blast RPC Method # eth_accounts Returns a list of addresses owned by the client on Blast. > **Why Blast?** Build on the only Ethereum L2 with native yield—4% for ETH and 5%+ for stablecoins automatically with $2.5B+ TVL, auto-rebasing ETH and USDB, gas revenue sharing for developers, and Blur-backed ecosystem. ## Important Note On public RPC endpoints like Dwellir, `eth_accounts` returns an empty array because the node does not hold any private keys. This method is primarily useful for: - Local development nodes (Ganache, Hardhat, Anvil) - Private nodes with managed accounts - Wallet provider connections (MetaMask injects accounts) ## When to Use This Method `eth_accounts` is relevant for DeFi developers, yield protocol builders, and teams building passive-income dApps in specific scenarios: - **Development Testing** — Retrieve test accounts from local nodes - **Wallet Detection** — Check if a wallet provider has connected accounts - **Client Verification** — Confirm node account access capabilities ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `Array` | List of 20-byte account addresses owned by the client | **Return format**: Array of `0x` prefixed hexadecimal addresses (typically empty for public nodes) ## Request ```json { "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 } ``` ## Response ### Successful Response (Public Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [] } ``` ### Successful Response (Local Development Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [ "0x407d73d8a49eeb85d32cf465507dd71d507100c1", "0x85d32cf465507dd71d507100c1407d73d8a49eeb" ] } ``` ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_accounts', params: [], id: 1 }) }); const { result } = await response.json(); console.log('Accounts:', result); // Using ethers.js const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const accounts = await provider.listAccounts(); console.log('Accounts:', accounts); ``` ```python def get_accounts(): response = requests.post( 'https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_accounts', 'params': [], 'id': 1 } ) return response.json()['result'] accounts = get_accounts() print(f'Accounts: {accounts}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) print(f'Accounts: {w3.eth.accounts}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/rpc" ) func main() { client, err := rpc.Dial("https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } var accounts []string err = client.CallContext(context.Background(), &accounts, "eth_accounts") if err != nil { log.Fatal(err) } fmt.Printf("Accounts: %v\n", accounts) } ``` ## Common Use Cases ### 1. Development Environment Detection Check if running against a development node with test accounts: ```javascript async function isDevEnvironment(provider) { const accounts = await provider.listAccounts(); return accounts.length > 0; } const isDev = await isDevEnvironment(provider); if (isDev) { console.log('Development environment detected'); } ``` ### 2. Wallet Connection Check Verify wallet provider has connected accounts: ```javascript async function checkWalletConnection() { if (typeof window.ethereum === 'undefined') { return { connected: false, reason: 'No wallet detected' }; } const accounts = await window.ethereum.request({ method: 'eth_accounts' }); return { connected: accounts.length > 0, accounts: accounts }; } ``` ### 3. Fallback Account Selection Use first available account or request connection: ```javascript async function getActiveAccount() { // Check existing connections let accounts = await window.ethereum.request({ method: 'eth_accounts' }); // Request connection if no accounts if (accounts.length === 0) { accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); } return accounts[0] || null; } ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32601 | Method not found | Node may not support this method | | -32603 | Internal error | Retry with exponential backoff | ```javascript async function safeGetAccounts(provider) { try { const accounts = await provider.listAccounts(); return { success: true, accounts }; } catch (error) { if (error.code === -32601) { console.warn('eth_accounts not supported on this node'); return { success: false, accounts: [], reason: 'unsupported' }; } throw error; } } ``` ## Related Methods - [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102) — Request wallet connection (browser wallets) - [`eth_getBalance`](./eth_getBalance) — Get account balance - [`eth_getTransactionCount`](./eth_getTransactionCount) — Get account nonce --- ## eth_blockNumber - Blast RPC Method # eth_blockNumber Returns the number of the most recent block on Blast. > **Why Blast?** Build on the only Ethereum L2 with native yield—4% for ETH and 5%+ for stablecoins automatically with $2.5B+ TVL, auto-rebasing ETH and USDB, gas revenue sharing for developers, and Blur-backed ecosystem. ## When to Use This Method `eth_blockNumber` is fundamental for DeFi developers, yield protocol builders, and teams building passive-income dApps: - **Syncing Applications** — Keep your dApp in sync with the latest Blast blockchain state - **Transaction Monitoring** — Verify confirmations by comparing block numbers - **Event Filtering** — Set the correct block range for querying logs on yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications - **Health Checks** — Monitor node connectivity and sync status ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `QUANTITY` | Hexadecimal string representing the current block number | **Return format**: `0x` prefixed hexadecimal (e.g., `0x5BAD55` = 6,008,149 in decimal) ## Request ```json { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } ``` ## Response ### Successful Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5BAD55" } ``` ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error" } } ``` ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }) }); const { result } = await response.json(); const blockNumber = parseInt(result, 16); console.log('Blast block:', blockNumber); // Using ethers.js const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockNumber = await provider.getBlockNumber(); console.log('Blast block:', blockNumber); ``` ```python def get_block_number(): response = requests.post( 'https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_blockNumber', 'params': [], 'id': 1 } ) result = response.json()['result'] return int(result, 16) block_number = get_block_number() print(f'Blast block: {block_number}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) print(f'Blast block: {w3.eth.block_number}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockNumber, err := client.BlockNumber(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Blast block: %d\n", blockNumber) } ``` ## Common Use Cases ### 1. Block Confirmation Counter Monitor transaction confirmations on Blast: ```javascript async function getConfirmations(provider, txHash) { const tx = await provider.getTransaction(txHash); if (!tx || !tx.blockNumber) return 0; const currentBlock = await provider.getBlockNumber(); return currentBlock - tx.blockNumber + 1; } // Wait for specific confirmations async function waitForConfirmations(provider, txHash, confirmations = 6) { let currentConfirmations = 0; while (currentConfirmations < confirmations) { currentConfirmations = await getConfirmations(provider, txHash); console.log(`Confirmations: ${currentConfirmations}/${confirmations}`); await new Promise(r => setTimeout(r, 2000)); } return true; } ``` ### 2. Event Log Filtering Query events from recent blocks on Blast: ```javascript async function getRecentEvents(provider, contract, eventName, blockRange = 100) { const currentBlock = await provider.getBlockNumber(); const fromBlock = currentBlock - blockRange; const filter = contract.filters[eventName](); const events = await contract.queryFilter(filter, fromBlock, currentBlock); return events; } ``` ### 3. Node Health Monitoring Check if your Blast node is synced: ```javascript async function checkNodeHealth(provider) { try { const blockNumber = await provider.getBlockNumber(); const block = await provider.getBlock(blockNumber); const now = Date.now() / 1000; const blockAge = now - block.timestamp; if (blockAge > 60) { console.warn(`Node may be behind. Last block was ${blockAge}s ago`); return false; } console.log(`Node healthy. Latest block: ${blockNumber}`); return true; } catch (error) { console.error('Node unreachable:', error); return false; } } ``` ## Performance Optimization ### Caching Strategy Cache block numbers to reduce API calls: ```javascript class BlockNumberCache { constructor(ttl = 2000) { this.cache = null; this.timestamp = 0; this.ttl = ttl; } async get(provider) { const now = Date.now(); if (this.cache && (now - this.timestamp) < this.ttl) { return this.cache; } this.cache = await provider.getBlockNumber(); this.timestamp = now; return this.cache; } invalidate() { this.cache = null; this.timestamp = 0; } } const blockCache = new BlockNumberCache(); ``` ### Batch Requests Combine with other calls for efficiency: ```javascript const batch = [ { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }, { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 }, { jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 } ]; const response = await fetch('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await response.json(); ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32603 | Internal error | Retry with exponential backoff | | -32005 | Rate limit exceeded | Implement rate limiting client-side | | -32000 | Execution reverted | Check node sync status | ```javascript async function safeGetBlockNumber(provider, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await provider.getBlockNumber(); } catch (error) { if (error.code === -32005) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } else if (i === maxRetries - 1) { throw error; } } } } ``` ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) — Get full block details by number - [`eth_getBlockByHash`](./eth_getBlockByHash) — Get block details by hash - [`eth_syncing`](./eth_syncing) — Check if node is still syncing --- ## eth_call - Blast RPC Method # eth_call Executes a new message call immediately without creating a transaction on Blast. Used for reading smart contract state. > **Why Blast?** Build on the only Ethereum L2 with native yield—4% for ETH and 5%+ for stablecoins automatically with $2.5B+ TVL, auto-rebasing ETH and USDB, gas revenue sharing for developers, and Blur-backed ecosystem. ## Use Cases The `eth_call` method is essential for: - **Reading contract state** - Query view/pure functions - **Simulating transactions** - Test execution without gas costs - **DeFi integrations** - Check prices, balances, allowances for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications - **Complex queries** - Execute multi-step contract logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | 20-byte address executing the call | | `to` | `DATA` | Yes | 20-byte contract address | | `gas` | `QUANTITY` | No | Gas limit for the call | | `gasPrice` | `QUANTITY` | No | Gas price in wei | | `value` | `QUANTITY` | No | Value to send in wei | | `data` | `DATA` | Yes | Encoded function call data | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_call", "params": [ { "to": "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "data": "0x70a08231000000000000000000000000A8b2218036Eab12e58e02f88E8825723aB4C5E5f" }, "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | The return value of the executed contract function | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000" } ``` ## Code Examples ```bash # Call ERC20 balanceOf function curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{ "to": "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "data": "0x70a08231000000000000000000000000A8b2218036Eab12e58e02f88E8825723aB4C5E5f" }, "latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // ERC20 ABI for common functions const ERC20_ABI = [ "function balanceOf(address owner) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function totalSupply() view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)" ]; // Read ERC20 token balance async function getTokenBalance(tokenAddress, walletAddress) { const contract = new Contract(tokenAddress, ERC20_ABI, provider); const balance = await contract.balanceOf(walletAddress); const decimals = await contract.decimals(); const symbol = await contract.symbol(); return { raw: balance.toString(), formatted: (Number(balance) / Math.pow(10, decimals)).toFixed(4), symbol: symbol }; } // Direct eth_call async function directCall(to, data) { const result = await provider.call({ to, data }); return result; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) def get_erc20_balance(token_address, wallet_address): # balanceOf(address) selector function_signature = "balanceOf(address)" function_selector = w3.keccak(text=function_signature)[:4].hex() # Encode address parameter encoded_address = wallet_address[2:].lower().zfill(64) data = function_selector + encoded_address # Make the call result = w3.eth.call({ 'to': token_address, 'data': data }) return int(result.hex(), 16) balance = get_erc20_balance( '0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f', '0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f' ) print(f'Balance: {balance}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f") data := common.FromHex("0x70a08231000000000000000000000000A8b2218036Eab12e58e02f88E8825723aB4C5E5f") msg := ethereum.CallMsg{ To: &contractAddress, Data: data, } result, err := client.CallContract(context.Background(), msg, nil) if err != nil { log.Fatal(err) } fmt.Printf("Result: 0x%x\n", result) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Contract function reverted | | -32602 | Invalid parameters | Invalid data encoding | | -32015 | VM execution error | Contract logic error | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas for transaction - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send actual transaction --- ## eth_chainId - Blast RPC Method # eth_chainId Returns the chain ID used for transaction signing on Blast. > **Why Blast?** Build on the only Ethereum L2 with native yield—4% for ETH and 5%+ for stablecoins automatically with $2.5B+ TVL, auto-rebasing ETH and USDB, gas revenue sharing for developers, and Blur-backed ecosystem. ## Use Cases The `eth_chainId` method is essential for: - **Transaction signing** - Ensure transactions are signed for the correct network - **Network verification** - Confirm connection to the expected chain - **Multi-chain apps** - Handle different networks programmatically - **Wallet integration** - Validate network before transactions ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Chain ID in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1" } ``` ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const network = await provider.getNetwork(); console.log('Chain ID:', network.chainId); // Verify network before transaction async function verifyNetwork(expectedChainId) { const network = await provider.getNetwork(); if (network.chainId !== BigInt(expectedChainId)) { throw new Error(`Wrong network. Expected ${expectedChainId}, got ${network.chainId}`); } return true; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) chain_id = w3.eth.chain_id print(f'Chain ID: {chain_id}') # Verify network def verify_network(expected_chain_id): chain_id = w3.eth.chain_id if chain_id != expected_chain_id: raise ValueError(f'Wrong network. Expected {expected_chain_id}, got {chain_id}') return True ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } chainID, err := client.ChainID(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Chain ID: %d\n", chainID) } ``` ## Related Methods - [`net_version`](./net_version) - Get network version - [`eth_syncing`](./eth_syncing) - Check sync status --- ## eth_coinbase - Get coinbase address(Blast) # eth_coinbase Get coinbase address on the Blast network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_coinbase](https://ethereum.org/developers/docs/apis/json-rpc/#eth_coinbase) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_coinbase", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_coinbase', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Blast documentation](/docs/blast).* --- ## eth_estimateGas - Blast RPC Method # eth_estimateGas Estimates the gas necessary to execute a transaction on Blast. > **Why Blast?** Build on the only Ethereum L2 with native yield—4% for ETH and 5%+ for stablecoins automatically with $2.5B+ TVL, auto-rebasing ETH and USDB, gas revenue sharing for developers, and Blur-backed ecosystem. ## Use Cases The `eth_estimateGas` method is essential for: - **Transaction preparation** - Set appropriate gas limits - **Cost estimation** - Calculate transaction costs before sending - **Error detection** - Identify reverts before spending gas - **DeFi operations** - Estimate costs for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | Sender address | | `to` | `DATA` | No | Recipient address | | `gas` | `QUANTITY` | No | Gas limit | | `gasPrice` | `QUANTITY` | No | Gas price | | `value` | `QUANTITY` | No | Value in wei | | `data` | `DATA` | No | Transaction data | ## Request ```json { "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "to": "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "value": "0x1" }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Estimated gas amount in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5208" } ``` **Note**: `0x5208` = 21000 gas (standard ETH transfer) ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "to": "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "value": "0x1" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Estimate simple transfer async function estimateTransfer(to, value) { const gasEstimate = await provider.estimateGas({ to: to, value: parseEther(value) }); console.log('Estimated gas:', gasEstimate.toString()); return gasEstimate; } // Estimate contract call async function estimateContractCall(contract, method, args) { const gasEstimate = await contract[method].estimateGas(...args); console.log('Estimated gas:', gasEstimate.toString()); // Add 20% buffer for safety return gasEstimate * 120n / 100n; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) def estimate_transfer(to, value_in_ether): gas_estimate = w3.eth.estimate_gas({ 'to': to, 'value': w3.to_wei(value_in_ether, 'ether') }) print(f'Estimated gas: {gas_estimate}') return gas_estimate def estimate_contract_call(contract, method, args): func = getattr(contract.functions, method) gas_estimate = func(*args).estimate_gas() # Add 20% buffer return int(gas_estimate * 1.2) # Estimate simple transfer gas = estimate_transfer('0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f', 0.1) ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } toAddress := common.HexToAddress("0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f") msg := ethereum.CallMsg{ To: &toAddress, Value: big.NewInt(1000000000000000000), } gasLimit, err := client.EstimateGas(context.Background(), msg) if err != nil { log.Fatal(err) } fmt.Printf("Estimated gas: %d\n", gasLimit) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Transaction would fail | | -32602 | Invalid params | Invalid transaction parameters | **Tip**: If estimation fails, the transaction would likely revert if sent. ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_feeHistory - Blast RPC Method # eth_feeHistory Returns historical gas information on Blast for fee estimation. ## Use Cases - **Fee prediction** - Estimate future gas prices based on history - **Gas analytics** - Analyze fee trends over time - **Optimal timing** - Find best times for transactions on yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockCount` | `QUANTITY` | Yes | Number of blocks in the range | | `newestBlock` | `QUANTITY\|TAG` | Yes | Highest block of the range | | `rewardPercentiles` | `Array` | Yes | Percentiles to sample for priority fees | ## Request ```json { "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const feeHistory = await provider.send('eth_feeHistory', ['0xa', 'latest', [25, 50, 75]]); console.log('Base fees:', feeHistory.baseFeePerGas.map(f => formatUnits(f, 'gwei'))); console.log('Reward (25th percentile):', feeHistory.reward.map(r => formatUnits(r[0], 'gwei'))); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) fee_history = w3.eth.fee_history(10, 'latest', [25, 50, 75]) print(f'Base fees: {[w3.from_wei(f, "gwei") for f in fee_history["baseFeePerGas"]]}') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee --- ## eth_gasPrice - Blast RPC Method # eth_gasPrice Returns the current gas price on Blast in wei. > **Why Blast?** Build on the only Ethereum L2 with native yield—4% for ETH and 5%+ for stablecoins automatically with $2.5B+ TVL, auto-rebasing ETH and USDB, gas revenue sharing for developers, and Blur-backed ecosystem. ## Use Cases The `eth_gasPrice` method is essential for: - **Transaction pricing** - Set appropriate gas prices - **Cost estimation** - Calculate transaction costs before sending - **Gas monitoring** - Track network congestion - **DeFi operations** - Optimize costs for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Current gas price in wei (hexadecimal) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x3b9aca00" } ``` **Note**: `0x3b9aca00` = 1 Gwei (1,000,000,000 wei) ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); const gasPrice = feeData.gasPrice; console.log('Gas Price:', formatUnits(gasPrice, 'gwei'), 'Gwei'); // Calculate transaction cost async function estimateTransactionCost(gasLimit) { const feeData = await provider.getFeeData(); const cost = feeData.gasPrice * BigInt(gasLimit); return formatUnits(cost, 'ether'); } const cost = await estimateTransactionCost(21000); console.log('Transfer cost:', cost, 'ETH'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) gas_price = w3.eth.gas_price print(f'Gas Price: {w3.from_wei(gas_price, "gwei")} Gwei') # Calculate transaction cost def estimate_transaction_cost(gas_limit): gas_price = w3.eth.gas_price cost = gas_price * gas_limit return w3.from_wei(cost, 'ether') cost = estimate_transaction_cost(21000) print(f'Transfer cost: {cost} ETH') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } gasPrice, err := client.SuggestGasPrice(context.Background()) if err != nil { log.Fatal(err) } // Convert to Gwei gwei := new(big.Float).Quo( new(big.Float).SetInt(gasPrice), big.NewFloat(1e9), ) fmt.Printf("Gas Price: %f Gwei\n", gwei) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32603 | Internal error | Node error | ## Related Methods - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee (EIP-1559) - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas needed --- ## eth_getBalance - Blast RPC Method # eth_getBalance Returns the balance of a given address on Blast. > **Why Blast?** Build on the only Ethereum L2 with native yield—4% for ETH and 5%+ for stablecoins automatically with $2.5B+ TVL, auto-rebasing ETH and USDB, gas revenue sharing for developers, and Blur-backed ecosystem. ## Use Cases The `eth_getBalance` method is essential for: - **Wallet applications** - Display user balances - **Transaction validation** - Check if account has sufficient funds - **DeFi applications** - Monitor collateral and liquidity for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications - **Account monitoring** - Track balance changes over time ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address to check balance for | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Integer of the current balance in wei (hexadecimal) | **Note**: 1 native token = 10^18 wei. Convert using `balance / 10^18`. ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1a055690d9db80000" } ``` ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f'; const balanceWei = await provider.getBalance(address); const balance = formatEther(balanceWei); console.log(`Balance: ${balance}`); // Get balance at specific block const historicalBalance = await provider.getBalance(address, 1000000); console.log(`Historical balance: ${formatEther(historicalBalance)}`); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f' balance_wei = w3.eth.get_balance(address) balance = w3.from_wei(balance_wei, 'ether') print(f'Balance: {balance}') # Get balance at specific block historical_balance = w3.eth.get_balance(address, block_identifier=1000000) print(f'Historical balance: {w3.from_wei(historical_balance, "ether")}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f") balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } // Convert to ether fbalance := new(big.Float).SetInt(balance) ethValue := new(big.Float).Quo(fbalance, big.NewFloat(1e18)) fmt.Printf("Balance: %f\n", ethValue) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid address format or block parameter | | -32000 | Execution error | Node execution error | ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_getTransactionCount`](./eth_getTransactionCount) - Get account nonce --- ## eth_getBlockByHash - Blast RPC Method # eth_getBlockByHash Returns information about a block by hash on Blast. > **Why Blast?** Build on the only Ethereum L2 with native yield—4% for ETH and 5%+ for stablecoins automatically with $2.5B+ TVL, auto-rebasing ETH and USDB, gas revenue sharing for developers, and Blur-backed ecosystem. ## Use Cases The `eth_getBlockByHash` method is essential for: - **Block verification** - Verify block data using its unique hash - **Chain reorganization handling** - Track blocks during reorgs - **Cross-chain bridges** - Verify block finality for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications - **Deterministic queries** - Get consistent block data regardless of chain state ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0x645a6a1b48a2c3312d7bc389eb4f548acfbce860916e6894bd7b611d26f3de0f", false ], "id": 1 } ``` ## Returns Returns the same block object as `eth_getBlockByNumber`, or `null` if no block is found. | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used | | `transactions` | `Array` | Transaction objects or hashes | ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0x645a6a1b48a2c3312d7bc389eb4f548acfbce860916e6894bd7b611d26f3de0f", false ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0x645a6a1b48a2c3312d7bc389eb4f548acfbce860916e6894bd7b611d26f3de0f'; const block = await provider.getBlock(blockHash); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) block_hash = '0x645a6a1b48a2c3312d7bc389eb4f548acfbce860916e6894bd7b611d26f3de0f' block = w3.eth.get_block(block_hash) print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockHash := common.HexToHash("0x645a6a1b48a2c3312d7bc389eb4f548acfbce860916e6894bd7b611d26f3de0f") block, err := client.BlockByHash(context.Background(), blockHash) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block hash format | | -32000 | Block not found | Block with this hash does not exist | ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) - Get block by number - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number --- ## eth_getBlockByNumber - Blast RPC Method # eth_getBlockByNumber Returns information about a block by block number on Blast. > **Why Blast?** Build on the only Ethereum L2 with native yield—4% for ETH and 5%+ for stablecoins automatically with $2.5B+ TVL, auto-rebasing ETH and USDB, gas revenue sharing for developers, and Blur-backed ecosystem. ## Use Cases The `eth_getBlockByNumber` method is essential for: - **Block explorers** - Display complete block information - **Transaction indexers** - Process all transactions in a block - **Analytics platforms** - Analyze blockchain data for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications - **Timestamp verification** - Get block timestamps for time-based logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used by all transactions | | `gasLimit` | `QUANTITY` | Maximum gas allowed in block | | `transactions` | `Array` | Array of transaction objects or hashes | | `baseFeePerGas` | `QUANTITY` | Base fee per gas (EIP-1559) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": { "number": "0x5BAD55", "hash": "0x645a6a1b48a2c3312d7bc389eb4f548acfbce860916e6894bd7b611d26f3de0f", "parentHash": "0x...", "timestamp": "0x64d8f6d0", "gasUsed": "0x1234", "gasLimit": "0x1c9c380", "transactions": [], "baseFeePerGas": "0x5f5e100" } } ``` ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Get latest block const block = await provider.getBlock('latest'); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); console.log('Transactions:', block.transactions.length); // Get block with full transactions const blockWithTxs = await provider.getBlock('latest', true); for (const tx of blockWithTxs.prefetchedTransactions) { console.log('Transaction:', tx.hash); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) # Get latest block block = w3.eth.get_block('latest') print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') print(f'Transactions: {len(block.transactions)}') # Get block with full transactions block_full = w3.eth.get_block('latest', full_transactions=True) for tx in block_full.transactions: print(f'Transaction: {tx.hash.hex()}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } // Get latest block block, err := client.BlockByNumber(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) fmt.Printf("Timestamp: %d\n", block.Time()) fmt.Printf("Transactions: %d\n", len(block.Transactions())) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block number or parameter format | | -32000 | Block not found | Block does not exist | ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number - [`eth_getBlockByHash`](./eth_getBlockByHash) - Get block by hash - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_getCode - Blast RPC Method # eth_getCode Returns the bytecode at a given address on Blast. > **Why Blast?** Build on the only Ethereum L2 with native yield—4% for ETH and 5%+ for stablecoins automatically with $2.5B+ TVL, auto-rebasing ETH and USDB, gas revenue sharing for developers, and Blur-backed ecosystem. ## Use Cases The `eth_getCode` method is essential for: - **Contract verification** - Check if address is a contract - **Security analysis** - Verify deployed bytecode matches expected - **DeFi integrations** - Validate contracts before interactions - **Protocol analysis** - Analyze contract deployments for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Contract bytecode or `0x` if EOA | ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f'; const code = await provider.getCode(address); if (code === '0x') { console.log('Address is an EOA (externally owned account)'); } else { console.log('Address is a contract'); console.log('Bytecode length:', code.length); } // Check if address is a contract async function isContract(address) { const code = await provider.getCode(address); return code !== '0x'; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f' code = w3.eth.get_code(address) if code == b'': print('Address is an EOA') else: print('Address is a contract') print(f'Bytecode length: {len(code.hex())}') # Check if address is a contract def is_contract(address): code = w3.eth.get_code(address) return code != b'' ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f") code, err := client.CodeAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } if len(code) == 0 { fmt.Println("Address is an EOA") } else { fmt.Printf("Contract bytecode length: %d\n", len(code)) } } ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_getStorageAt`](./eth_getStorageAt) - Get contract storage --- ## eth_getFilterChanges - Blast RPC Method # eth_getFilterChanges Polling method for a filter on Blast, returns an array of logs since last poll. ## Use Cases - **Event streaming** - Get new events incrementally - **Real-time monitoring** - Track contract activity for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications - **Efficient indexing** - Process only new events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Poll loop async function pollFilter(filterId, interval = 2000) { while (true) { const changes = await provider.send('eth_getFilterChanges', [filterId]); if (changes.length > 0) { console.log('New events:', changes); } await new Promise(r => setTimeout(r, interval)); } } ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter --- ## eth_getFilterLogs - Blast RPC Method # eth_getFilterLogs Returns an array of all logs matching filter with given ID on Blast. ## Use Cases - **Historical queries** - Get all matching logs for a filter - **Full event history** - Retrieve complete event data for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const logs = await provider.send('eth_getFilterLogs', [filterId]); console.log('All matching logs:', logs.length); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_getLogs - Blast RPC Method # eth_getLogs Returns an array of all logs matching a given filter object on Blast. > **Why Blast?** Build on the only Ethereum L2 with native yield—4% for ETH and 5%+ for stablecoins automatically with $2.5B+ TVL, auto-rebasing ETH and USDB, gas revenue sharing for developers, and Blur-backed ecosystem. ## Use Cases The `eth_getLogs` method is essential for: - **Event indexing** - Track contract events for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications - **Token transfers** - Monitor ERC20/ERC721 transfers - **DeFi analytics** - Track swaps, liquidity events, and more - **Notification systems** - Alert on specific on-chain events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block (default: `"latest"`) | | `toBlock` | `QUANTITY\|TAG` | No | Ending block (default: `"latest"`) | | `address` | `DATA\|Array` | No | Contract address(es) to filter | | `topics` | `Array` | No | Array of topic filters | | `blockHash` | `DATA` | No | Filter single block by hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns Array of log objects: | Field | Type | Description | |-------|------|-------------| | `address` | `DATA` | Contract that emitted the log | | `topics` | `Array` | Array of indexed topics | | `data` | `DATA` | Non-indexed log data | | `blockNumber` | `QUANTITY` | Block number | | `transactionHash` | `DATA` | Transaction hash | | `logIndex` | `QUANTITY` | Log index in block | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": [{ "address": "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."], "data": "0x...", "blockNumber": "0x5BAD55", "transactionHash": "0x...", "logIndex": "0x0" }] } ``` ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Get Transfer events const TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'; async function getTransferEvents(tokenAddress, fromBlock, toBlock) { const logs = await provider.getLogs({ address: tokenAddress, topics: [TRANSFER_TOPIC], fromBlock: fromBlock, toBlock: toBlock }); return logs.map(log => ({ from: '0x' + log.topics[1].slice(26), to: '0x' + log.topics[2].slice(26), blockNumber: log.blockNumber, transactionHash: log.transactionHash })); } const events = await getTransferEvents( '0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f', 'latest', 'latest' ); console.log('Transfer events:', events); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' def get_transfer_events(token_address, from_block, to_block): logs = w3.eth.get_logs({ 'address': token_address, 'topics': [TRANSFER_TOPIC], 'fromBlock': from_block, 'toBlock': to_block }) events = [] for log in logs: events.append({ 'from': '0x' + log['topics'][1].hex()[26:], 'to': '0x' + log['topics'][2].hex()[26:], 'block': log['blockNumber'], 'tx': log['transactionHash'].hex() }) return events events = get_transfer_events( '0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f', 'latest', 'latest' ) print(f'Found {len(events)} transfer events') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f") transferTopic := common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef") query := ethereum.FilterQuery{ FromBlock: big.NewInt(0), ToBlock: nil, Addresses: []common.Address{contractAddress}, Topics: [][]common.Hash, } logs, err := client.FilterLogs(context.Background(), query) if err != nil { log.Fatal(err) } fmt.Printf("Found %d events\n", len(logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32005 | Query returned more than 10000 results | Reduce block range | | -32602 | Invalid params | Invalid filter parameters | ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create a filter for logs - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for new logs --- ## eth_getStorageAt - Blast RPC Method # eth_getStorageAt Returns the value from a storage position at a given address on Blast. ## Use Cases - **Contract analysis** - Read raw storage values - **State verification** - Verify contract state - **Security auditing** - Analyze storage layout for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications - **Protocol monitoring** - Track state changes ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte contract address | | `position` | `QUANTITY` | Yes | Storage slot position | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "0x0", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "0x0", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f'; const slot = 0; const storage = await provider.getStorage(address, slot); console.log('Storage at slot 0:', storage); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f' storage = w3.eth.get_storage_at(address, 0) print(f'Storage at slot 0: {storage.hex()}') ``` ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_call`](./eth_call) - Call contract functions --- ## eth_getTransactionByHash - Blast RPC Method # eth_getTransactionByHash Returns the information about a transaction by transaction hash on Blast. > **Why Blast?** Build on the only Ethereum L2 with native yield—4% for ETH and 5%+ for stablecoins automatically with $2.5B+ TVL, auto-rebasing ETH and USDB, gas revenue sharing for developers, and Blur-backed ecosystem. ## Use Cases The `eth_getTransactionByHash` method is essential for: - **Transaction tracking** - Get details of pending or confirmed transactions - **Payment verification** - Verify transaction parameters - **Debugging** - Analyze transaction data for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications - **Block explorers** - Display transaction information ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x56f0fad1416d7e1ce20a18fc488c0d850c24b0bd4297f51bb901eeb24346bbe2"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `hash` | `DATA` | Transaction hash | | `from` | `DATA` | Sender address | | `to` | `DATA` | Recipient address | | `value` | `QUANTITY` | Value in wei | | `gas` | `QUANTITY` | Gas provided | | `gasPrice` | `QUANTITY` | Gas price in wei | | `input` | `DATA` | Transaction input data | | `nonce` | `QUANTITY` | Sender's nonce | | `blockHash` | `DATA` | Block hash (null if pending) | | `blockNumber` | `QUANTITY` | Block number (null if pending) | ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x56f0fad1416d7e1ce20a18fc488c0d850c24b0bd4297f51bb901eeb24346bbe2"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x56f0fad1416d7e1ce20a18fc488c0d850c24b0bd4297f51bb901eeb24346bbe2'; const tx = await provider.getTransaction(txHash); if (tx) { console.log('From:', tx.from); console.log('To:', tx.to); console.log('Value:', formatEther(tx.value)); console.log('Block:', tx.blockNumber); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x56f0fad1416d7e1ce20a18fc488c0d850c24b0bd4297f51bb901eeb24346bbe2' tx = w3.eth.get_transaction(tx_hash) if tx: print(f'From: {tx["from"]}') print(f'To: {tx["to"]}') print(f'Value: {w3.from_wei(tx["value"], "ether")}') print(f'Block: {tx["blockNumber"]}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x56f0fad1416d7e1ce20a18fc488c0d850c24b0bd4297f51bb901eeb24346bbe2") tx, isPending, err := client.TransactionByHash(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Pending: %v\n", isPending) fmt.Printf("Value: %s\n", tx.Value().String()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash format | ## Related Methods - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction receipt - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionCount - Blast RPC Method # eth_getTransactionCount Returns the number of transactions sent from an address on Blast (the nonce). ## Use Cases - **Transaction building** - Get correct nonce for new transactions - **Account analysis** - Count total outgoing transactions - **Nonce management** - Handle pending transaction queues - **Wallet operations** - Prepare transactions for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag (`pending` for next nonce) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f'; const nonce = await provider.getTransactionCount(address); console.log('Nonce:', nonce); // Get pending nonce for new transaction const pendingNonce = await provider.getTransactionCount(address, 'pending'); console.log('Next nonce:', pendingNonce); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f' nonce = w3.eth.get_transaction_count(address) print(f'Nonce: {nonce}') # Get pending nonce pending_nonce = w3.eth.get_transaction_count(address, 'pending') print(f'Next nonce: {pending_nonce}') ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionReceipt - Blast RPC Method # eth_getTransactionReceipt Returns the receipt of a transaction by transaction hash on Blast. Receipt is only available for mined transactions. > **Why Blast?** Build on the only Ethereum L2 with native yield—4% for ETH and 5%+ for stablecoins automatically with $2.5B+ TVL, auto-rebasing ETH and USDB, gas revenue sharing for developers, and Blur-backed ecosystem. ## Use Cases The `eth_getTransactionReceipt` method is essential for: - **Transaction confirmation** - Verify transaction was mined successfully - **Gas analysis** - Check actual gas used vs estimated - **Event parsing** - Read emitted events from logs - **Status verification** - Confirm success/failure for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x56f0fad1416d7e1ce20a18fc488c0d850c24b0bd4297f51bb901eeb24346bbe2"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `status` | `QUANTITY` | `1` (success) or `0` (failure) | | `transactionHash` | `DATA` | Transaction hash | | `blockHash` | `DATA` | Block hash | | `blockNumber` | `QUANTITY` | Block number | | `gasUsed` | `QUANTITY` | Gas used by this transaction | | `cumulativeGasUsed` | `QUANTITY` | Total gas used in block up to this tx | | `logs` | `Array` | Array of log objects | | `contractAddress` | `DATA` | Created contract address (if deployment) | ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x56f0fad1416d7e1ce20a18fc488c0d850c24b0bd4297f51bb901eeb24346bbe2"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x56f0fad1416d7e1ce20a18fc488c0d850c24b0bd4297f51bb901eeb24346bbe2'; const receipt = await provider.getTransactionReceipt(txHash); if (receipt) { console.log('Status:', receipt.status === 1 ? 'Success' : 'Failed'); console.log('Gas Used:', receipt.gasUsed.toString()); console.log('Block:', receipt.blockNumber); console.log('Logs:', receipt.logs.length); // Parse specific events for (const log of receipt.logs) { console.log('Event from:', log.address); } } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x56f0fad1416d7e1ce20a18fc488c0d850c24b0bd4297f51bb901eeb24346bbe2' receipt = w3.eth.get_transaction_receipt(tx_hash) if receipt: status = 'Success' if receipt['status'] == 1 else 'Failed' print(f'Status: {status}') print(f'Gas Used: {receipt["gasUsed"]}') print(f'Block: {receipt["blockNumber"]}') print(f'Logs: {len(receipt["logs"])}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x56f0fad1416d7e1ce20a18fc488c0d850c24b0bd4297f51bb901eeb24346bbe2") receipt, err := client.TransactionReceipt(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Status: %d\n", receipt.Status) fmt.Printf("Gas Used: %d\n", receipt.GasUsed) fmt.Printf("Logs: %d\n", len(receipt.Logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash | **Note**: Returns `null` if transaction is not yet mined. ## Related Methods - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details - [`eth_getLogs`](./eth_getLogs) - Query logs by filter --- ## eth_hashrate - Get node hashrate(Blast) # eth_hashrate Get node hashrate on the Blast network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_hashrate](https://ethereum.org/developers/docs/apis/json-rpc/#eth_hashrate) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_hashrate", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_hashrate', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Blast documentation](/docs/blast).* --- ## eth_maxPriorityFeePerGas - Blast RPC Method # eth_maxPriorityFeePerGas Returns the current recommended priority fee per gas on Blast for EIP-1559 transactions. ## Use Cases - **EIP-1559 transactions** - Set appropriate priority fees - **Transaction acceleration** - Calculate tips for faster inclusion - **Gas optimization** - Balance speed vs cost for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); console.log('Max Priority Fee:', formatUnits(feeData.maxPriorityFeePerGas, 'gwei'), 'Gwei'); console.log('Max Fee Per Gas:', formatUnits(feeData.maxFeePerGas, 'gwei'), 'Gwei'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) priority_fee = w3.eth.max_priority_fee print(f'Max Priority Fee: {w3.from_wei(priority_fee, "gwei")} Gwei') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get legacy gas price - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data --- ## eth_mining - Check if node is mining(Blast) # eth_mining Check if node is mining on the Blast network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_mining](https://ethereum.org/developers/docs/apis/json-rpc/#eth_mining) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_mining', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Blast documentation](/docs/blast).* --- ## eth_newBlockFilter - Blast RPC Method # eth_newBlockFilter Creates a filter on Blast to notify when a new block arrives. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newBlockFilter', []); // Poll for new blocks const newBlocks = await provider.send('eth_getFilterChanges', [filterId]); console.log('New block hashes:', newBlocks); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_blockNumber`](./eth_blockNumber) - Get current block --- ## eth_newFilter - Blast RPC Method # eth_newFilter Creates a filter object on Blast to notify when state changes (logs). ## Use Cases - **Event monitoring** - Subscribe to contract events - **Real-time updates** - Track events for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications - **Indexing** - Build event indexes incrementally ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block | | `toBlock` | `QUANTITY\|TAG` | No | Ending block | | `address` | `DATA\|Array` | No | Contract address(es) | | `topics` | `Array` | No | Topic filters | ## Request ```json { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Create filter const filterId = await provider.send('eth_newFilter', [{ fromBlock: 'latest', address: '0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f', topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'] }]); // Poll for changes const changes = await provider.send('eth_getFilterChanges', [filterId]); console.log('New events:', changes); // Cleanup await provider.send('eth_uninstallFilter', [filterId]); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for changes - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_newPendingTransactionFilter - Blast RPC Method # eth_newPendingTransactionFilter Creates a filter on Blast to notify when new pending transactions arrive. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newPendingTransactionFilter', []); // Poll for pending transactions const pendingTxs = await provider.send('eth_getFilterChanges', [filterId]); console.log('Pending transaction hashes:', pendingTxs); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_protocolVersion - Get protocol version(Blast) # eth_protocolVersion Get protocol version on the Blast network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_protocolVersion](https://ethereum.org/developers/docs/apis/json-rpc/#eth_protocolversion) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_protocolVersion", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_protocolVersion', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Blast documentation](/docs/blast).* --- ## eth_sendRawTransaction - Blast RPC Method # eth_sendRawTransaction Submits a pre-signed transaction for broadcast to Blast. > **Why Blast?** Build on the only Ethereum L2 with native yield—4% for ETH and 5%+ for stablecoins automatically with $2.5B+ TVL, auto-rebasing ETH and USDB, gas revenue sharing for developers, and Blur-backed ecosystem. ## Use Cases The `eth_sendRawTransaction` method is essential for: - **Broadcasting transactions** - Submit signed transactions to the network - **Wallet operations** - Send native tokens and interact with contracts - **DeFi operations** - Execute swaps, provide liquidity for yield-generating dApps, DeFi protocols with built-in returns, and gas-subsidized applications - **Batch operations** - Submit multiple transactions efficiently ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `signedTransactionData` | `DATA` | Yes | The signed transaction data (RLP encoded) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | 32-byte transaction hash | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c808504a817c80082520894..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const wallet = new Wallet('YOUR_PRIVATE_KEY', provider); // Send native tokens async function sendTransaction(to, value) { const tx = await wallet.sendTransaction({ to: to, value: parseEther(value) }); console.log('Transaction hash:', tx.hash); // Wait for confirmation const receipt = await tx.wait(); console.log('Confirmed in block:', receipt.blockNumber); return receipt; } // Send to contract async function sendContractTransaction(contract, method, args, value = '0') { const tx = await contract[method](...args, { value: parseEther(value) }); return await tx.wait(); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) def send_transaction(private_key, to, value_in_ether): account = w3.eth.account.from_key(private_key) # Build transaction tx = { 'nonce': w3.eth.get_transaction_count(account.address), 'to': to, 'value': w3.to_wei(value_in_ether, 'ether'), 'gas': 21000, 'gasPrice': w3.eth.gas_price, 'chainId': w3.eth.chain_id } # Sign transaction signed_tx = account.sign_transaction(tx) # Send transaction tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) print(f'Transaction hash: {tx_hash.hex()}') # Wait for confirmation receipt = w3.eth.wait_for_transaction_receipt(tx_hash) print(f'Confirmed in block: {receipt["blockNumber"]}') return receipt ``` ```go package main "context" "crypto/ecdsa" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY") if err != nil { log.Fatal(err) } publicKey := privateKey.Public() publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey) fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA) nonce, _ := client.PendingNonceAt(context.Background(), fromAddress) value := big.NewInt(1000000000000000000) gasLimit := uint64(21000) gasPrice, _ := client.SuggestGasPrice(context.Background()) toAddress := common.HexToAddress("0xA8b2218036Eab12e58e02f88E8825723aB4C5E5f") tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil) chainID, _ := client.NetworkID(context.Background()) signedTx, _ := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey) err = client.SendTransaction(context.Background(), signedTx) if err != nil { log.Fatal(err) } fmt.Printf("Transaction hash: %s\n", signedTx.Hash().Hex()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Nonce too low | Transaction nonce already used | | -32000 | Insufficient funds | Account has insufficient balance | | -32000 | Gas too low | Gas limit insufficient | | -32000 | Replacement underpriced | Gas price too low for replacement | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas required - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction result --- ## eth_sendTransaction - Send transaction (wallet...(Blast) # eth_sendTransaction > **Important**: Dwellir's shared Blast endpoints do not manage user private keys. JSON-RPC nodes cannot unlock your account, so `eth_sendTransaction` calls will fail. Sign transactions client-side and broadcast them with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Why this method is disabled on shared nodes - [`eth_sendTransaction` requires the node to hold and unlock the `from` account's private key](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction). - Managed infrastructure providers disable it for security reasons rather than storing customer keys on shared servers (for example, [Infura explicitly blocks the method on shared endpoints](https://docs.infura.io/api/networks/ethereum/json-rpc-methods/eth_sendtransaction)). ## Recommended workflow 1. Build the raw transaction locally with your wallet or SDK. 2. Sign the payload client-side (hardware wallet, custodial service, or library). 3. Submit the signed hex string with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Example response from the shared endpoint ```bash curl -s -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"0x0000000000000000000000000000000000000000"}],"id":1}' ``` ```json {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"unknown account"}} ``` Need help? Contact our [support team](mailto:support@dwellir.com) or use the dedicated [`eth_sendRawTransaction`](./eth_sendRawTransaction) guide. --- ## eth_signTransaction - Sign transaction (rarely...(Blast) # eth_signTransaction Signs a transaction using an unlocked account on the node. **Important**: Most RPC providers don't support this method for security reasons, as it requires private keys to be stored on the server. ## Security Considerations - This method requires an unlocked account on the node - Private keys must be available to the RPC server - Most production RPC providers disable this method - Use client-side signing libraries instead for better security ## Parameters 1. `Object` - The transaction object: - `from`: `DATA`, 20 Bytes - The address the transaction is sent from - `to`: `DATA`, 20 Bytes - (optional) The address the transaction is directed to - `gas`: `QUANTITY` - (optional) Integer of the gas provided for the transaction execution - `gasPrice`: `QUANTITY` - (optional) Integer of the gasPrice used for each paid gas - `value`: `QUANTITY` - (optional) Integer of the value sent with this transaction - `data`: `DATA` - (optional) The compiled code of a contract OR the hash of the invoked method signature and encoded parameters ## Returns `DATA` - The signed transaction data, ready for transmission via `eth_sendRawTransaction`. ## Implementation Example ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_signTransaction", "params": [{ "from": "0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a" }], "id": 1 }' ``` ```javascript const response = await fetch('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_signTransaction', params: [{ from: '0x9b2055d370f73ec7d8a03e965129118dc8f5bf83', to: '0xd46e8dd67c5d32be8058bb8eb970870f07244567', gas: '0x76c0', gasPrice: '0x9184e72a000', value: '0x9184e72a' }], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0xf86c808504a817c8008276c094d46e8dd67c5d32be8058bb8eb970870f072445675849184e72a8001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804" } ``` **Note**: This method is typically not available on hosted RPC providers for security reasons. The response shows a signed transaction ready for broadcast. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Blast documentation](/docs/blast).* --- ## eth_syncing - Blast RPC Method # eth_syncing Returns syncing status of Blast node. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 } ``` ## Returns Returns `false` if not syncing, or an object with sync status. ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const syncing = await provider.send('eth_syncing', []); if (syncing === false) { console.log('Node is fully synced'); } else { console.log('Syncing:', syncing); } ``` ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get current block - [`net_peerCount`](./net_peerCount) - Get peer count --- ## eth_uninstallFilter - Blast RPC Method # eth_uninstallFilter Uninstalls a filter on Blast. Should be called when no longer needed. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID to uninstall | ## Request ```json { "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if filter was found and uninstalled | ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const success = await provider.send('eth_uninstallFilter', [filterId]); console.log('Filter removed:', success); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter --- ## Blast RPC with Dwellir # Blast - Build on the High-Performance EVM L2 ## Why Build on Blast? Blast is a next-generation Ethereum Layer 2 solution designed for high-performance applications and DeFi protocols. Built to optimize developer and user experience, Blast offers: ### 🚀 **High-Performance EVM** - **Fast transaction finality** - Sub-second confirmation times - **Low gas costs** - Significantly reduced fees compared to Ethereum L1 - **High throughput** - Optimized for demanding applications ### 💰 **Native Yield Generation** - **Built-in yield** - ETH and USDB automatically earn yield - **Developer incentives** - Gas fee rebates and yield sharing - **Capital efficiency** - Maximize returns for users and protocols ### 🔧 **Developer-First Design** - **Full EVM compatibility** - Deploy existing Ethereum contracts seamlessly - **Rich tooling support** - Works with Hardhat, Foundry, and all standard tools - **Growing ecosystem** - Active developer community and partnerships ### 🌐 **Decentralized & Secure** - **Ethereum security** - Inherits L1 security properties - **Decentralized sequencing** - Robust network architecture - **Battle-tested infrastructure** - Proven reliability and uptime ## Quick Start with Blast Connect to Blast in seconds with Dwellir's optimized endpoints: ### Installation & Setup ```javascript // Connect to Blast mainnet const provider = new JsonRpcProvider( 'https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); // Get the latest block const block = await provider.getBlock('latest'); console.log('Latest block:', block.number); // Query account balance const balance = await provider.getBalance('0x...'); console.log('Balance:', balance.toString()); ``` ```javascript const Web3 = require('web3'); // Connect to Blast mainnet const web3 = new Web3( 'https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); // Get chain ID to verify connection const chainId = await web3.eth.getChainId(); console.log('Connected to Blast:', chainId === 81457n); // Get gas price for optimal transaction pricing const gasPrice = await web3.eth.getGasPrice(); console.log('Current gas price:', gasPrice); ``` ```typescript // Create Blast client const client = createPublicClient({ chain: blast, transport: http('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'), }); // Read contract data const data = await client.readContract({ address: '0x...', abi: contractAbi, functionName: 'balanceOf', args: ['0x...'], }); ``` ```python from web3 import Web3 # Connect to Blast mainnet w3 = Web3(Web3.HTTPProvider( 'https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY' )) # Verify connection print(f'Connected: {w3.is_connected()}') print(f'Chain ID: {w3.eth.chain_id}') # Get latest block number latest_block = w3.eth.block_number print(f'Latest block: {latest_block}') # Get account balance balance = w3.eth.get_balance('0x...') print(f'Balance: {w3.from_wei(balance, "ether")} ETH') ``` ## Network Information Chain ID 81457 Mainnet Testnet Chain ID 168587773 Sepolia Testnet Gas Token ETH Native token RPC Standard Ethereum JSON-RPC 2.0 ## JSON-RPC API Reference Blast supports the full [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/). ## Common Integration Patterns ### 🔄 Transaction Monitoring Monitor pending and confirmed transactions efficiently: ```javascript // Watch for transaction confirmation async function waitForTransaction(txHash) { const receipt = await provider.waitForTransaction(txHash, 1); // Check transaction status if (receipt.status === 1) { console.log('Transaction confirmed:', receipt.transactionHash); } return receipt; } ``` ### 💰 Gas Optimization Optimize gas costs on Blast: ```javascript // Estimate gas for transaction const gasEstimate = await provider.estimateGas(tx); // Get current fee data for EIP-1559 const feeData = await provider.getFeeData(); // Prepare transaction with optimal gas settings const optimizedTx = { ...tx, gasLimit: gasEstimate, maxFeePerGas: feeData.maxFeePerGas, maxPriorityFeePerGas: feeData.maxPriorityFeePerGas, }; ``` ### 🔍 Event Filtering Efficiently query contract events: ```javascript // Query events with automatic retry and pagination async function getEvents(contract, eventName, fromBlock = 0) { const filter = contract.filters[eventName](); const events = []; const batchSize = 2000; // Recommended batch size for (let i = fromBlock; i <= currentBlock; i += batchSize) { const batch = await contract.queryFilter( filter, i, Math.min(i + batchSize - 1, currentBlock) ); events.push(...batch); } return events; } ``` ## Performance Best Practices ### 1. **Batch Requests** Combine multiple RPC calls for optimal performance: ```javascript const batch = [ { method: 'eth_blockNumber', params: [] }, { method: 'eth_gasPrice', params: [] }, { method: 'eth_getBalance', params: [address, 'latest'] } ]; const results = await provider.send(batch); ``` ### 2. **Connection Pooling** Reuse provider instances to minimize connection overhead: ```javascript // Singleton pattern for provider class BlastProvider { static instance = null; static getInstance() { if (!this.instance) { this.instance = new JsonRpcProvider( 'https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); } return this.instance; } } ``` ### 3. **Smart Caching** Cache immutable data to reduce API calls: ```javascript const cache = new Map(); async function getCachedBlockData(blockNumber) { const key = `block_${blockNumber}`; if (!cache.has(key)) { const block = await provider.getBlock(blockNumber); cache.set(key, block); } return cache.get(key); } ``` ## Troubleshooting Common Issues ### Error: "Wrong chain ID" Verify you're connecting to the correct Blast network: ```javascript // Check current chain ID const chainId = await provider.send('eth_chainId', []); console.log('Current chain ID:', parseInt(chainId, 16)); // Blast Mainnet should return 81457 (0x13e31) // Blast Sepolia Testnet should return 168587773 (0xa0c71fd) ``` ### Error: "Transaction underpriced" Blast uses EIP-1559 pricing. Always use dynamic gas pricing: ```javascript // Get current fee data const feeData = await provider.getFeeData(); const tx = { to: recipient, value: amount, maxFeePerGas: feeData.maxFeePerGas, maxPriorityFeePerGas: feeData.maxPriorityFeePerGas, gasLimit: 21000n }; ``` ### Error: "Rate limit exceeded" Implement exponential backoff for resilient applications: ```javascript async function callWithRetry(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error.code === 429 && i < maxRetries - 1) { await new Promise(r => setTimeout(r, 2 ** i * 1000)); } else { throw error; } } } } ``` ## FAQs ### What makes Blast different from other L2s? Blast is unique in providing native yield generation for ETH and USDB holdings, along with gas fee rebates for developers and automatic capital efficiency optimizations. ### How do I bridge assets to Blast? Use the official Blast Bridge at [blast.io/bridge](https://blast.io/bridge) or integrate with supported bridging protocols. ### Does Blast support all Ethereum tools? Yes, Blast is fully EVM-compatible and works with all standard Ethereum development tools including Hardhat, Foundry, Remix, and MetaMask. ## Smoke Tests Test your connection to Blast: ### curl (Mainnet) ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' ``` ### curl (Testnet) ```bash curl -X POST https://api-blast-sepolia-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' ``` ### Ethers.js v6 ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockNumber = await provider.getBlockNumber(); const network = await provider.getNetwork(); console.log('Block number:', blockNumber); console.log('Chain ID:', network.chainId); // Should be 81457 ``` ### Web3.py ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) print(f'Connected: {w3.is_connected()}') print(f'Chain ID: {w3.eth.chain_id}') # Should be 81457 print(f'Latest block: {w3.eth.block_number}') ``` ## Migration Guide ### From Ethereum Mainnet Moving from L1 to Blast requires minimal changes: ```javascript // Before (Ethereum) const provider = new JsonRpcProvider('https://eth-rpc.example.com'); // After (Blast) const provider = new JsonRpcProvider( 'https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); // ✅ Smart contracts work identically // ✅ Same tooling and libraries // ⚠️ Different chain ID (81457) // ⚠️ Separate block numbers // ✅ Lower gas fees // ✅ Native yield generation ``` ## Resources & Tools ### Official Resources - [Blast Documentation](https://docs.blast.io) - [Blast Bridge](https://blast.io/bridge) - [Blast Explorer](https://blastscan.io) ### Developer Tools - [Blast GitHub](https://github.com/blast-io) - [Developer Portal](https://docs.blast.io/building) - [Smart Contract Templates](https://docs.blast.io/building/smart-contracts) ### Need Help? - 📧 **Email**: support@dwellir.com - 📚 **Docs**: You're here! - 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com) --- *Start building on Blast with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)* --- ## net_listening - Blast RPC Method # net_listening Returns `true` if client is actively listening for network connections on Blast. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if listening | ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const listening = await provider.send('net_listening', []); console.log('Node listening:', listening); ``` ## Related Methods - [`net_peerCount`](./net_peerCount) - Get peer count --- ## net_peerCount - Blast RPC Method # net_peerCount Returns number of peers currently connected to Blast client. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Number of connected peers (hexadecimal) | ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const peerCount = await provider.send('net_peerCount', []); console.log('Peer count:', parseInt(peerCount, 16)); ``` ## Related Methods - [`net_listening`](./net_listening) - Check if listening --- ## net_version - Blast RPC Method # net_version Returns the current network ID on Blast. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Network ID as a string | ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const networkId = await provider.send('net_version', []); console.log('Network ID:', networkId); ``` ## Related Methods - [`eth_chainId`](./eth_chainId) - Get chain ID --- ## web3_clientVersion - Blast RPC Method # web3_clientVersion Returns the current client version on Blast. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Client version string | ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const version = await provider.send('web3_clientVersion', []); console.log('Client version:', version); ``` --- ## web3_sha3 - Blast RPC Method # web3_sha3 Returns Keccak-256 (not standard SHA3-256) of the given data on Blast. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `data` | `DATA` | Yes | Data to hash | ## Request ```json { "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Keccak-256 hash of the data | ## Code Examples ```bash curl -X POST https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-blast-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Using RPC const hash = await provider.send('web3_sha3', ['0x68656c6c6f']); console.log('Hash:', hash); // Using ethers directly (faster) const localHash = keccak256(toUtf8Bytes('hello')); console.log('Local hash:', localHash); ``` --- ## debug_traceBlock - Boba Network RPC Method # debug_traceBlock Traces all transactions in a block on Boba Network by block RLP. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Analyze transaction execution step-by-step - **Smart contract analysis** - Debug contract interactions - **Security auditing** - Trace internal calls for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockRlp` | `DATA` | Yes | RLP-encoded block data | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); // Use debug_traceBlockByNumber instead (more practical) const traces = await provider.send('debug_traceBlockByNumber', ['latest', {}]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by block number - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by block hash --- ## debug_traceBlockByHash - Boba Network RPC Method # debug_traceBlockByHash Traces all transactions in a block on Boba Network by block hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0x164c0bb90ae67c0b6c3ab90a32a8cd3917f1d3840187fb874f00f7e417dd9437", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0x164c0bb90ae67c0b6c3ab90a32a8cd3917f1d3840187fb874f00f7e417dd9437", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0x164c0bb90ae67c0b6c3ab90a32a8cd3917f1d3840187fb874f00f7e417dd9437'; const traces = await provider.send('debug_traceBlockByHash', [blockHash, { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by number - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceBlockByNumber - Boba Network RPC Method # debug_traceBlockByNumber Traces all transactions in a block on Boba Network by block number. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('debug_traceBlockByNumber', ['latest', { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by hash - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceCall - Boba Network RPC Method # debug_traceCall Traces a call without creating a transaction on Boba Network. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction simulation** - Debug before sending - **Gas analysis** - Analyze gas usage per opcode - **Contract debugging** - Step through execution for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `call` | `Object` | Yes | Call object (same as eth_call) | | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ { "to": "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "data": "0x70a08231000000000000000000000000DeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000" }, "latest", {} ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ {"to": "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "data": "0x70a08231000000000000000000000000DeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000"}, "latest", {"tracer": "callTracer"} ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const trace = await provider.send('debug_traceCall', [ { to: '0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000', data: '0x70a08231000000000000000000000000DeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000' }, 'latest', { tracer: 'callTracer' } ]); console.log('Trace:', trace); ``` ## Related Methods - [`eth_call`](./eth_call) - Execute call without trace - [`debug_traceTransaction`](./debug_traceTransaction) - Trace actual transaction --- ## debug_traceTransaction - Boba Network RPC Method # debug_traceTransaction Traces a transaction execution on Boba Network by transaction hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Understand exactly what happened - **Failure analysis** - Find where and why a transaction reverted - **Gas optimization** - Analyze gas usage for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Tracer Options - `{}` - Default opcode tracer (verbose) - `{ tracer: "callTracer" }` - Call tree tracer - `{ tracer: "prestateTracer" }` - Pre-state tracer ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x5d01c1b5655ee1315a49968be5bf94b730e8ea3854e88b3ee4ef7624f3b15565", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x5d01c1b5655ee1315a49968be5bf94b730e8ea3854e88b3ee4ef7624f3b15565", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x5d01c1b5655ee1315a49968be5bf94b730e8ea3854e88b3ee4ef7624f3b15565'; // Call tracer - shows internal calls const callTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'callTracer' } ]); console.log('Type:', callTrace.type); console.log('From:', callTrace.from); console.log('To:', callTrace.to); console.log('Gas used:', parseInt(callTrace.gasUsed, 16)); // Prestate tracer - shows state before execution const prestateTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'prestateTracer' } ]); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x5d01c1b5655ee1315a49968be5bf94b730e8ea3854e88b3ee4ef7624f3b15565' # Call tracer trace = w3.provider.make_request('debug_traceTransaction', [ tx_hash, {'tracer': 'callTracer'} ]) print(f'Trace type: {trace["result"]["type"]}') print(f'Gas used: {int(trace["result"]["gasUsed"], 16)}') ``` ## Related Methods - [`debug_traceCall`](./debug_traceCall) - Trace without executing - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace entire block --- ## eth_accounts - Boba Network RPC Method # eth_accounts Returns a list of addresses owned by the client on Boba Network. > **Why Boba Network?** Build on the Hybrid Compute L2 enabling smart contracts to access AI models and Web2 APIs natively with HybridCompute 2.0 for native AI/API access, $70M ecosystem funding, OP Stack compatibility, and two-way offchain integration. ## Important Note On public RPC endpoints like Dwellir, `eth_accounts` returns an empty array because the node does not hold any private keys. This method is primarily useful for: - Local development nodes (Ganache, Hardhat, Anvil) - Private nodes with managed accounts - Wallet provider connections (MetaMask injects accounts) ## When to Use This Method `eth_accounts` is relevant for AI dApp developers, enterprise integration teams, and builders requiring offchain compute access in specific scenarios: - **Development Testing** — Retrieve test accounts from local nodes - **Wallet Detection** — Check if a wallet provider has connected accounts - **Client Verification** — Confirm node account access capabilities ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `Array` | List of 20-byte account addresses owned by the client | **Return format**: Array of `0x` prefixed hexadecimal addresses (typically empty for public nodes) ## Request ```json { "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 } ``` ## Response ### Successful Response (Public Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [] } ``` ### Successful Response (Local Development Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [ "0x407d73d8a49eeb85d32cf465507dd71d507100c1", "0x85d32cf465507dd71d507100c1407d73d8a49eeb" ] } ``` ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_accounts', params: [], id: 1 }) }); const { result } = await response.json(); console.log('Accounts:', result); // Using ethers.js const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const accounts = await provider.listAccounts(); console.log('Accounts:', accounts); ``` ```python def get_accounts(): response = requests.post( 'https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_accounts', 'params': [], 'id': 1 } ) return response.json()['result'] accounts = get_accounts() print(f'Accounts: {accounts}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) print(f'Accounts: {w3.eth.accounts}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/rpc" ) func main() { client, err := rpc.Dial("https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } var accounts []string err = client.CallContext(context.Background(), &accounts, "eth_accounts") if err != nil { log.Fatal(err) } fmt.Printf("Accounts: %v\n", accounts) } ``` ## Common Use Cases ### 1. Development Environment Detection Check if running against a development node with test accounts: ```javascript async function isDevEnvironment(provider) { const accounts = await provider.listAccounts(); return accounts.length > 0; } const isDev = await isDevEnvironment(provider); if (isDev) { console.log('Development environment detected'); } ``` ### 2. Wallet Connection Check Verify wallet provider has connected accounts: ```javascript async function checkWalletConnection() { if (typeof window.ethereum === 'undefined') { return { connected: false, reason: 'No wallet detected' }; } const accounts = await window.ethereum.request({ method: 'eth_accounts' }); return { connected: accounts.length > 0, accounts: accounts }; } ``` ### 3. Fallback Account Selection Use first available account or request connection: ```javascript async function getActiveAccount() { // Check existing connections let accounts = await window.ethereum.request({ method: 'eth_accounts' }); // Request connection if no accounts if (accounts.length === 0) { accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); } return accounts[0] || null; } ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32601 | Method not found | Node may not support this method | | -32603 | Internal error | Retry with exponential backoff | ```javascript async function safeGetAccounts(provider) { try { const accounts = await provider.listAccounts(); return { success: true, accounts }; } catch (error) { if (error.code === -32601) { console.warn('eth_accounts not supported on this node'); return { success: false, accounts: [], reason: 'unsupported' }; } throw error; } } ``` ## Related Methods - [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102) — Request wallet connection (browser wallets) - [`eth_getBalance`](./eth_getBalance) — Get account balance - [`eth_getTransactionCount`](./eth_getTransactionCount) — Get account nonce --- ## eth_blockNumber - Boba Network RPC Method # eth_blockNumber Returns the number of the most recent block on Boba Network. > **Why Boba Network?** Build on the Hybrid Compute L2 enabling smart contracts to access AI models and Web2 APIs natively with HybridCompute 2.0 for native AI/API access, $70M ecosystem funding, OP Stack compatibility, and two-way offchain integration. ## When to Use This Method `eth_blockNumber` is fundamental for AI dApp developers, enterprise integration teams, and builders requiring offchain compute access: - **Syncing Applications** — Keep your dApp in sync with the latest Boba Network blockchain state - **Transaction Monitoring** — Verify confirmations by comparing block numbers - **Event Filtering** — Set the correct block range for querying logs on AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation - **Health Checks** — Monitor node connectivity and sync status ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `QUANTITY` | Hexadecimal string representing the current block number | **Return format**: `0x` prefixed hexadecimal (e.g., `0x5BAD55` = 6,008,149 in decimal) ## Request ```json { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } ``` ## Response ### Successful Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5BAD55" } ``` ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error" } } ``` ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }) }); const { result } = await response.json(); const blockNumber = parseInt(result, 16); console.log('Boba Network block:', blockNumber); // Using ethers.js const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const blockNumber = await provider.getBlockNumber(); console.log('Boba Network block:', blockNumber); ``` ```python def get_block_number(): response = requests.post( 'https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_blockNumber', 'params': [], 'id': 1 } ) result = response.json()['result'] return int(result, 16) block_number = get_block_number() print(f'Boba Network block: {block_number}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) print(f'Boba Network block: {w3.eth.block_number}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockNumber, err := client.BlockNumber(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Boba Network block: %d\n", blockNumber) } ``` ## Common Use Cases ### 1. Block Confirmation Counter Monitor transaction confirmations on Boba Network: ```javascript async function getConfirmations(provider, txHash) { const tx = await provider.getTransaction(txHash); if (!tx || !tx.blockNumber) return 0; const currentBlock = await provider.getBlockNumber(); return currentBlock - tx.blockNumber + 1; } // Wait for specific confirmations async function waitForConfirmations(provider, txHash, confirmations = 6) { let currentConfirmations = 0; while (currentConfirmations < confirmations) { currentConfirmations = await getConfirmations(provider, txHash); console.log(`Confirmations: ${currentConfirmations}/${confirmations}`); await new Promise(r => setTimeout(r, 2000)); } return true; } ``` ### 2. Event Log Filtering Query events from recent blocks on Boba Network: ```javascript async function getRecentEvents(provider, contract, eventName, blockRange = 100) { const currentBlock = await provider.getBlockNumber(); const fromBlock = currentBlock - blockRange; const filter = contract.filters[eventName](); const events = await contract.queryFilter(filter, fromBlock, currentBlock); return events; } ``` ### 3. Node Health Monitoring Check if your Boba Network node is synced: ```javascript async function checkNodeHealth(provider) { try { const blockNumber = await provider.getBlockNumber(); const block = await provider.getBlock(blockNumber); const now = Date.now() / 1000; const blockAge = now - block.timestamp; if (blockAge > 60) { console.warn(`Node may be behind. Last block was ${blockAge}s ago`); return false; } console.log(`Node healthy. Latest block: ${blockNumber}`); return true; } catch (error) { console.error('Node unreachable:', error); return false; } } ``` ## Performance Optimization ### Caching Strategy Cache block numbers to reduce API calls: ```javascript class BlockNumberCache { constructor(ttl = 2000) { this.cache = null; this.timestamp = 0; this.ttl = ttl; } async get(provider) { const now = Date.now(); if (this.cache && (now - this.timestamp) < this.ttl) { return this.cache; } this.cache = await provider.getBlockNumber(); this.timestamp = now; return this.cache; } invalidate() { this.cache = null; this.timestamp = 0; } } const blockCache = new BlockNumberCache(); ``` ### Batch Requests Combine with other calls for efficiency: ```javascript const batch = [ { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }, { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 }, { jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 } ]; const response = await fetch('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await response.json(); ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32603 | Internal error | Retry with exponential backoff | | -32005 | Rate limit exceeded | Implement rate limiting client-side | | -32000 | Execution reverted | Check node sync status | ```javascript async function safeGetBlockNumber(provider, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await provider.getBlockNumber(); } catch (error) { if (error.code === -32005) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } else if (i === maxRetries - 1) { throw error; } } } } ``` ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) — Get full block details by number - [`eth_getBlockByHash`](./eth_getBlockByHash) — Get block details by hash - [`eth_syncing`](./eth_syncing) — Check if node is still syncing --- ## eth_call - Boba Network RPC Method # eth_call Executes a new message call immediately without creating a transaction on Boba Network. Used for reading smart contract state. > **Why Boba Network?** Build on the Hybrid Compute L2 enabling smart contracts to access AI models and Web2 APIs natively with HybridCompute 2.0 for native AI/API access, $70M ecosystem funding, OP Stack compatibility, and two-way offchain integration. ## Use Cases The `eth_call` method is essential for: - **Reading contract state** - Query view/pure functions - **Simulating transactions** - Test execution without gas costs - **DeFi integrations** - Check prices, balances, allowances for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation - **Complex queries** - Execute multi-step contract logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | 20-byte address executing the call | | `to` | `DATA` | Yes | 20-byte contract address | | `gas` | `QUANTITY` | No | Gas limit for the call | | `gasPrice` | `QUANTITY` | No | Gas price in wei | | `value` | `QUANTITY` | No | Value to send in wei | | `data` | `DATA` | Yes | Encoded function call data | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_call", "params": [ { "to": "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "data": "0x70a08231000000000000000000000000DeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000" }, "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | The return value of the executed contract function | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000" } ``` ## Code Examples ```bash # Call ERC20 balanceOf function curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{ "to": "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "data": "0x70a08231000000000000000000000000DeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000" }, "latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); // ERC20 ABI for common functions const ERC20_ABI = [ "function balanceOf(address owner) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function totalSupply() view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)" ]; // Read ERC20 token balance async function getTokenBalance(tokenAddress, walletAddress) { const contract = new Contract(tokenAddress, ERC20_ABI, provider); const balance = await contract.balanceOf(walletAddress); const decimals = await contract.decimals(); const symbol = await contract.symbol(); return { raw: balance.toString(), formatted: (Number(balance) / Math.pow(10, decimals)).toFixed(4), symbol: symbol }; } // Direct eth_call async function directCall(to, data) { const result = await provider.call({ to, data }); return result; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) def get_erc20_balance(token_address, wallet_address): # balanceOf(address) selector function_signature = "balanceOf(address)" function_selector = w3.keccak(text=function_signature)[:4].hex() # Encode address parameter encoded_address = wallet_address[2:].lower().zfill(64) data = function_selector + encoded_address # Make the call result = w3.eth.call({ 'to': token_address, 'data': data }) return int(result.hex(), 16) balance = get_erc20_balance( '0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000', '0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000' ) print(f'Balance: {balance}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000") data := common.FromHex("0x70a08231000000000000000000000000DeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000") msg := ethereum.CallMsg{ To: &contractAddress, Data: data, } result, err := client.CallContract(context.Background(), msg, nil) if err != nil { log.Fatal(err) } fmt.Printf("Result: 0x%x\n", result) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Contract function reverted | | -32602 | Invalid parameters | Invalid data encoding | | -32015 | VM execution error | Contract logic error | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas for transaction - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send actual transaction --- ## eth_chainId - Boba Network RPC Method # eth_chainId Returns the chain ID used for transaction signing on Boba Network. > **Why Boba Network?** Build on the Hybrid Compute L2 enabling smart contracts to access AI models and Web2 APIs natively with HybridCompute 2.0 for native AI/API access, $70M ecosystem funding, OP Stack compatibility, and two-way offchain integration. ## Use Cases The `eth_chainId` method is essential for: - **Transaction signing** - Ensure transactions are signed for the correct network - **Network verification** - Confirm connection to the expected chain - **Multi-chain apps** - Handle different networks programmatically - **Wallet integration** - Validate network before transactions ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Chain ID in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1" } ``` ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const network = await provider.getNetwork(); console.log('Chain ID:', network.chainId); // Verify network before transaction async function verifyNetwork(expectedChainId) { const network = await provider.getNetwork(); if (network.chainId !== BigInt(expectedChainId)) { throw new Error(`Wrong network. Expected ${expectedChainId}, got ${network.chainId}`); } return true; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) chain_id = w3.eth.chain_id print(f'Chain ID: {chain_id}') # Verify network def verify_network(expected_chain_id): chain_id = w3.eth.chain_id if chain_id != expected_chain_id: raise ValueError(f'Wrong network. Expected {expected_chain_id}, got {chain_id}') return True ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } chainID, err := client.ChainID(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Chain ID: %d\n", chainID) } ``` ## Related Methods - [`net_version`](./net_version) - Get network version - [`eth_syncing`](./eth_syncing) - Check sync status --- ## eth_coinbase - Get coinbase address(Boba-network) # eth_coinbase Get coinbase address on the Boba Network network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_coinbase](https://ethereum.org/developers/docs/apis/json-rpc/#eth_coinbase) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_coinbase", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_coinbase', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Boba Network documentation](/docs/base).* --- ## eth_estimateGas - Boba Network RPC Method # eth_estimateGas Estimates the gas necessary to execute a transaction on Boba Network. > **Why Boba Network?** Build on the Hybrid Compute L2 enabling smart contracts to access AI models and Web2 APIs natively with HybridCompute 2.0 for native AI/API access, $70M ecosystem funding, OP Stack compatibility, and two-way offchain integration. ## Use Cases The `eth_estimateGas` method is essential for: - **Transaction preparation** - Set appropriate gas limits - **Cost estimation** - Calculate transaction costs before sending - **Error detection** - Identify reverts before spending gas - **DeFi operations** - Estimate costs for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | Sender address | | `to` | `DATA` | No | Recipient address | | `gas` | `QUANTITY` | No | Gas limit | | `gasPrice` | `QUANTITY` | No | Gas price | | `value` | `QUANTITY` | No | Value in wei | | `data` | `DATA` | No | Transaction data | ## Request ```json { "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "to": "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "value": "0x1" }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Estimated gas amount in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5208" } ``` **Note**: `0x5208` = 21000 gas (standard ETH transfer) ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "to": "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "value": "0x1" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); // Estimate simple transfer async function estimateTransfer(to, value) { const gasEstimate = await provider.estimateGas({ to: to, value: parseEther(value) }); console.log('Estimated gas:', gasEstimate.toString()); return gasEstimate; } // Estimate contract call async function estimateContractCall(contract, method, args) { const gasEstimate = await contract[method].estimateGas(...args); console.log('Estimated gas:', gasEstimate.toString()); // Add 20% buffer for safety return gasEstimate * 120n / 100n; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) def estimate_transfer(to, value_in_ether): gas_estimate = w3.eth.estimate_gas({ 'to': to, 'value': w3.to_wei(value_in_ether, 'ether') }) print(f'Estimated gas: {gas_estimate}') return gas_estimate def estimate_contract_call(contract, method, args): func = getattr(contract.functions, method) gas_estimate = func(*args).estimate_gas() # Add 20% buffer return int(gas_estimate * 1.2) # Estimate simple transfer gas = estimate_transfer('0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000', 0.1) ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } toAddress := common.HexToAddress("0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000") msg := ethereum.CallMsg{ To: &toAddress, Value: big.NewInt(1000000000000000000), } gasLimit, err := client.EstimateGas(context.Background(), msg) if err != nil { log.Fatal(err) } fmt.Printf("Estimated gas: %d\n", gasLimit) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Transaction would fail | | -32602 | Invalid params | Invalid transaction parameters | **Tip**: If estimation fails, the transaction would likely revert if sent. ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_feeHistory - Boba Network RPC Method # eth_feeHistory Returns historical gas information on Boba Network for fee estimation. ## Use Cases - **Fee prediction** - Estimate future gas prices based on history - **Gas analytics** - Analyze fee trends over time - **Optimal timing** - Find best times for transactions on AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockCount` | `QUANTITY` | Yes | Number of blocks in the range | | `newestBlock` | `QUANTITY\|TAG` | Yes | Highest block of the range | | `rewardPercentiles` | `Array` | Yes | Percentiles to sample for priority fees | ## Request ```json { "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const feeHistory = await provider.send('eth_feeHistory', ['0xa', 'latest', [25, 50, 75]]); console.log('Base fees:', feeHistory.baseFeePerGas.map(f => formatUnits(f, 'gwei'))); console.log('Reward (25th percentile):', feeHistory.reward.map(r => formatUnits(r[0], 'gwei'))); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) fee_history = w3.eth.fee_history(10, 'latest', [25, 50, 75]) print(f'Base fees: {[w3.from_wei(f, "gwei") for f in fee_history["baseFeePerGas"]]}') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee --- ## eth_gasPrice - Boba Network RPC Method # eth_gasPrice Returns the current gas price on Boba Network in wei. > **Why Boba Network?** Build on the Hybrid Compute L2 enabling smart contracts to access AI models and Web2 APIs natively with HybridCompute 2.0 for native AI/API access, $70M ecosystem funding, OP Stack compatibility, and two-way offchain integration. ## Use Cases The `eth_gasPrice` method is essential for: - **Transaction pricing** - Set appropriate gas prices - **Cost estimation** - Calculate transaction costs before sending - **Gas monitoring** - Track network congestion - **DeFi operations** - Optimize costs for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Current gas price in wei (hexadecimal) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x3b9aca00" } ``` **Note**: `0x3b9aca00` = 1 Gwei (1,000,000,000 wei) ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); const gasPrice = feeData.gasPrice; console.log('Gas Price:', formatUnits(gasPrice, 'gwei'), 'Gwei'); // Calculate transaction cost async function estimateTransactionCost(gasLimit) { const feeData = await provider.getFeeData(); const cost = feeData.gasPrice * BigInt(gasLimit); return formatUnits(cost, 'ether'); } const cost = await estimateTransactionCost(21000); console.log('Transfer cost:', cost, 'ETH'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) gas_price = w3.eth.gas_price print(f'Gas Price: {w3.from_wei(gas_price, "gwei")} Gwei') # Calculate transaction cost def estimate_transaction_cost(gas_limit): gas_price = w3.eth.gas_price cost = gas_price * gas_limit return w3.from_wei(cost, 'ether') cost = estimate_transaction_cost(21000) print(f'Transfer cost: {cost} ETH') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } gasPrice, err := client.SuggestGasPrice(context.Background()) if err != nil { log.Fatal(err) } // Convert to Gwei gwei := new(big.Float).Quo( new(big.Float).SetInt(gasPrice), big.NewFloat(1e9), ) fmt.Printf("Gas Price: %f Gwei\n", gwei) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32603 | Internal error | Node error | ## Related Methods - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee (EIP-1559) - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas needed --- ## eth_getBalance - Boba Network RPC Method # eth_getBalance Returns the balance of a given address on Boba Network. > **Why Boba Network?** Build on the Hybrid Compute L2 enabling smart contracts to access AI models and Web2 APIs natively with HybridCompute 2.0 for native AI/API access, $70M ecosystem funding, OP Stack compatibility, and two-way offchain integration. ## Use Cases The `eth_getBalance` method is essential for: - **Wallet applications** - Display user balances - **Transaction validation** - Check if account has sufficient funds - **DeFi applications** - Monitor collateral and liquidity for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation - **Account monitoring** - Track balance changes over time ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address to check balance for | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Integer of the current balance in wei (hexadecimal) | **Note**: 1 native token = 10^18 wei. Convert using `balance / 10^18`. ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1a055690d9db80000" } ``` ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000'; const balanceWei = await provider.getBalance(address); const balance = formatEther(balanceWei); console.log(`Balance: ${balance}`); // Get balance at specific block const historicalBalance = await provider.getBalance(address, 1000000); console.log(`Historical balance: ${formatEther(historicalBalance)}`); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000' balance_wei = w3.eth.get_balance(address) balance = w3.from_wei(balance_wei, 'ether') print(f'Balance: {balance}') # Get balance at specific block historical_balance = w3.eth.get_balance(address, block_identifier=1000000) print(f'Historical balance: {w3.from_wei(historical_balance, "ether")}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000") balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } // Convert to ether fbalance := new(big.Float).SetInt(balance) ethValue := new(big.Float).Quo(fbalance, big.NewFloat(1e18)) fmt.Printf("Balance: %f\n", ethValue) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid address format or block parameter | | -32000 | Execution error | Node execution error | ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_getTransactionCount`](./eth_getTransactionCount) - Get account nonce --- ## eth_getBlockByHash - Boba Network RPC Method # eth_getBlockByHash Returns information about a block by hash on Boba Network. > **Why Boba Network?** Build on the Hybrid Compute L2 enabling smart contracts to access AI models and Web2 APIs natively with HybridCompute 2.0 for native AI/API access, $70M ecosystem funding, OP Stack compatibility, and two-way offchain integration. ## Use Cases The `eth_getBlockByHash` method is essential for: - **Block verification** - Verify block data using its unique hash - **Chain reorganization handling** - Track blocks during reorgs - **Cross-chain bridges** - Verify block finality for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation - **Deterministic queries** - Get consistent block data regardless of chain state ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0x164c0bb90ae67c0b6c3ab90a32a8cd3917f1d3840187fb874f00f7e417dd9437", false ], "id": 1 } ``` ## Returns Returns the same block object as `eth_getBlockByNumber`, or `null` if no block is found. | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used | | `transactions` | `Array` | Transaction objects or hashes | ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0x164c0bb90ae67c0b6c3ab90a32a8cd3917f1d3840187fb874f00f7e417dd9437", false ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0x164c0bb90ae67c0b6c3ab90a32a8cd3917f1d3840187fb874f00f7e417dd9437'; const block = await provider.getBlock(blockHash); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) block_hash = '0x164c0bb90ae67c0b6c3ab90a32a8cd3917f1d3840187fb874f00f7e417dd9437' block = w3.eth.get_block(block_hash) print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockHash := common.HexToHash("0x164c0bb90ae67c0b6c3ab90a32a8cd3917f1d3840187fb874f00f7e417dd9437") block, err := client.BlockByHash(context.Background(), blockHash) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block hash format | | -32000 | Block not found | Block with this hash does not exist | ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) - Get block by number - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number --- ## eth_getBlockByNumber - Boba Network RPC Method # eth_getBlockByNumber Returns information about a block by block number on Boba Network. > **Why Boba Network?** Build on the Hybrid Compute L2 enabling smart contracts to access AI models and Web2 APIs natively with HybridCompute 2.0 for native AI/API access, $70M ecosystem funding, OP Stack compatibility, and two-way offchain integration. ## Use Cases The `eth_getBlockByNumber` method is essential for: - **Block explorers** - Display complete block information - **Transaction indexers** - Process all transactions in a block - **Analytics platforms** - Analyze blockchain data for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation - **Timestamp verification** - Get block timestamps for time-based logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used by all transactions | | `gasLimit` | `QUANTITY` | Maximum gas allowed in block | | `transactions` | `Array` | Array of transaction objects or hashes | | `baseFeePerGas` | `QUANTITY` | Base fee per gas (EIP-1559) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": { "number": "0x5BAD55", "hash": "0x164c0bb90ae67c0b6c3ab90a32a8cd3917f1d3840187fb874f00f7e417dd9437", "parentHash": "0x...", "timestamp": "0x64d8f6d0", "gasUsed": "0x1234", "gasLimit": "0x1c9c380", "transactions": [], "baseFeePerGas": "0x5f5e100" } } ``` ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); // Get latest block const block = await provider.getBlock('latest'); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); console.log('Transactions:', block.transactions.length); // Get block with full transactions const blockWithTxs = await provider.getBlock('latest', true); for (const tx of blockWithTxs.prefetchedTransactions) { console.log('Transaction:', tx.hash); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) # Get latest block block = w3.eth.get_block('latest') print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') print(f'Transactions: {len(block.transactions)}') # Get block with full transactions block_full = w3.eth.get_block('latest', full_transactions=True) for tx in block_full.transactions: print(f'Transaction: {tx.hash.hex()}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } // Get latest block block, err := client.BlockByNumber(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) fmt.Printf("Timestamp: %d\n", block.Time()) fmt.Printf("Transactions: %d\n", len(block.Transactions())) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block number or parameter format | | -32000 | Block not found | Block does not exist | ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number - [`eth_getBlockByHash`](./eth_getBlockByHash) - Get block by hash - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_getCode - Boba Network RPC Method # eth_getCode Returns the bytecode at a given address on Boba Network. > **Why Boba Network?** Build on the Hybrid Compute L2 enabling smart contracts to access AI models and Web2 APIs natively with HybridCompute 2.0 for native AI/API access, $70M ecosystem funding, OP Stack compatibility, and two-way offchain integration. ## Use Cases The `eth_getCode` method is essential for: - **Contract verification** - Check if address is a contract - **Security analysis** - Verify deployed bytecode matches expected - **DeFi integrations** - Validate contracts before interactions - **Protocol analysis** - Analyze contract deployments for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Contract bytecode or `0x` if EOA | ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000'; const code = await provider.getCode(address); if (code === '0x') { console.log('Address is an EOA (externally owned account)'); } else { console.log('Address is a contract'); console.log('Bytecode length:', code.length); } // Check if address is a contract async function isContract(address) { const code = await provider.getCode(address); return code !== '0x'; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000' code = w3.eth.get_code(address) if code == b'': print('Address is an EOA') else: print('Address is a contract') print(f'Bytecode length: {len(code.hex())}') # Check if address is a contract def is_contract(address): code = w3.eth.get_code(address) return code != b'' ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000") code, err := client.CodeAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } if len(code) == 0 { fmt.Println("Address is an EOA") } else { fmt.Printf("Contract bytecode length: %d\n", len(code)) } } ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_getStorageAt`](./eth_getStorageAt) - Get contract storage --- ## eth_getFilterChanges - Boba Network RPC Method # eth_getFilterChanges Polling method for a filter on Boba Network, returns an array of logs since last poll. ## Use Cases - **Event streaming** - Get new events incrementally - **Real-time monitoring** - Track contract activity for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation - **Efficient indexing** - Process only new events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); // Poll loop async function pollFilter(filterId, interval = 2000) { while (true) { const changes = await provider.send('eth_getFilterChanges', [filterId]); if (changes.length > 0) { console.log('New events:', changes); } await new Promise(r => setTimeout(r, interval)); } } ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter --- ## eth_getFilterLogs - Boba Network RPC Method # eth_getFilterLogs Returns an array of all logs matching filter with given ID on Boba Network. ## Use Cases - **Historical queries** - Get all matching logs for a filter - **Full event history** - Retrieve complete event data for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const logs = await provider.send('eth_getFilterLogs', [filterId]); console.log('All matching logs:', logs.length); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_getLogs - Boba Network RPC Method # eth_getLogs Returns an array of all logs matching a given filter object on Boba Network. > **Why Boba Network?** Build on the Hybrid Compute L2 enabling smart contracts to access AI models and Web2 APIs natively with HybridCompute 2.0 for native AI/API access, $70M ecosystem funding, OP Stack compatibility, and two-way offchain integration. ## Use Cases The `eth_getLogs` method is essential for: - **Event indexing** - Track contract events for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation - **Token transfers** - Monitor ERC20/ERC721 transfers - **DeFi analytics** - Track swaps, liquidity events, and more - **Notification systems** - Alert on specific on-chain events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block (default: `"latest"`) | | `toBlock` | `QUANTITY\|TAG` | No | Ending block (default: `"latest"`) | | `address` | `DATA\|Array` | No | Contract address(es) to filter | | `topics` | `Array` | No | Array of topic filters | | `blockHash` | `DATA` | No | Filter single block by hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns Array of log objects: | Field | Type | Description | |-------|------|-------------| | `address` | `DATA` | Contract that emitted the log | | `topics` | `Array` | Array of indexed topics | | `data` | `DATA` | Non-indexed log data | | `blockNumber` | `QUANTITY` | Block number | | `transactionHash` | `DATA` | Transaction hash | | `logIndex` | `QUANTITY` | Log index in block | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": [{ "address": "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."], "data": "0x...", "blockNumber": "0x5BAD55", "transactionHash": "0x...", "logIndex": "0x0" }] } ``` ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); // Get Transfer events const TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'; async function getTransferEvents(tokenAddress, fromBlock, toBlock) { const logs = await provider.getLogs({ address: tokenAddress, topics: [TRANSFER_TOPIC], fromBlock: fromBlock, toBlock: toBlock }); return logs.map(log => ({ from: '0x' + log.topics[1].slice(26), to: '0x' + log.topics[2].slice(26), blockNumber: log.blockNumber, transactionHash: log.transactionHash })); } const events = await getTransferEvents( '0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000', 'latest', 'latest' ); console.log('Transfer events:', events); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' def get_transfer_events(token_address, from_block, to_block): logs = w3.eth.get_logs({ 'address': token_address, 'topics': [TRANSFER_TOPIC], 'fromBlock': from_block, 'toBlock': to_block }) events = [] for log in logs: events.append({ 'from': '0x' + log['topics'][1].hex()[26:], 'to': '0x' + log['topics'][2].hex()[26:], 'block': log['blockNumber'], 'tx': log['transactionHash'].hex() }) return events events = get_transfer_events( '0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000', 'latest', 'latest' ) print(f'Found {len(events)} transfer events') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000") transferTopic := common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef") query := ethereum.FilterQuery{ FromBlock: big.NewInt(0), ToBlock: nil, Addresses: []common.Address{contractAddress}, Topics: [][]common.Hash, } logs, err := client.FilterLogs(context.Background(), query) if err != nil { log.Fatal(err) } fmt.Printf("Found %d events\n", len(logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32005 | Query returned more than 10000 results | Reduce block range | | -32602 | Invalid params | Invalid filter parameters | ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create a filter for logs - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for new logs --- ## eth_getStorageAt - Boba Network RPC Method # eth_getStorageAt Returns the value from a storage position at a given address on Boba Network. ## Use Cases - **Contract analysis** - Read raw storage values - **State verification** - Verify contract state - **Security auditing** - Analyze storage layout for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation - **Protocol monitoring** - Track state changes ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte contract address | | `position` | `QUANTITY` | Yes | Storage slot position | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "0x0", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "0x0", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000'; const slot = 0; const storage = await provider.getStorage(address, slot); console.log('Storage at slot 0:', storage); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000' storage = w3.eth.get_storage_at(address, 0) print(f'Storage at slot 0: {storage.hex()}') ``` ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_call`](./eth_call) - Call contract functions --- ## eth_getTransactionByHash - Boba Network RPC Method # eth_getTransactionByHash Returns the information about a transaction by transaction hash on Boba Network. > **Why Boba Network?** Build on the Hybrid Compute L2 enabling smart contracts to access AI models and Web2 APIs natively with HybridCompute 2.0 for native AI/API access, $70M ecosystem funding, OP Stack compatibility, and two-way offchain integration. ## Use Cases The `eth_getTransactionByHash` method is essential for: - **Transaction tracking** - Get details of pending or confirmed transactions - **Payment verification** - Verify transaction parameters - **Debugging** - Analyze transaction data for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation - **Block explorers** - Display transaction information ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x5d01c1b5655ee1315a49968be5bf94b730e8ea3854e88b3ee4ef7624f3b15565"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `hash` | `DATA` | Transaction hash | | `from` | `DATA` | Sender address | | `to` | `DATA` | Recipient address | | `value` | `QUANTITY` | Value in wei | | `gas` | `QUANTITY` | Gas provided | | `gasPrice` | `QUANTITY` | Gas price in wei | | `input` | `DATA` | Transaction input data | | `nonce` | `QUANTITY` | Sender's nonce | | `blockHash` | `DATA` | Block hash (null if pending) | | `blockNumber` | `QUANTITY` | Block number (null if pending) | ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x5d01c1b5655ee1315a49968be5bf94b730e8ea3854e88b3ee4ef7624f3b15565"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x5d01c1b5655ee1315a49968be5bf94b730e8ea3854e88b3ee4ef7624f3b15565'; const tx = await provider.getTransaction(txHash); if (tx) { console.log('From:', tx.from); console.log('To:', tx.to); console.log('Value:', formatEther(tx.value)); console.log('Block:', tx.blockNumber); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x5d01c1b5655ee1315a49968be5bf94b730e8ea3854e88b3ee4ef7624f3b15565' tx = w3.eth.get_transaction(tx_hash) if tx: print(f'From: {tx["from"]}') print(f'To: {tx["to"]}') print(f'Value: {w3.from_wei(tx["value"], "ether")}') print(f'Block: {tx["blockNumber"]}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x5d01c1b5655ee1315a49968be5bf94b730e8ea3854e88b3ee4ef7624f3b15565") tx, isPending, err := client.TransactionByHash(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Pending: %v\n", isPending) fmt.Printf("Value: %s\n", tx.Value().String()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash format | ## Related Methods - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction receipt - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionCount - Boba Network RPC Method # eth_getTransactionCount Returns the number of transactions sent from an address on Boba Network (the nonce). ## Use Cases - **Transaction building** - Get correct nonce for new transactions - **Account analysis** - Count total outgoing transactions - **Nonce management** - Handle pending transaction queues - **Wallet operations** - Prepare transactions for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag (`pending` for next nonce) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000'; const nonce = await provider.getTransactionCount(address); console.log('Nonce:', nonce); // Get pending nonce for new transaction const pendingNonce = await provider.getTransactionCount(address, 'pending'); console.log('Next nonce:', pendingNonce); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000' nonce = w3.eth.get_transaction_count(address) print(f'Nonce: {nonce}') # Get pending nonce pending_nonce = w3.eth.get_transaction_count(address, 'pending') print(f'Next nonce: {pending_nonce}') ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionReceipt - Boba Network RPC Method # eth_getTransactionReceipt Returns the receipt of a transaction by transaction hash on Boba Network. Receipt is only available for mined transactions. > **Why Boba Network?** Build on the Hybrid Compute L2 enabling smart contracts to access AI models and Web2 APIs natively with HybridCompute 2.0 for native AI/API access, $70M ecosystem funding, OP Stack compatibility, and two-way offchain integration. ## Use Cases The `eth_getTransactionReceipt` method is essential for: - **Transaction confirmation** - Verify transaction was mined successfully - **Gas analysis** - Check actual gas used vs estimated - **Event parsing** - Read emitted events from logs - **Status verification** - Confirm success/failure for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x5d01c1b5655ee1315a49968be5bf94b730e8ea3854e88b3ee4ef7624f3b15565"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `status` | `QUANTITY` | `1` (success) or `0` (failure) | | `transactionHash` | `DATA` | Transaction hash | | `blockHash` | `DATA` | Block hash | | `blockNumber` | `QUANTITY` | Block number | | `gasUsed` | `QUANTITY` | Gas used by this transaction | | `cumulativeGasUsed` | `QUANTITY` | Total gas used in block up to this tx | | `logs` | `Array` | Array of log objects | | `contractAddress` | `DATA` | Created contract address (if deployment) | ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x5d01c1b5655ee1315a49968be5bf94b730e8ea3854e88b3ee4ef7624f3b15565"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x5d01c1b5655ee1315a49968be5bf94b730e8ea3854e88b3ee4ef7624f3b15565'; const receipt = await provider.getTransactionReceipt(txHash); if (receipt) { console.log('Status:', receipt.status === 1 ? 'Success' : 'Failed'); console.log('Gas Used:', receipt.gasUsed.toString()); console.log('Block:', receipt.blockNumber); console.log('Logs:', receipt.logs.length); // Parse specific events for (const log of receipt.logs) { console.log('Event from:', log.address); } } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x5d01c1b5655ee1315a49968be5bf94b730e8ea3854e88b3ee4ef7624f3b15565' receipt = w3.eth.get_transaction_receipt(tx_hash) if receipt: status = 'Success' if receipt['status'] == 1 else 'Failed' print(f'Status: {status}') print(f'Gas Used: {receipt["gasUsed"]}') print(f'Block: {receipt["blockNumber"]}') print(f'Logs: {len(receipt["logs"])}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x5d01c1b5655ee1315a49968be5bf94b730e8ea3854e88b3ee4ef7624f3b15565") receipt, err := client.TransactionReceipt(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Status: %d\n", receipt.Status) fmt.Printf("Gas Used: %d\n", receipt.GasUsed) fmt.Printf("Logs: %d\n", len(receipt.Logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash | **Note**: Returns `null` if transaction is not yet mined. ## Related Methods - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details - [`eth_getLogs`](./eth_getLogs) - Query logs by filter --- ## eth_hashrate - Get node hashrate(Boba-network) # eth_hashrate Get node hashrate on the Boba Network network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_hashrate](https://ethereum.org/developers/docs/apis/json-rpc/#eth_hashrate) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_hashrate", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_hashrate', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Boba Network documentation](/docs/base).* --- ## eth_maxPriorityFeePerGas - Boba Network RPC Method # eth_maxPriorityFeePerGas Returns the current recommended priority fee per gas on Boba Network for EIP-1559 transactions. ## Use Cases - **EIP-1559 transactions** - Set appropriate priority fees - **Transaction acceleration** - Calculate tips for faster inclusion - **Gas optimization** - Balance speed vs cost for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); console.log('Max Priority Fee:', formatUnits(feeData.maxPriorityFeePerGas, 'gwei'), 'Gwei'); console.log('Max Fee Per Gas:', formatUnits(feeData.maxFeePerGas, 'gwei'), 'Gwei'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) priority_fee = w3.eth.max_priority_fee print(f'Max Priority Fee: {w3.from_wei(priority_fee, "gwei")} Gwei') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get legacy gas price - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data --- ## eth_mining - Check if node is mining(Boba-network) # eth_mining Check if node is mining on the Boba Network network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_mining](https://ethereum.org/developers/docs/apis/json-rpc/#eth_mining) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_mining', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Boba Network documentation](/docs/base).* --- ## eth_newBlockFilter - Boba Network RPC Method # eth_newBlockFilter Creates a filter on Boba Network to notify when a new block arrives. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newBlockFilter', []); // Poll for new blocks const newBlocks = await provider.send('eth_getFilterChanges', [filterId]); console.log('New block hashes:', newBlocks); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_blockNumber`](./eth_blockNumber) - Get current block --- ## eth_newFilter - Boba Network RPC Method # eth_newFilter Creates a filter object on Boba Network to notify when state changes (logs). ## Use Cases - **Event monitoring** - Subscribe to contract events - **Real-time updates** - Track events for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation - **Indexing** - Build event indexes incrementally ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block | | `toBlock` | `QUANTITY\|TAG` | No | Ending block | | `address` | `DATA\|Array` | No | Contract address(es) | | `topics` | `Array` | No | Topic filters | ## Request ```json { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); // Create filter const filterId = await provider.send('eth_newFilter', [{ fromBlock: 'latest', address: '0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000', topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'] }]); // Poll for changes const changes = await provider.send('eth_getFilterChanges', [filterId]); console.log('New events:', changes); // Cleanup await provider.send('eth_uninstallFilter', [filterId]); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for changes - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_newPendingTransactionFilter - Boba Network RPC Method # eth_newPendingTransactionFilter Creates a filter on Boba Network to notify when new pending transactions arrive. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newPendingTransactionFilter', []); // Poll for pending transactions const pendingTxs = await provider.send('eth_getFilterChanges', [filterId]); console.log('Pending transaction hashes:', pendingTxs); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_protocolVersion - Get protocol version(Boba-network) # eth_protocolVersion Get protocol version on the Boba Network network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_protocolVersion](https://ethereum.org/developers/docs/apis/json-rpc/#eth_protocolversion) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_protocolVersion", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_protocolVersion', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Boba Network documentation](/docs/base).* --- ## eth_sendRawTransaction - Boba Network RPC Method # eth_sendRawTransaction Submits a pre-signed transaction for broadcast to Boba Network. > **Why Boba Network?** Build on the Hybrid Compute L2 enabling smart contracts to access AI models and Web2 APIs natively with HybridCompute 2.0 for native AI/API access, $70M ecosystem funding, OP Stack compatibility, and two-way offchain integration. ## Use Cases The `eth_sendRawTransaction` method is essential for: - **Broadcasting transactions** - Submit signed transactions to the network - **Wallet operations** - Send native tokens and interact with contracts - **DeFi operations** - Execute swaps, provide liquidity for AI-powered dApps, Web2 API integration, enterprise blockchain solutions, and offchain computation - **Batch operations** - Submit multiple transactions efficiently ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `signedTransactionData` | `DATA` | Yes | The signed transaction data (RLP encoded) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | 32-byte transaction hash | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c808504a817c80082520894..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const wallet = new Wallet('YOUR_PRIVATE_KEY', provider); // Send native tokens async function sendTransaction(to, value) { const tx = await wallet.sendTransaction({ to: to, value: parseEther(value) }); console.log('Transaction hash:', tx.hash); // Wait for confirmation const receipt = await tx.wait(); console.log('Confirmed in block:', receipt.blockNumber); return receipt; } // Send to contract async function sendContractTransaction(contract, method, args, value = '0') { const tx = await contract[method](...args, { value: parseEther(value) }); return await tx.wait(); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY')) def send_transaction(private_key, to, value_in_ether): account = w3.eth.account.from_key(private_key) # Build transaction tx = { 'nonce': w3.eth.get_transaction_count(account.address), 'to': to, 'value': w3.to_wei(value_in_ether, 'ether'), 'gas': 21000, 'gasPrice': w3.eth.gas_price, 'chainId': w3.eth.chain_id } # Sign transaction signed_tx = account.sign_transaction(tx) # Send transaction tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) print(f'Transaction hash: {tx_hash.hex()}') # Wait for confirmation receipt = w3.eth.wait_for_transaction_receipt(tx_hash) print(f'Confirmed in block: {receipt["blockNumber"]}') return receipt ``` ```go package main "context" "crypto/ecdsa" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY") if err != nil { log.Fatal(err) } publicKey := privateKey.Public() publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey) fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA) nonce, _ := client.PendingNonceAt(context.Background(), fromAddress) value := big.NewInt(1000000000000000000) gasLimit := uint64(21000) gasPrice, _ := client.SuggestGasPrice(context.Background()) toAddress := common.HexToAddress("0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000") tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil) chainID, _ := client.NetworkID(context.Background()) signedTx, _ := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey) err = client.SendTransaction(context.Background(), signedTx) if err != nil { log.Fatal(err) } fmt.Printf("Transaction hash: %s\n", signedTx.Hash().Hex()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Nonce too low | Transaction nonce already used | | -32000 | Insufficient funds | Account has insufficient balance | | -32000 | Gas too low | Gas limit insufficient | | -32000 | Replacement underpriced | Gas price too low for replacement | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas required - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction result --- ## eth_sendTransaction - Send transaction... # eth_sendTransaction > **Important**: Dwellir's shared Boba endpoints do not manage user private keys. JSON-RPC nodes cannot unlock your account, so `eth_sendTransaction` calls will fail. Sign transactions client-side and broadcast them with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Why this method is disabled on shared nodes - [`eth_sendTransaction` requires the node to hold and unlock the `from` account's private key](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction). - Managed infrastructure providers disable it for security reasons rather than storing customer keys on shared servers (for example, [Infura explicitly blocks the method on shared endpoints](https://docs.infura.io/api/networks/ethereum/json-rpc-methods/eth_sendtransaction)). ## Recommended workflow 1. Build the raw transaction locally with your wallet or SDK. 2. Sign the payload client-side (hardware wallet, custodial service, or library). 3. Submit the signed hex string with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Example response from the shared endpoint ```bash curl -s -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"0x0000000000000000000000000000000000000000"}],"id":1}' ``` ```json {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"unknown account"}} ``` Need help? Contact our [support team](mailto:support@dwellir.com) or use the dedicated [`eth_sendRawTransaction`](./eth_sendRawTransaction) guide. --- ## eth_signTransaction - Sign transaction... # eth_signTransaction Signs a transaction using an unlocked account on the node. **Important**: Most RPC providers don't support this method for security reasons, as it requires private keys to be stored on the server. ## Security Considerations - This method requires an unlocked account on the node - Private keys must be available to the RPC server - Most production RPC providers disable this method - Use client-side signing libraries instead for better security ## Parameters 1. `Object` - The transaction object: - `from`: `DATA`, 20 Bytes - The address the transaction is sent from - `to`: `DATA`, 20 Bytes - (optional) The address the transaction is directed to - `gas`: `QUANTITY` - (optional) Integer of the gas provided for the transaction execution - `gasPrice`: `QUANTITY` - (optional) Integer of the gasPrice used for each paid gas - `value`: `QUANTITY` - (optional) Integer of the value sent with this transaction - `data`: `DATA` - (optional) The compiled code of a contract OR the hash of the invoked method signature and encoded parameters ## Returns `DATA` - The signed transaction data, ready for transmission via `eth_sendRawTransaction`. ## Implementation Example ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_signTransaction", "params": [{ "from": "0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a" }], "id": 1 }' ``` ```javascript const response = await fetch('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_signTransaction', params: [{ from: '0x9b2055d370f73ec7d8a03e965129118dc8f5bf83', to: '0xd46e8dd67c5d32be8058bb8eb970870f07244567', gas: '0x76c0', gasPrice: '0x9184e72a000', value: '0x9184e72a' }], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0xf86c808504a817c8008276c094d46e8dd67c5d32be8058bb8eb970870f072445675849184e72a8001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804" } ``` **Note**: This method is typically not available on hosted RPC providers for security reasons. The response shows a signed transaction ready for broadcast. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Boba Network documentation](/docs/base).* --- ## eth_syncing - Boba Network RPC Method # eth_syncing Returns syncing status of Boba Network node. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 } ``` ## Returns Returns `false` if not syncing, or an object with sync status. ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const syncing = await provider.send('eth_syncing', []); if (syncing === false) { console.log('Node is fully synced'); } else { console.log('Syncing:', syncing); } ``` ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get current block - [`net_peerCount`](./net_peerCount) - Get peer count --- ## eth_uninstallFilter - Boba Network RPC Method # eth_uninstallFilter Uninstalls a filter on Boba Network. Should be called when no longer needed. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID to uninstall | ## Request ```json { "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if filter was found and uninstalled | ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const success = await provider.send('eth_uninstallFilter', [filterId]); console.log('Filter removed:', success); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter --- ## Boba Network - Ethereum L2 Documentation # Boba Network - Build on the Multichain Hybrid L2 ## Why Build on Boba Network? Boba Network is the only multichain Layer 2 that delivers off-chain data and compute, enabling smarter applications for mass adoption. Built with hybrid blockchain technology, Boba Network offers: ### 🚀 **Hybrid Technology** - **HybridCompute™** - Connect on-chain smart contracts to off-chain data and APIs - **Up to 100x cheaper** than underlying blockchains - **Fast finality** - Lightning-fast transactions and confirmations ### 🛡️ **Proven Security** - **Optimistic Rollup** - Secured by the underlying blockchain - **Battle-tested** - Based on proven Optimism technology - **EVM compatible** - Full compatibility with existing Ethereum tools ### 🌍 **Multichain Innovation** - **First multichain L2** - Deployed on Ethereum and BNB Chain - **Dual-fee tokens** - Pay fees in $BOBA or native currency - **Growing ecosystem** - Active developer community and partnerships ## Quick Start with Boba Network Connect to Boba Network in seconds with Dwellir's optimized endpoints: ### Installation & Setup ```javascript // Connect to Boba Network mainnet const provider = new JsonRpcProvider( 'https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY' ); // Get the latest block const block = await provider.getBlock('latest'); console.log('Latest block:', block.number); // Query account balance const balance = await provider.getBalance('0x...'); console.log('Balance:', balance.toString()); ``` ```javascript const Web3 = require('web3'); // Connect to Boba Network mainnet const web3 = new Web3( 'https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY' ); // Get chain ID to verify connection const chainId = await web3.eth.getChainId(); console.log('Connected to Boba Network:', chainId === 288); // Get gas price for optimal transaction pricing const gasPrice = await web3.eth.getGasPrice(); console.log('Current gas price:', gasPrice); ``` ```typescript // Create Boba Network client const client = createPublicClient({ chain: { id: 288, name: 'Boba Network', network: 'boba', nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 }, rpcUrls: { default: { http: ['https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'] }, public: { http: ['https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'] }, }, }, transport: http('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'), }); // Read contract data const data = await client.readContract({ address: '0x...', abi: contractAbi, functionName: 'balanceOf', args: ['0x...'], }); ``` ## Network Information Chain ID 288 Mainnet Block Time ~2 seconds Average Gas Token ETH Native token RPC Standard Ethereum JSON-RPC 2.0 ## JSON-RPC API Reference Boba Network supports the full [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/). Access all standard methods plus hybrid compute features. ## Common Integration Patterns ### 🔄 Transaction Monitoring Monitor pending and confirmed transactions efficiently: ```javascript // Watch for transaction confirmation async function waitForTransaction(txHash) { const receipt = await provider.waitForTransaction(txHash, 1); // Boba Network: Check transaction details console.log('Transaction confirmed on Boba Network'); console.log('Block number:', receipt.blockNumber); return receipt; } ``` ### 💰 Gas Optimization Optimize gas costs on Boba Network: ```javascript // Estimate gas for transaction const gasEstimate = await provider.estimateGas(tx); // Get current gas price const gasPrice = await provider.getGasPrice(); // Calculate total cost const totalCost = gasEstimate * gasPrice; console.log('Estimated cost:', totalCost.toString(), 'wei'); ``` ### 🔍 Event Filtering Efficiently query contract events: ```javascript // Query events with automatic retry and pagination async function getEvents(contract, eventName, fromBlock = 0) { const filter = contract.filters[eventName](); const events = []; const batchSize = 2000; // Boba Network recommended batch size for (let i = fromBlock; i <= currentBlock; i += batchSize) { const batch = await contract.queryFilter( filter, i, Math.min(i + batchSize - 1, currentBlock) ); events.push(...batch); } return events; } ``` ## Performance Best Practices ### 1. **Batch Requests** Combine multiple RPC calls for optimal performance: ```javascript const batch = [ { method: 'eth_blockNumber', params: [] }, { method: 'eth_gasPrice', params: [] }, { method: 'eth_getBalance', params: [address, 'latest'] } ]; const results = await provider.send(batch); ``` ### 2. **Connection Pooling** Reuse provider instances to minimize connection overhead: ```javascript // Singleton pattern for provider class BobaProvider { static instance = null; static getInstance() { if (!this.instance) { this.instance = new JsonRpcProvider( 'https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY' ); } return this.instance; } } ``` ### 3. **Smart Caching** Cache immutable data to reduce API calls: ```javascript const cache = new Map(); async function getCachedBlockData(blockNumber) { const key = `block_${blockNumber}`; if (!cache.has(key)) { const block = await provider.getBlock(blockNumber); cache.set(key, block); } return cache.get(key); } ``` ## Troubleshooting Common Issues ### Error: "Insufficient funds for gas" Boba Network transactions require ETH for gas fees: ```javascript // Check balance and gas requirements const balance = await provider.getBalance(address); const gasEstimate = await provider.estimateGas(tx); const gasPrice = await provider.getGasPrice(); const totalRequired = gasEstimate * gasPrice + (tx.value || 0n); if (balance < totalRequired) { throw new Error(`Need ${totalRequired - balance} more ETH`); } ``` ### Error: "Transaction underpriced" Boba Network uses EIP-1559 pricing. Always use dynamic gas pricing: ```javascript // Get current fee data const feeData = await provider.getFeeData(); const tx = { to: recipient, value: amount, maxFeePerGas: feeData.maxFeePerGas, maxPriorityFeePerGas: feeData.maxPriorityFeePerGas, gasLimit: 21000n }; ``` ### Error: "Rate limit exceeded" Implement exponential backoff for resilient applications: ```javascript async function callWithRetry(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error.code === 429 && i < maxRetries - 1) { await new Promise(r => setTimeout(r, 2 ** i * 1000)); } else { throw error; } } } } ``` ## Migration Guide ### From Ethereum Mainnet Moving from L1 to Boba Network requires minimal changes: ```javascript // Before (Ethereum) const provider = new JsonRpcProvider('https://eth-rpc.example.com'); // After (Boba Network) const provider = new JsonRpcProvider( 'https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY' ); // ✅ Smart contracts work identically // ✅ Same tooling and libraries // ⚠️ Different chain ID (288) // ⚠️ Separate block numbers // ✅ Lower gas costs ``` ## Resources & Tools ### Official Resources - [Boba Network Documentation](https://docs.boba.network) - [Boba Gateway Bridge](https://gateway.boba.network) - [Boba Block Explorer](https://bobascan.com) ### Developer Tools - [Boba Network GitHub](https://github.com/bobanetwork) - [Developer Resources](https://docs.boba.network) ### Need Help? - 📧 **Email**: support@dwellir.com - 📚 **Docs**: You're here! - 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com) --- *Start building on Boba Network with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)* --- ## net_listening - Boba Network RPC Method # net_listening Returns `true` if client is actively listening for network connections on Boba Network. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if listening | ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const listening = await provider.send('net_listening', []); console.log('Node listening:', listening); ``` ## Related Methods - [`net_peerCount`](./net_peerCount) - Get peer count --- ## net_peerCount - Boba Network RPC Method # net_peerCount Returns number of peers currently connected to Boba Network client. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Number of connected peers (hexadecimal) | ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const peerCount = await provider.send('net_peerCount', []); console.log('Peer count:', parseInt(peerCount, 16)); ``` ## Related Methods - [`net_listening`](./net_listening) - Check if listening --- ## net_version - Boba Network RPC Method # net_version Returns the current network ID on Boba Network. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Network ID as a string | ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const networkId = await provider.send('net_version', []); console.log('Network ID:', networkId); ``` ## Related Methods - [`eth_chainId`](./eth_chainId) - Get chain ID --- ## web3_clientVersion - Boba Network RPC Method # web3_clientVersion Returns the current client version on Boba Network. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Client version string | ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); const version = await provider.send('web3_clientVersion', []); console.log('Client version:', version); ``` --- ## web3_sha3 - Boba Network RPC Method # web3_sha3 Returns Keccak-256 (not standard SHA3-256) of the given data on Boba Network. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `data` | `DATA` | Yes | Data to hash | ## Request ```json { "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Keccak-256 hash of the data | ## Code Examples ```bash curl -X POST https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-boba-mainnet.n.dwellir.com/YOUR_API_KEY'); // Using RPC const hash = await provider.send('web3_sha3', ['0x68656c6c6f']); console.log('Hash:', hash); // Using ethers directly (faster) const localHash = keccak256(toUtf8Bytes('hello')); console.log('Local hash:', localHash); ``` --- ## author_pendingExtrinsics - Bridge Hub RPC Method # author_pendingExtrinsics Returns all pending extrinsics in the transaction pool on Bridge Hub. ## Use Cases - **Mempool monitoring** - Track pending transactions - **Transaction status** - Check if your transaction is pending for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Pool analysis** - Monitor network activity ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "author_pendingExtrinsics", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_pendingExtrinsics", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const pending = await api.rpc.author.pendingExtrinsics(); console.log('Pending extrinsics:', pending.length); pending.forEach((ext, idx) => { console.log(`${idx}: ${ext.method.section}.${ext.method.method}`); }); await api.disconnect(); ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction --- ## author_rotateKeys - Bridge Hub RPC Method # author_rotateKeys Generate a new set of session keys on Bridge Hub. This method creates fresh cryptographic keys for validator operations and stores them in the node's keystore. The returned keys must be registered on-chain via `session.setKeys`. ## Use Cases - **Validator setup** - Generate initial session keys for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Key rotation** - Periodically rotate keys for security best practices - **Recovery** - Generate new keys after potential key compromise ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | `Bytes` | Concatenated SCALE-encoded public keys for all session key types | ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_rotateKeys", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Generate new session keys const keys = await api.rpc.author.rotateKeys(); console.log('New session keys:', keys.toHex()); // These keys need to be registered on-chain: // api.tx.session.setKeys(keys, proof) await api.disconnect(); ``` ```python url = 'https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'author_rotateKeys', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json() if 'result' in result: session_keys = result['result'] print(f'New session keys: {session_keys}') print('Register these keys using session.setKeys extrinsic') else: print(f"Error: {result.get('error')}") ``` ## Validator Setup Workflow 1. **Generate keys** - Call `author_rotateKeys` on your validator node 2. **Register on-chain** - Submit `session.setKeys(keys, proof)` extrinsic 3. **Wait for session** - Keys become active in the next session 4. **Verify** - Check `session.nextKeys` storage ## Security Considerations - Only call this method on your own validator node - Session keys are stored in the node's keystore - Rotate keys periodically and after any security incident - Never expose this RPC method publicly ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit setKeys transaction - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - View pending transactions --- ## author_submitAndWatchExtrinsic - Bridge Hub RPC Method # author_submitAndWatchExtrinsic Submit a signed extrinsic to and subscribe to status updates. This WebSocket method provides real-time feedback on transaction progress from submission through finalization. ## Use Cases - **Transaction tracking** - Monitor extrinsic lifecycle for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **UI feedback** - Show users real-time transaction status - **Confirmation workflows** - Wait for specific finality level before proceeding ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `Bytes` | Yes | SCALE-encoded signed extrinsic | ## Returns Returns a subscription that emits `ExtrinsicStatus` updates: | Status | Description | |--------|-------------| | `future` | In future queue (nonce too high) | | `ready` | In ready queue, waiting for block | | `broadcast` | Broadcast to peers | | `inBlock` | Included in block (hash provided) | | `retracted` | Block retracted (reorg) | | `finalityTimeout` | Finality timeout | | `finalized` | Finalized in block (hash provided) | | `usurped` | Replaced by another extrinsic | | `dropped` | Dropped from pool | | `invalid` | Invalid extrinsic | ## Code Examples ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const keyring = new Keyring({ type: 'sr25519' }); // Create and sign a transfer const sender = keyring.addFromUri('//Alice'); const transfer = api.tx.balances.transferKeepAlive( '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 1000000000000n ); // Submit and watch const unsub = await transfer.signAndSend(sender, ({ status, events }) => { console.log(`Status: ${status.type}`); if (status.isInBlock) { console.log(`Included in block: ${status.asInBlock.toHex()}`); } if (status.isFinalized) { console.log(`Finalized in block: ${status.asFinalized.toHex()}`); unsub(); } }); ``` ```python async def submit_and_watch(signed_extrinsic_hex): uri = 'wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: # Submit and subscribe await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'author_submitAndWatchExtrinsic', 'params': [signed_extrinsic_hex], 'id': 1 })) # Get subscription ID response = json.loads(await ws.recv()) if 'error' in response: print(f"Error: {response['error']}") return sub_id = response['result'] print(f'Watching with subscription: {sub_id}') # Listen for status updates while True: message = json.loads(await ws.recv()) if 'params' in message: status = message['params']['result'] print(f"Status: {status}") # Check for finalization if isinstance(status, dict) and 'finalized' in status: print(f"Finalized in: {status['finalized']}") break # asyncio.run(submit_and_watch('0x...')) ``` ## Status Flow ``` ready → broadcast → inBlock → finalized ↘ retracted (if reorg) ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit without watching (fire-and-forget) - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - View transaction pool - [`payment_queryInfo`](./payment_queryInfo) - Estimate fees before submission --- ## author_submitExtrinsic - Bridge Hub RPC Method # author_submitExtrinsic Submit a signed extrinsic to Bridge Hub for inclusion in a block. ## Use Cases - **Transaction submission** - Broadcast signed transactions - **dApp interactions** - Execute on-chain operations for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Automated systems** - Submit programmatic transactions ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `String` | Yes | Hex-encoded signed extrinsic | ## Request ```json { "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": ["0x..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Transaction hash | ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": ["0x..."], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const keyring = new Keyring({ type: 'sr25519' }); const sender = keyring.addFromUri('//Alice'); // Build and sign transaction const transfer = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000); const hash = await transfer.signAndSend(sender); console.log('Transaction hash:', hash.toHex()); await api.disconnect(); ``` ## Related Methods - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - Get pending transactions - [`payment_queryInfo`](./payment_queryInfo) - Estimate fees --- ## beefy_getFinalizedHead - Bridge Hub RPC Method # beefy_getFinalizedHead Returns the block hash of the latest BEEFY-finalized block on Bridge Hub. BEEFY (Bridge Efficiency Enabling Finality Yielder) provides additional finality proofs optimized for light clients and bridges. ## Use Cases - **Cross-chain bridges** - Verify finality proofs for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Light clients** - Efficient finality verification without full GRANDPA proofs - **Trustless bridges** - Generate compact finality proofs for external chains ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | `Hash` | Block hash of the latest BEEFY-finalized block | ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "beefy_getFinalizedHead", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get BEEFY finalized head const beefyHead = await api.rpc.beefy.getFinalizedHead(); console.log('BEEFY finalized:', beefyHead.toHex()); // Compare with GRANDPA finalized const grandpaHead = await api.rpc.chain.getFinalizedHead(); console.log('GRANDPA finalized:', grandpaHead.toHex()); await api.disconnect(); ``` ```python url = 'https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'beefy_getFinalizedHead', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json() if 'result' in result: print(f"BEEFY finalized: {result['result']}") else: print(f"Error: {result.get('error')}") ``` ## BEEFY vs GRANDPA Finality | Aspect | GRANDPA | BEEFY | |--------|---------|-------| | **Purpose** | Primary finality | Bridge-optimized finality | | **Proof size** | Larger (full validator set) | Compact (aggregated signatures) | | **Latency** | Immediate | Slightly delayed | | **Use case** | On-chain finality | Cross-chain bridges | ## Availability BEEFY is enabled on relay chains and some parachains. If BEEFY is not enabled, this method will return an error. ## Related Methods - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - GRANDPA finalized head - [`grandpa_roundState`](./grandpa_roundState) - GRANDPA consensus state - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks --- ## chain_getBlock - Bridge Hub RPC Method # chain_getBlock Retrieves complete block information from Bridge Hub, including the block header, extrinsics, and justifications. > **Why Bridge Hub?** Build on Polkadot's trustless bridging parachain with $75M+ TVL via Snowbridge to Ethereum with on-chain BEEFY/Beacon light clients (no multisigs), 100+ ERC-20 tokens supported, 24+ parachain integrations, and 1-2 minute transfer times. ## Use Cases The `chain_getBlock` method is essential for: - **Block explorers** - Display complete block information - **Chain analysis** - Analyze block production patterns - **Transaction verification** - Confirm extrinsic inclusion for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Data indexing** - Build historical blockchain databases ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Hex-encoded block hash. If omitted, returns latest block | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getBlock", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `block` | `Object` | Complete block data | | `block.header` | `Object` | Block header information | | `block.header.parentHash` | `String` | Hash of the parent block | | `block.header.number` | `String` | Block number (hex-encoded) | | `block.header.stateRoot` | `String` | Root of the state trie | | `block.header.extrinsicsRoot` | `String` | Root of the extrinsics trie | | `block.extrinsics` | `Array` | Array of extrinsics in the block | | `justifications` | `Array` | Block justifications (if available) | ## Code Examples ```bash # Get latest block curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": [], "id": 1 }' # Get specific block curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get latest block const latestHash = await api.rpc.chain.getBlockHash(); const latestBlock = await api.rpc.chain.getBlock(latestHash); console.log('Latest block:', { number: latestBlock.block.header.number.toNumber(), hash: latestHash.toHex(), extrinsicsCount: latestBlock.block.extrinsics.length }); // Get specific block const blockHash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'; const block = await api.rpc.chain.getBlock(blockHash); console.log('Block extrinsics:', block.block.extrinsics.length); await api.disconnect(); ``` ```python def get_block(block_hash=None): url = 'https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY' params = [block_hash] if block_hash else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getBlock', 'params': params, 'id': 1 } response = requests.post(url, json=payload) data = response.json() if 'error' in data: raise Exception(f"RPC Error: {data['error']}") return data['result'] # Get latest block latest_block = get_block() block_number = int(latest_block['block']['header']['number'], 16) print(f'Latest block number: {block_number}') # Get specific block specific_block = get_block('0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3') print(f"Extrinsics count: {len(specific_block['block']['extrinsics'])}") ``` ## Related Methods - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number - [`chain_getHeader`](./chain_getHeader) - Get block header only - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get finalized block hash --- ## chain_getBlockHash - Bridge Hub RPC Method # chain_getBlockHash Returns the block hash for a given block number on Bridge Hub. ## Use Cases - **Historical queries** - Convert block numbers to hashes - **Block navigation** - Navigate blockchain history for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Data indexing** - Build block number to hash mappings ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `Number` | No | Block number. If omitted, returns latest block hash | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getBlockHash", "params": [1000000], "id": 1 } ``` ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlockHash", "params": [1000000], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get hash for specific block number const blockNumber = 1000000; const blockHash = await api.rpc.chain.getBlockHash(blockNumber); console.log(`Block ${blockNumber} hash:`, blockHash.toHex()); await api.disconnect(); ``` ```python def get_block_hash(block_number=None): url = 'https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY' params = [block_number] if block_number is not None else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getBlockHash', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] block_hash = get_block_hash(1000000) print(f'Block hash: {block_hash}') ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get block by hash - [`chain_getHeader`](./chain_getHeader) - Get block header --- ## chain_getFinalizedHead - Bridge Hub RPC Method # chain_getFinalizedHead Returns the hash of the last finalized block on Bridge Hub. ## Use Cases - **Confirmed state** - Query state that cannot be reverted - **Transaction confirmation** - Verify transaction finality for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Safe checkpoints** - Use finalized blocks for critical operations ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const finalizedHash = await api.rpc.chain.getFinalizedHead(); console.log('Finalized block hash:', finalizedHash.toHex()); // Get finalized block details const block = await api.rpc.chain.getBlock(finalizedHash); console.log('Finalized block number:', block.block.header.number.toNumber()); await api.disconnect(); ``` ```python def get_finalized_head(): url = 'https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'chain_getFinalizedHead', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] finalized_hash = get_finalized_head() print(f'Finalized block hash: {finalized_hash}') ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get block by hash - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number --- ## chain_getHeader - Bridge Hub RPC Method # chain_getHeader Returns the block header for a given hash on Bridge Hub. ## Use Cases - **Lightweight queries** - Get header without full block data - **Chain synchronization** - Track block production for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Parent chain navigation** - Follow parentHash links ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash. If omitted, returns latest header | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getHeader", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 } ``` ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getHeader", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get latest header const header = await api.rpc.chain.getHeader(); console.log('Block number:', header.number.toNumber()); console.log('Parent hash:', header.parentHash.toHex()); await api.disconnect(); ``` ```python def get_header(block_hash=None): url = 'https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY' params = [block_hash] if block_hash else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getHeader', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] header = get_header() print(f"Block number: {int(header['number'], 16)}") ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get full block with extrinsics - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number --- ## chain_subscribeFinalizedHeads - Bridge Hub RPC Method # chain_subscribeFinalizedHeads Subscribe to receive notifications when blocks are finalized on Bridge Hub. Finalized blocks are guaranteed to never be reverted, making this essential for applications requiring strong consistency. ## Use Cases - **Exchange deposits** - Only credit funds after finalization for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Bridge operations** - Wait for finality before cross-chain transfers - **Critical state changes** - Ensure irreversibility for important transactions ## Parameters This method takes no parameters. ## Returns Returns a subscription ID. The subscription emits `Header` objects for each finalized block: | Field | Type | Description | |-------|------|-------------| | `parentHash` | `Hash` | Parent block hash | | `number` | `BlockNumber` | Block number | | `stateRoot` | `Hash` | State trie root hash | | `extrinsicsRoot` | `Hash` | Extrinsics trie root hash | | `digest` | `Digest` | Block digest with consensus logs | ## Code Examples ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Subscribe to finalized heads const unsubscribe = await api.rpc.chain.subscribeFinalizedHeads((header) => { console.log(`Finalized block #${header.number}`); console.log(` Hash: ${header.hash.toHex()}`); // Safe to consider this block permanent processConfirmedBlock(header); }); // Later: unsubscribe() ``` ```python async def subscribe_finalized(): uri = 'wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'chain_subscribeFinalizedHeads', 'params': [], 'id': 1 })) response = json.loads(await ws.recv()) sub_id = response['result'] print(f'Subscribed to finalized heads: {sub_id}') while True: message = json.loads(await ws.recv()) if 'params' in message: header = message['params']['result'] block_num = int(header['number'], 16) print(f"Finalized: #{block_num}") asyncio.run(subscribe_finalized()) ``` ## Finality Lag Finalized blocks typically lag behind the best block by a few blocks due to GRANDPA consensus requirements. This is normal and ensures Byzantine fault tolerance. ## Related Methods - [`chain_subscribeNewHeads`](./chain_subscribeNewHeads) - Subscribe to all new blocks (not just finalized) - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get current finalized block hash - [`grandpa_roundState`](./grandpa_roundState) - Monitor GRANDPA consensus progress --- ## chain_subscribeNewHeads - Bridge Hub RPC Method # chain_subscribeNewHeads Subscribe to receive notifications when new block headers are produced on Bridge Hub. This WebSocket subscription provides real-time updates for each new block. ## Use Cases - **Block monitoring** - Track new blocks in real-time for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Event indexing** - Trigger processing when new blocks arrive - **Chain synchronization** - Keep external systems in sync with the chain ## Parameters This method takes no parameters. ## Returns Returns a subscription ID. The subscription emits `Header` objects for each new block: | Field | Type | Description | |-------|------|-------------| | `parentHash` | `Hash` | Parent block hash | | `number` | `BlockNumber` | Block number | | `stateRoot` | `Hash` | State trie root hash | | `extrinsicsRoot` | `Hash` | Extrinsics trie root hash | | `digest` | `Digest` | Block digest with consensus logs | ## Code Examples ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Subscribe to new heads const unsubscribe = await api.rpc.chain.subscribeNewHeads((header) => { console.log(`New block #${header.number}`); console.log(` Hash: ${header.hash.toHex()}`); console.log(` Parent: ${header.parentHash.toHex()}`); console.log(` State root: ${header.stateRoot.toHex()}`); }); // Later: unsubscribe() ``` ```python async def subscribe_new_heads(): uri = 'wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: # Subscribe to new heads await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'chain_subscribeNewHeads', 'params': [], 'id': 1 })) # Get subscription ID response = json.loads(await ws.recv()) sub_id = response['result'] print(f'Subscribed with ID: {sub_id}') # Listen for new headers while True: message = json.loads(await ws.recv()) if 'params' in message: header = message['params']['result'] print(f"Block #{int(header['number'], 16)}") print(f" Hash: {header['parentHash']}") asyncio.run(subscribe_new_heads()) ``` ## Subscription vs Polling | Approach | Latency | Resource Usage | Use Case | |----------|---------|----------------|----------| | `subscribeNewHeads` | Immediate | Low (push-based) | Real-time monitoring | | Polling `getHeader` | Block time + poll interval | Higher (repeated requests) | Simple integrations | ## Related Methods - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks only - [`chain_getHeader`](./chain_getHeader) - Get a specific block header - [`chain_getBlock`](./chain_getBlock) - Get full block with extrinsics --- ## grandpa_roundState - Bridge Hub RPC Method # grandpa_roundState Returns the state of the current GRANDPA finality round on Bridge Hub. GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) is the finality gadget used by Substrate chains. ## Use Cases - **Finality monitoring** - Track consensus progress for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Validator analysis** - Monitor prevote/precommit participation - **Chain health checks** - Detect finality delays or stalls ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `setId` | `u64` | Current authority set ID | | `best` | `RoundState` | Best round state | | `background` | `Vec` | Background rounds | ### RoundState Structure | Field | Type | Description | |-------|------|-------------| | `round` | `u64` | Round number | | `totalWeight` | `u64` | Total validator weight | | `thresholdWeight` | `u64` | Weight needed for supermajority | | `prevotes` | `Prevotes` | Prevote information | | `precommits` | `Precommits` | Precommit information | ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "grandpa_roundState", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const roundState = await api.rpc.grandpa.roundState(); console.log('Set ID:', roundState.setId.toString()); console.log('Best round:', roundState.best.round.toString()); console.log('Total weight:', roundState.best.totalWeight.toString()); console.log('Threshold:', roundState.best.thresholdWeight.toString()); await api.disconnect(); ``` ```python url = 'https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'grandpa_roundState', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json()['result'] print(f"Set ID: {result['setId']}") print(f"Round: {result['best']['round']}") print(f"Total weight: {result['best']['totalWeight']}") ``` ## Understanding GRANDPA Rounds 1. **Prevote phase** - Validators vote on best block they've seen 2. **Precommit phase** - Validators commit to finalize if supermajority prevoted 3. **Finalization** - Block is finalized when 2/3+ weight precommits ## Related Methods - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get current finalized hash - [`beefy_getFinalizedHead`](./beefy_getFinalizedHead) - BEEFY finality (if enabled) --- ## Bridge Hub - Polkadot Interoperability # Bridge Hub – Polkadot's Trustless Interoperability Parachain ## Why Build on Bridge Hub? Bridge Hub is Polkadot's system parachain dedicated to secure cross-network connectivity. It hosts bridge light clients, routing logic, and XCM tooling that allow ecosystems such as Kusama and Ethereum to interoperate without trusted third parties. ### 🔐 **Trustless Finality** - **On-chain GRANDPA & BEEFY verification** – Embedded light clients validate both Polkadot and bridged consensus, enabling permissionless relayers. - **Optimistic root tracking** – Finality proofs are persisted so downstream chains can verify historical headers. - **Governed suspension modes** – Bridge operators can pause lanes per pallet when anomalies are detected. ### 🌉 **Multi-Chain Connectors** - **Polkadot ↔ Kusama routing** – Bridge Westend/Bridge Bulletin pallets exchange relay-chain and parachain headers between ecosystems. - **Snowbridge (Polkadot ↔ Ethereum)** – Native integration of Snowbridge pallets for ERC-20 asset movement and message passing with Ethereum mainnet. - **Message fan-out** – Bridge Bulletin instances distribute payloads to partner chains without duplicating relayer work. ### 🧩 **Specialized Pallets** - `pallet_bridge_grandpa` – Stores bridged finality proofs and validator sets. - `pallet_bridge_parachains` – Syncs parachain headers required for XCM and HRMP messaging. - `pallet_bridge_messages` – Manages outbound/inbound lanes, delivery proofs, and fee accounting for cross-chain messages. - `pallet_xcm_bridge_hub` – Provides XCM helpers for routing assets and arbitrary instructions over bridge lanes. ## Quick Start with Bridge Hub Connect to Bridge Hub using Dwellir's low-latency infrastructure: :::info Multi-network Access Dwellir maintains Bridge Hub connectivity across Polkadot environments: - **Polkadot Bridge Hub** – Production-grade routing parachain for trustless bridging. - **Westend Bridge Hub** – Official Polkadot testnet used for validating upgrades before mainnet rollout. - **Paseo Bridge Hub** – Community-driven public testnet mirroring upcoming Polkadot features. - **Kusama Bridge Hub** – Economic canary network that ships features before Polkadot. ::: ### Installation & Setup ```bash # Discover supported RPC namespaces curl -X POST https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 }' # Fetch latest bridged Westend block hash curl -X POST https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_call", "params": [ "BridgeWestendGrandpa_finalityApi_bestFinalized", "0x" ], "id": 2 }' ``` ```typescript // Connect to Bridge Hub const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Confirm we are on Bridge Hub const [chain, version] = await Promise.all([ api.rpc.system.chain(), api.rpc.system.version() ]); console.log(`Connected to ${chain} v${version}`); // Inspect the latest bridged Westend finality proof const bestWestendFinality = await api.query.bridgeWestendGrandpa.bestFinalized(); console.log('Best Westend header finalized on Bridge Hub:', bestWestendFinality.toString()); // Track Snowbridge outbound lane metrics const outboundLanes = await api.query.bridgeWestendMessages.outboundLanes.entries(); outboundLanes.slice(0, 1).forEach(([key, value]) => { console.log('Outbound lane', key.args[0].toString(), value.toHuman()); }); ``` ```rust use jsonrpsee::rpc_params; use substrate_api_client::{rpc::JsonrpseeClient, Api, GetBlockHash}; #[tokio::main] async fn main() -> anyhow::Result<()> { let client = JsonrpseeClient::with_url("https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY").await?; let api = Api::new(client).await?; // Fetch parachain head let head = api.get_finalized_head().await?; println!("Latest Bridge Hub head: {head}"); // Query BEEFY justification root published by Bridge Hub let beefy_head: Option = api .rpc() .request("beefy_getFinalizedHead", rpc_params![]) .await?; println!("Latest BEEFY finalized head: {:?}", beefy_head); // Inspect permissionless lane pallet state let storage_key = api.metadata().storage_map_key( "BridgeRelayersForPermissionlessLanes", "RelayerConfig", &0u32, )?; let config: Option> = api.get_storage_by_key(storage_key, None).await?; println!("Permissionless relayer config: {:?}", config); Ok(()) } ``` ```python from substrateinterface import SubstrateInterface substrate = SubstrateInterface( url="wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY" ) chain_name = substrate.rpc_request("system_chain", []) print("Chain:", chain_name["result"]) # Retrieve head committed to the Kusama bridge lane best_header = substrate.query( module='BridgeWestendGrandpa', storage_function='BestFinalized' ) print("Best bridged Westend header:", best_header) # Check outbound message lane status for Snowbridge lane_status = substrate.query( module='EthereumOutboundQueue', storage_function='Outbox', params=[0] ) print("Snowbridge outbound lane 0 status:", lane_status.value) ``` ## Network Information Genesis Hash 0xdcf691b5... Bridge Hub (Polkadot) Block Time 6 seconds Aura + Relay finality Native Token DOT Fees paid via Relay Chain Parachain ID 1002 Polkadot system parachain :::info Network Details - **Relay Chain**: Polkadot - **Genesis Hash**: `0xdcf691b5a3fbe24adc99ddc959c0561b973e329b1aef4c4b22e7bb2ddecb4464` - **Consensus**: Collator-produced blocks with Polkadot relay GRANDPA finality - **Bridged Counterparts**: Kusama (Westend), Bridge Bulletin, Ethereum (Snowbridge) - **Security**: On-chain slashable relayer incentives via `pallet_bridge_relayers` ::: ## Available JSON-RPC Methods Bridge Hub exposes the standard Substrate namespaces alongside bridge-specific RPCs for GRANDPA, BEEFY, and Snowbridge messaging. Use the tables below to jump straight to the reference pages that match your integration needs. ### Core Substrate namespaces | Group | Purpose | Key Methods | |-------|---------|-------------| | `system_*` | Node health, network peers, runtime properties | [`system_health`](/bridge-hub/system_health), [`system_version`](/bridge-hub/system_version), [`system_properties`](/bridge-hub/system_properties) | | `chain_*` | Blocks, headers, and finality subscriptions | [`chain_getHeader`](/bridge-hub/chain_getHeader), [`chain_getFinalizedHead`](/bridge-hub/chain_getFinalizedHead), [`chain_subscribeNewHeads`](/bridge-hub/chain_subscribeNewHeads) | | `state_*` | Storage reads, metadata, runtime calls | [`state_getStorage`](/bridge-hub/state_getStorage), [`state_getRuntimeVersion`](/bridge-hub/state_getRuntimeVersion), [`state_getKeysPaged`](/bridge-hub/state_getKeysPaged) | | `author_*` | Extrinsic submission lifecycle | [`author_submitExtrinsic`](/bridge-hub/author_submitExtrinsic), [`author_submitAndWatchExtrinsic`](/bridge-hub/author_submitAndWatchExtrinsic), [`author_pendingExtrinsics`](/bridge-hub/author_pendingExtrinsics) | | `grandpa_*` | Finality gadget status for the parachain | [`grandpa_roundState`](/bridge-hub/grandpa_roundState) | | `rpc_methods` | Discover every enabled namespace | [`rpc_methods`](/bridge-hub/rpc_methods) | ### Bridge & BEEFY namespaces | Namespace | Purpose | Methods | |-----------|---------|---------| | `beefy_*` | Inspect the latest BEEFY justifications broadcast to Snowbridge | [`beefy_getFinalizedHead`](/bridge-hub/beefy_getFinalizedHead) | | `bridge_grandpa_*` | Pending public release — current nodes return `-32601 Method not found` | _Coming soon_ | | `bridge_messages_*` | Pending public release — current nodes return `-32601 Method not found` | _Coming soon_ | ## Bridge Protocols ### Snowbridge (Ethereum ↔ Polkadot) - **BEEFY light client** verifies Ethereum finality proofs and publishes outbound commitments. - **Inbound queue** accepts ERC-20 and arbitrary message payloads via event proofs. - **Outbound queue** batches Polkadot-origin messages and anchors them on Ethereum. ### Kusama Bridge (Westend ↔ Polkadot) - **BridgeWestendGrandpa** pallet syncs Westend finality headers and validator sets. - **BridgeWestendParachains** tracks parachain heads to validate XCM and HRMP messages. - **BridgeWestendMessages** exposes lane metrics, delivery confirmations, and fee accounting. ### Bridge Bulletin - **Polkadot Bulletin** acts as a hub-and-spoke relay for partners requiring broadcast style delivery. - **Permissionless lanes** allow new chains to request connectivity without runtime upgrades. ## XCM Integration Bridge Hub exposes `pallet_xcm_bridge_hub` helpers for routing XCM messages over bridge lanes. ```typescript const api = await ApiPromise.create({ provider: new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY') }); const laneId = 0; // Snowbridge outbound lane const beneficiary = { parents: 2, interior: { X1: { AccountId32: { network: 'Any', id: '0x...' } } } }; const assets = { parents: 1, interior: 'Here' }; const tx = api.tx.xcmBridgeHub.sendAssetsOverBridge( laneId, beneficiary, assets, new BN('100000000000'), 'Unlimited' ); await tx.signAndSend('//Alice', ({ status }) => { if (status.isInBlock) { console.log('Bridge XCM submitted in block', status.asInBlock.toString()); } }); ``` ## Development Guides ### 1. Finality Relayer Checklist - Subscribe to `bridgeWestendGrandpa.bestFinalized` and `bridgePolkadotBulletinGrandpa.bestFinalized` storage changes. - Submit new proofs via `BridgeGrandpa.submit_finality_proof` extrinsics when headers advance by configured intervals. - Monitor `pallet_bridge_relayers::Rewards` to reconcile payments. ### 2. Message Relayer Operations - Watch `bridgeWestendMessages.outboundLanes(laneId)` for `latest_generated_nonce` vs `latest_received_nonce`. - When public proof RPCs are released, fetch Merkle lane proofs before submitting to bridged chains (currently relayers must build proofs off-chain). - Handle rejections by inspecting `bridgeHub` events: `MessageDispatched` and `MessageRejected`. ### 3. Observability & Alerting - Track BEEFY justifications with `beefy_subscribeJustifications` for Snowbridge health. - Use `state_traceBlock` on Bridge Hub to replay block execution when diagnosing bridge stalls. - Surface metrics such as `MessageQueue.Processed` events to confirm queue throughput. ## Monitoring & Troubleshooting | Scenario | Diagnostic Steps | Resolution | |----------|------------------|------------| | Lane backpressure | Compare `latest_generated_nonce` and `latest_confirmed_nonce` on outbound lanes | Increase relayer frequency or investigate failed proofs | | Proof rejected on target chain | Rebuild proofs off-chain and verify against the target runtime | Re-submit with corrected payload or wait for next finalized header | | BEEFY stalled | Check `beefy_subscribeJustifications` stream and collator logs | Restart Snowbridge relayer or investigate validator availability | With Dwellir endpoints you get globally replicated infrastructure, WebSocket support for proof streaming, and archive access for rebuilding historical proofs. --- ## payment_queryFeeDetails - Bridge Hub RPC Method # payment_queryFeeDetails Returns a detailed breakdown of fees for a given extrinsic on Bridge Hub. Unlike `payment_queryInfo` which returns the total fee, this method separates the fee into its component parts. ## Use Cases - **Fee analysis** - Understand fee composition for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Optimization** - Identify which fee component dominates costs - **Debugging** - Diagnose unexpected fee amounts ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `Bytes` | Yes | SCALE-encoded extrinsic (signed or unsigned) | | `blockHash` | `Hash` | No | Block hash for fee calculation context | ## Returns | Field | Type | Description | |-------|------|-------------| | `inclusionFee` | `Option` | Fee details (null for unsigned extrinsics) | ### InclusionFee Structure | Field | Type | Description | |-------|------|-------------| | `baseFee` | `Balance` | Fixed base fee per extrinsic | | `lenFee` | `Balance` | Fee based on encoded extrinsic length | | `adjustedWeightFee` | `Balance` | Fee based on execution weight | ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "payment_queryFeeDetails", "params": ["0x...encodedExtrinsic"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Create a sample transfer const tx = api.tx.balances.transferKeepAlive( '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 1000000000000n ); // Get fee details const feeDetails = await api.rpc.payment.queryFeeDetails(tx.toHex()); if (feeDetails.inclusionFee.isSome) { const fee = feeDetails.inclusionFee.unwrap(); console.log('Base fee:', fee.baseFee.toString()); console.log('Length fee:', fee.lenFee.toString()); console.log('Weight fee:', fee.adjustedWeightFee.toString()); } await api.disconnect(); ``` ```python url = 'https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY' # Replace with actual encoded extrinsic encoded_extrinsic = '0x...' payload = { 'jsonrpc': '2.0', 'method': 'payment_queryFeeDetails', 'params': [encoded_extrinsic], 'id': 1 } response = requests.post(url, json=payload) result = response.json()['result'] if result['inclusionFee']: fee = result['inclusionFee'] print(f"Base fee: {fee['baseFee']}") print(f"Length fee: {fee['lenFee']}") print(f"Weight fee: {fee['adjustedWeightFee']}") ``` ## Fee Components Explained | Component | Calculation | Optimization | |-----------|-------------|--------------| | **Base fee** | Fixed per extrinsic | Batch calls to share base fee | | **Length fee** | `length * lengthToFee` | Minimize call data size | | **Weight fee** | `weight * weightToFee` | Choose efficient operations | ## Related Methods - [`payment_queryInfo`](./payment_queryInfo) - Get total fee estimate - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction - [`state_call`](./state_call) - Call TransactionPaymentApi directly --- ## payment_queryInfo - Bridge Hub RPC Method # payment_queryInfo Estimates the fee for an extrinsic on Bridge Hub. ## Use Cases - **Fee estimation** - Calculate transaction costs before sending - **UI display** - Show fees to users for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Transaction planning** - Ensure sufficient funds ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `String` | Yes | Hex-encoded unsigned extrinsic | | `blockHash` | `String` | No | Block hash for fee calculation | ## Request ```json { "jsonrpc": "2.0", "method": "payment_queryInfo", "params": ["0x..."], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `weight` | `Object` | Transaction weight | | `class` | `String` | Dispatch class | | `partialFee` | `String` | Estimated fee | ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "payment_queryInfo", "params": ["0x..."], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Create transfer (unsigned for estimation) const transfer = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000); const info = await transfer.paymentInfo('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'); console.log('Partial fee:', info.partialFee.toHuman()); await api.disconnect(); ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction --- ## rpc_methods - Bridge Hub RPC Method # rpc_methods Returns a list of all RPC methods available on Bridge Hub. ## Use Cases - **API discovery** - List all available methods - **Compatibility checking** - Verify method availability for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Documentation** - Auto-generate method lists ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const methods = await api.rpc.rpc.methods(); console.log('Available methods:', methods.methods.length); await api.disconnect(); ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## state_call - Bridge Hub RPC Method # state_call Calls a runtime API method on Bridge Hub. ## Use Cases - **Runtime computations** - Execute runtime logic without transactions - **Account queries** - Use AccountNonceApi for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Fee estimation** - Use TransactionPaymentApi ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `method` | `String` | Yes | Runtime API method name | | `data` | `String` | Yes | SCALE-encoded call data | | `blockHash` | `String` | No | Block hash for historical call | ## Request ```json { "jsonrpc": "2.0", "method": "state_call", "params": ["AccountNonceApi_account_nonce", "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"], "id": 1 } ``` ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_call", "params": ["AccountNonceApi_account_nonce", "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get account nonce via runtime API const account = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const result = await api.call.accountNonceApi.accountNonce(account); console.log('Account nonce:', result.toNumber()); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Query storage - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## state_getKeys - JSON-RPC Method(Bridge-hub) ## Description Returns storage keys that match a given prefix. This JSON-RPC method is useful for discovering all storage entries under a specific module or querying multiple related storage items. Be cautious with broad prefixes as they may return large result sets. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `prefix` | string | Yes | Hex-encoded storage key prefix to match | | `blockHash` | string | No | Block hash to query at. If omitted, uses the latest block | ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | array | Array of hex-encoded storage keys matching the prefix | ## Request Example ```json { "jsonrpc": "2.0", "method": "state_getKeys", "params": [ "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9" ], "id": 1 } ``` ## Response Example ```json { "jsonrpc": "2.0", "result": [ "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9de1e86a9a8c739864cf3cc5ec2bea59fd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d", "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da94f9aea1afa791265fae359272badc1cf8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48" ], "id": 1 } ``` ## Code Examples ```python from substrateinterface import SubstrateInterface def get_storage_keys(prefix, block_hash=None): url = "https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY" headers = { "Content-Type": "application/json" } params = [prefix, block_hash] if block_hash else [prefix] payload = { "jsonrpc": "2.0", "method": "state_getKeys", "params": params, "id": 1 } response = requests.post(url, headers=headers, data=json.dumps(payload)) return response.json()["result"] # Example: Get all validator preferences keys def get_validator_keys(): # Staking.Validators storage prefix prefix = "0x5f3e4907f716ac89b6347d15ececedca9320c2dc4f5d7af5b320b04e2d1a3ff3" keys = get_storage_keys(prefix) print(f"Found {len(keys)} validator preference entries") for key in keys: # Extract validator account from key validator_account = key[-64:] print(f"Validator: 0x{validator_account}") return keys # Example: Query all keys under a module def get_module_keys(module_prefix): keys = get_storage_keys(module_prefix) # Group keys by storage item storage_items = {} for key in keys: # Storage keys typically have a fixed prefix per item item_prefix = key[:66] # First 33 bytes (66 hex chars) if item_prefix not in storage_items: storage_items[item_prefix] = [] storage_items[item_prefix].append(key) return storage_items ``` ```javascript const getStorageKeys = async (prefix, blockHash = null) => { const params = blockHash ? [prefix, blockHash] : [prefix]; const response = await fetch('https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'state_getKeys', params: params, id: 1 }) }); const data = await response.json(); return data.result; }; // Get all account keys (System.Account storage) const accountPrefix = '0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9'; const accountKeys = await getStorageKeys(accountPrefix); console.log(`Found ${accountKeys.length} accounts`); // Extract account addresses from keys accountKeys.forEach(key => { // The account address is the last 32 bytes of the key const addressHex = key.slice(-64); console.log('Account key:', key); console.log('Address portion:', addressHex); }); ``` ```typescript async function queryStorageKeys() { const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Method 1: Using high-level API to get keys const accountKeys = await api.query.system.account.keys(); console.log('Account addresses:', accountKeys.map(k => k.toHuman())); // Method 2: Using low-level RPC for custom prefixes const prefix = api.query.system.account.keyPrefix(); const keys = await api.rpc.state.getKeys(prefix); console.log(`Found ${keys.length} account storage keys`); // Method 3: Get keys for a specific map entry const validatorKeys = await api.query.staking.validators.keys(); console.log('Active validators:', validatorKeys.length); // Process keys to extract data for (const key of keys) { // Decode the storage key const keyHex = key.toHex(); console.log('Storage key:', keyHex); // Get the value for this key const value = await api.rpc.state.getStorage(key); console.log('Storage value:', value.toHex()); } await api.disconnect(); } // Advanced: Query keys with pagination async function getKeysPagedExample() { const api = await ApiPromise.create({ provider: new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY') }); const prefix = api.query.system.account.keyPrefix(); const pageSize = 100; let startKey = prefix; let allKeys = []; while (true) { // Note: state_getKeysPaged is used for pagination const keys = await api.rpc.state.getKeysPaged(prefix, pageSize, startKey); if (keys.length === 0) break; allKeys = allKeys.concat(keys); startKey = keys[keys.length - 1]; console.log(`Fetched ${keys.length} keys, total: ${allKeys.length}`); if (keys.length < pageSize) break; } console.log(`Total keys found: ${allKeys.length}`); await api.disconnect(); } ``` ## Common Storage Prefixes | Module | Storage Item | Prefix (example) | |--------|--------------|------------------| | System | Account | `0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9` | | Balances | TotalIssuance | `0xc2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80` | | Staking | Validators | `0x5f3e4907f716ac89b6347d15ececedca9320c2dc4f5d7af5b320b04e2d1a3ff3` | | Session | NextKeys | `0xcec5070d609dd3497f72bde07fc96ba0e0cdd062e6eaf24295ad4ccfc41d4609` | ## Batch Query Example ```javascript // Efficiently query multiple storage values async function batchQueryStorage(api, keys) { // Get all values in a single call const values = await api.rpc.state.queryStorageAt(keys); const results = {}; keys.forEach((key, index) => { results[key.toString()] = values[index]; }); return results; } // Example usage const keys = await getStorageKeys(accountPrefix); const values = await batchQueryStorage(api, keys.slice(0, 10)); console.log('Batch query results:', values); ``` ## Use Cases 1. **Account Discovery**: Find all accounts with balances 2. **Validator Enumeration**: List all validators in the network 3. **Storage Analysis**: Analyze storage usage by module 4. **Migration Scripts**: Iterate over storage for upgrades 5. **Indexing**: Build indexes of on-chain data ## Notes - Large prefixes may return many keys - use pagination when available - Keys are returned in lexicographical order - The prefix must be hex-encoded - Consider using `state_getKeysPaged` for large datasets - Storage keys include both the storage prefix and the key data ## Related Methods - [`state_getKeysPaged`](/bridge-hub/state_getKeysPaged) - Get keys with pagination - [`state_getStorage`](/bridge-hub/state_getStorage) - Get storage value - [`state_getMetadata`](/bridge-hub/state_getMetadata) - Get metadata to decode keys --- ## state_getKeysPaged - Bridge Hub RPC Method # state_getKeysPaged Returns storage keys with pagination on Bridge Hub. ## Use Cases - **Storage iteration** - Enumerate storage map entries - **Data export** - Bulk export chain data for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Account enumeration** - List all accounts ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `prefix` | `String` | Yes | Storage key prefix | | `count` | `Number` | Yes | Maximum keys to return | | `startKey` | `String` | No | Key to start after | | `blockHash` | `String` | No | Block hash for historical query | ## Request ```json { "jsonrpc": "2.0", "method": "state_getKeysPaged", "params": ["0x...", 100], "id": 1 } ``` ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getKeysPaged", "params": ["0x26aa394eea5630e07c48ae0c9558cef7", 100], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get all accounts (paginated) const keys = await api.rpc.state.getKeysPaged( api.query.system.account.keyPrefix(), 100 ); console.log('Found accounts:', keys.length); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Get storage value - [`state_queryStorageAt`](./state_queryStorageAt) - Batch storage query --- ## state_getMetadata - Bridge Hub RPC Method # state_getMetadata Returns the runtime metadata on Bridge Hub. ## Use Cases - **Runtime introspection** - Discover available pallets and calls - **Extrinsic building** - Get call and type information for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Storage key generation** - Build storage keys from metadata - **Client generation** - Auto-generate typed APIs ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash for historical metadata | ## Request ```json { "jsonrpc": "2.0", "method": "state_getMetadata", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getMetadata", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get runtime metadata const metadata = await api.rpc.state.getMetadata(); // List available pallets const pallets = metadata.asLatest.pallets.map(p => p.name.toString()); console.log('Available pallets:', pallets); // Get specific pallet info const systemPallet = metadata.asLatest.pallets.find(p => p.name.toString() === 'System'); console.log('System pallet calls:', systemPallet.calls.isSome ? 'Available' : 'None'); await api.disconnect(); ``` ```python def get_metadata(): url = 'https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'state_getMetadata', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] metadata_hex = get_metadata() print(f'Metadata length: {len(metadata_hex)} bytes') ``` ## Related Methods - [`state_getRuntimeVersion`](./state_getRuntimeVersion) - Get runtime version - [`state_getStorage`](./state_getStorage) - Query storage --- ## state_getRuntimeVersion - Bridge Hub RPC Method # state_getRuntimeVersion Returns the runtime version on Bridge Hub. ## Use Cases - **Version checking** - Verify runtime compatibility - **Upgrade detection** - Monitor for runtime upgrades on trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Client compatibility** - Ensure API compatibility ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash for historical version | ## Request ```json { "jsonrpc": "2.0", "method": "state_getRuntimeVersion", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getRuntimeVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const version = await api.rpc.state.getRuntimeVersion(); console.log('Spec name:', version.specName.toString()); console.log('Spec version:', version.specVersion.toNumber()); console.log('Impl version:', version.implVersion.toNumber()); await api.disconnect(); ``` ```python def get_runtime_version(): url = 'https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'state_getRuntimeVersion', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] version = get_runtime_version() print(f"Spec: {version['specName']} v{version['specVersion']}") ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata - [`system_version`](./system_version) - Get node version --- ## state_getStorage - Bridge Hub RPC Method # state_getStorage Returns a storage entry at a specific key on Bridge Hub. > **Why Bridge Hub?** Build on Polkadot's trustless bridging parachain with $75M+ TVL via Snowbridge to Ethereum with on-chain BEEFY/Beacon light clients (no multisigs), 100+ ERC-20 tokens supported, 24+ parachain integrations, and 1-2 minute transfer times. ## Use Cases - **State queries** - Read on-chain storage values - **Account balances** - Query account data for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Pallet storage** - Access runtime storage items - **Historical state** - Query state at specific blocks ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `key` | `String` | Yes | Storage key (hex-encoded) | | `blockHash` | `String` | No | Block hash for historical query | ## Request ```json { "jsonrpc": "2.0", "method": "state_getStorage", "params": [""], "id": 1 } ``` ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getStorage", "params": [""], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query account balance const account = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const accountInfo = await api.query.system.account(account); console.log('Free balance:', accountInfo.data.free.toString()); // Query at specific block const blockHash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'; const historicalBalance = await api.query.system.account.at(blockHash, account); console.log('Historical balance:', historicalBalance.data.free.toString()); await api.disconnect(); ``` ```python def get_storage(key, block_hash=None): url = 'https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY' params = [key] if block_hash is None else [key, block_hash] payload = { 'jsonrpc': '2.0', 'method': 'state_getStorage', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] # Query :code storage (runtime wasm) storage_key = '' value = get_storage(storage_key) print(f'Storage value: {value[:66]}...' if value else 'None') ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata - [`state_getKeysPaged`](./state_getKeysPaged) - Enumerate storage keys --- ## state_queryStorageAt - Bridge Hub RPC Method # state_queryStorageAt Query multiple storage keys at a specific block on Bridge Hub. ## Use Cases - **Batch queries** - Efficiently query multiple storage items - **Snapshot state** - Get consistent multi-key state for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Data analysis** - Compare storage across blocks ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `keys` | `Array` | Yes | Array of storage keys | | `blockHash` | `String` | No | Block hash for query | ## Request ```json { "jsonrpc": "2.0", "method": "state_queryStorageAt", "params": [[""]], "id": 1 } ``` ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_queryStorageAt", "params": [[""]], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query multiple accounts at once const accounts = ['5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY']; const entries = await api.query.system.account.multi(accounts); entries.forEach((info, idx) => { console.log(`Account ${idx}: ${info.data.free.toString()}`); }); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Single storage query - [`state_getKeysPaged`](./state_getKeysPaged) - Enumerate keys --- ## system_chain - Bridge Hub RPC Method # system_chain Returns the chain name on Bridge Hub. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const chain = await api.rpc.system.chain(); console.log('Chain:', chain.toString()); await api.disconnect(); ``` ## Related Methods - [`system_name`](./system_name) - Get node implementation name - [`system_version`](./system_version) - Get node version --- ## system_health - Bridge Hub RPC Method # system_health Returns the health status of the Bridge Hub node. ## Use Cases - **Health checks** - Monitor node availability - **Load balancing** - Route traffic based on health for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **Sync status** - Verify node is synced ## Parameters This method accepts no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `peers` | `Number` | Connected peer count | | `isSyncing` | `Boolean` | Whether node is syncing | | `shouldHavePeers` | `Boolean` | Whether node should have peers | ## Request ```json { "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const health = await api.rpc.system.health(); console.log('Peers:', health.peers.toNumber()); console.log('Is syncing:', health.isSyncing.isTrue); await api.disconnect(); ``` ```python def get_health(): url = 'https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'system_health', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] health = get_health() print(f"Peers: {health['peers']}") print(f"Syncing: {health['isSyncing']}") ``` ## Related Methods - [`system_version`](./system_version) - Get node version - [`system_chain`](./system_chain) - Get chain name --- ## system_name - Bridge Hub RPC Method # system_name Returns the node implementation name on Bridge Hub. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_name", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_name", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const name = await api.rpc.system.name(); console.log('Node name:', name.toString()); await api.disconnect(); ``` ## Related Methods - [`system_version`](./system_version) - Get node version - [`system_chain`](./system_chain) - Get chain name --- ## system_properties - Bridge Hub RPC Method # system_properties Returns chain properties including token symbol and decimals on Bridge Hub. ## Use Cases - **Token formatting** - Get decimals and symbol for trustless ETH and ERC-20 bridging, cross-chain messaging, and parachain-to-Ethereum asset transfers - **UI configuration** - Configure wallets and dApps - **Address formatting** - Get SS58 prefix ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_properties", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_properties", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const props = await api.rpc.system.properties(); console.log('Token symbol:', props.tokenSymbol.toString()); console.log('Token decimals:', props.tokenDecimals.toString()); console.log('SS58 prefix:', props.ss58Format.toString()); await api.disconnect(); ``` ## Related Methods - [`system_chain`](./system_chain) - Get chain name - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## system_version - Bridge Hub RPC Method # system_version Returns the node implementation version on Bridge Hub. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_version", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_version", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-bridge-hub-polkadot.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const version = await api.rpc.system.version(); console.log('Version:', version.toString()); await api.disconnect(); ``` ## Related Methods - [`system_chain`](./system_chain) - Get chain name - [`state_getRuntimeVersion`](./state_getRuntimeVersion) - Get runtime version --- ## debug_traceBlock - BSC RPC Method # debug_traceBlock Traces all transactions in a block on Binance Smart Chain by block RLP. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Analyze transaction execution step-by-step - **Smart contract analysis** - Debug contract interactions - **Security auditing** - Trace internal calls for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockRlp` | `DATA` | Yes | RLP-encoded block data | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); // Use debug_traceBlockByNumber instead (more practical) const traces = await provider.send('debug_traceBlockByNumber', ['latest', {}]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by block number - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by block hash --- ## debug_traceBlockByHash - BSC RPC Method # debug_traceBlockByHash Traces all transactions in a block on Binance Smart Chain by block hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0xc2b1f9c182513683b2358397114147563e5eb5a0be5d153487f15bb32ea559ff", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0xc2b1f9c182513683b2358397114147563e5eb5a0be5d153487f15bb32ea559ff", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0xc2b1f9c182513683b2358397114147563e5eb5a0be5d153487f15bb32ea559ff'; const traces = await provider.send('debug_traceBlockByHash', [blockHash, { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by number - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceBlockByNumber - BSC RPC Method # debug_traceBlockByNumber Traces all transactions in a block on Binance Smart Chain by block number. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('debug_traceBlockByNumber', ['latest', { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by hash - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceCall - BSC RPC Method # debug_traceCall Traces a call without creating a transaction on Binance Smart Chain. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction simulation** - Debug before sending - **Gas analysis** - Analyze gas usage per opcode - **Contract debugging** - Step through execution for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `call` | `Object` | Yes | Call object (same as eth_call) | | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ { "to": "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "data": "0x70a082310000000000000000000000008894E0a0c962CB723c1976a4421c95949bE2D4E3" }, "latest", {} ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ {"to": "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "data": "0x70a082310000000000000000000000008894E0a0c962CB723c1976a4421c95949bE2D4E3"}, "latest", {"tracer": "callTracer"} ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const trace = await provider.send('debug_traceCall', [ { to: '0x8894E0a0c962CB723c1976a4421c95949bE2D4E3', data: '0x70a082310000000000000000000000008894E0a0c962CB723c1976a4421c95949bE2D4E3' }, 'latest', { tracer: 'callTracer' } ]); console.log('Trace:', trace); ``` ## Related Methods - [`eth_call`](./eth_call) - Execute call without trace - [`debug_traceTransaction`](./debug_traceTransaction) - Trace actual transaction --- ## debug_traceTransaction - BSC RPC Method # debug_traceTransaction Traces a transaction execution on Binance Smart Chain by transaction hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Understand exactly what happened - **Failure analysis** - Find where and why a transaction reverted - **Gas optimization** - Analyze gas usage for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Tracer Options - `{}` - Default opcode tracer (verbose) - `{ tracer: "callTracer" }` - Call tree tracer - `{ tracer: "prestateTracer" }` - Pre-state tracer ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x15f20ca5615d94cc4685b9132ce7d5aafd5a4967197a2b3eec0bbbfef5eba10c", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x15f20ca5615d94cc4685b9132ce7d5aafd5a4967197a2b3eec0bbbfef5eba10c", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x15f20ca5615d94cc4685b9132ce7d5aafd5a4967197a2b3eec0bbbfef5eba10c'; // Call tracer - shows internal calls const callTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'callTracer' } ]); console.log('Type:', callTrace.type); console.log('From:', callTrace.from); console.log('To:', callTrace.to); console.log('Gas used:', parseInt(callTrace.gasUsed, 16)); // Prestate tracer - shows state before execution const prestateTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'prestateTracer' } ]); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x15f20ca5615d94cc4685b9132ce7d5aafd5a4967197a2b3eec0bbbfef5eba10c' # Call tracer trace = w3.provider.make_request('debug_traceTransaction', [ tx_hash, {'tracer': 'callTracer'} ]) print(f'Trace type: {trace["result"]["type"]}') print(f'Gas used: {int(trace["result"]["gasUsed"], 16)}') ``` ## Related Methods - [`debug_traceCall`](./debug_traceCall) - Trace without executing - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace entire block --- ## eth_accounts - BSC RPC Method # eth_accounts Returns a list of addresses owned by the client on Binance Smart Chain. > **Why BSC?** Build on the third-largest blockchain by market cap with $12B+ TVL and 37%+ DEX market share with sub-$0.10 fees, 2.6M daily active users, full EVM compatibility, and direct Binance integration. ## Important Note On public RPC endpoints like Dwellir, `eth_accounts` returns an empty array because the node does not hold any private keys. This method is primarily useful for: - Local development nodes (Ganache, Hardhat, Anvil) - Private nodes with managed accounts - Wallet provider connections (MetaMask injects accounts) ## When to Use This Method `eth_accounts` is relevant for DeFi developers, trading platform builders, and teams seeking Binance ecosystem access in specific scenarios: - **Development Testing** — Retrieve test accounts from local nodes - **Wallet Detection** — Check if a wallet provider has connected accounts - **Client Verification** — Confirm node account access capabilities ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `Array` | List of 20-byte account addresses owned by the client | **Return format**: Array of `0x` prefixed hexadecimal addresses (typically empty for public nodes) ## Request ```json { "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 } ``` ## Response ### Successful Response (Public Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [] } ``` ### Successful Response (Local Development Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [ "0x407d73d8a49eeb85d32cf465507dd71d507100c1", "0x85d32cf465507dd71d507100c1407d73d8a49eeb" ] } ``` ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_accounts', params: [], id: 1 }) }); const { result } = await response.json(); console.log('Accounts:', result); // Using ethers.js const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const accounts = await provider.listAccounts(); console.log('Accounts:', accounts); ``` ```python def get_accounts(): response = requests.post( 'https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_accounts', 'params': [], 'id': 1 } ) return response.json()['result'] accounts = get_accounts() print(f'Accounts: {accounts}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) print(f'Accounts: {w3.eth.accounts}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/rpc" ) func main() { client, err := rpc.Dial("https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } var accounts []string err = client.CallContext(context.Background(), &accounts, "eth_accounts") if err != nil { log.Fatal(err) } fmt.Printf("Accounts: %v\n", accounts) } ``` ## Common Use Cases ### 1. Development Environment Detection Check if running against a development node with test accounts: ```javascript async function isDevEnvironment(provider) { const accounts = await provider.listAccounts(); return accounts.length > 0; } const isDev = await isDevEnvironment(provider); if (isDev) { console.log('Development environment detected'); } ``` ### 2. Wallet Connection Check Verify wallet provider has connected accounts: ```javascript async function checkWalletConnection() { if (typeof window.ethereum === 'undefined') { return { connected: false, reason: 'No wallet detected' }; } const accounts = await window.ethereum.request({ method: 'eth_accounts' }); return { connected: accounts.length > 0, accounts: accounts }; } ``` ### 3. Fallback Account Selection Use first available account or request connection: ```javascript async function getActiveAccount() { // Check existing connections let accounts = await window.ethereum.request({ method: 'eth_accounts' }); // Request connection if no accounts if (accounts.length === 0) { accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); } return accounts[0] || null; } ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32601 | Method not found | Node may not support this method | | -32603 | Internal error | Retry with exponential backoff | ```javascript async function safeGetAccounts(provider) { try { const accounts = await provider.listAccounts(); return { success: true, accounts }; } catch (error) { if (error.code === -32601) { console.warn('eth_accounts not supported on this node'); return { success: false, accounts: [], reason: 'unsupported' }; } throw error; } } ``` ## Related Methods - [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102) — Request wallet connection (browser wallets) - [`eth_getBalance`](./eth_getBalance) — Get account balance - [`eth_getTransactionCount`](./eth_getTransactionCount) — Get account nonce --- ## eth_blockNumber - BSC RPC Method # eth_blockNumber Returns the number of the most recent block on Binance Smart Chain. > **Why BSC?** Build on the third-largest blockchain by market cap with $12B+ TVL and 37%+ DEX market share with sub-$0.10 fees, 2.6M daily active users, full EVM compatibility, and direct Binance integration. ## When to Use This Method `eth_blockNumber` is fundamental for DeFi developers, trading platform builders, and teams seeking Binance ecosystem access: - **Syncing Applications** — Keep your dApp in sync with the latest BSC blockchain state - **Transaction Monitoring** — Verify confirmations by comparing block numbers - **Event Filtering** — Set the correct block range for querying logs on high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications - **Health Checks** — Monitor node connectivity and sync status ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `QUANTITY` | Hexadecimal string representing the current block number | **Return format**: `0x` prefixed hexadecimal (e.g., `0x5BAD55` = 6,008,149 in decimal) ## Request ```json { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } ``` ## Response ### Successful Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5BAD55" } ``` ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error" } } ``` ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }) }); const { result } = await response.json(); const blockNumber = parseInt(result, 16); console.log('BSC block:', blockNumber); // Using ethers.js const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const blockNumber = await provider.getBlockNumber(); console.log('BSC block:', blockNumber); ``` ```python def get_block_number(): response = requests.post( 'https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_blockNumber', 'params': [], 'id': 1 } ) result = response.json()['result'] return int(result, 16) block_number = get_block_number() print(f'BSC block: {block_number}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) print(f'BSC block: {w3.eth.block_number}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockNumber, err := client.BlockNumber(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("BSC block: %d\n", blockNumber) } ``` ## Common Use Cases ### 1. Block Confirmation Counter Monitor transaction confirmations on BSC: ```javascript async function getConfirmations(provider, txHash) { const tx = await provider.getTransaction(txHash); if (!tx || !tx.blockNumber) return 0; const currentBlock = await provider.getBlockNumber(); return currentBlock - tx.blockNumber + 1; } // Wait for specific confirmations async function waitForConfirmations(provider, txHash, confirmations = 6) { let currentConfirmations = 0; while (currentConfirmations < confirmations) { currentConfirmations = await getConfirmations(provider, txHash); console.log(`Confirmations: ${currentConfirmations}/${confirmations}`); await new Promise(r => setTimeout(r, 2000)); } return true; } ``` ### 2. Event Log Filtering Query events from recent blocks on BSC: ```javascript async function getRecentEvents(provider, contract, eventName, blockRange = 100) { const currentBlock = await provider.getBlockNumber(); const fromBlock = currentBlock - blockRange; const filter = contract.filters[eventName](); const events = await contract.queryFilter(filter, fromBlock, currentBlock); return events; } ``` ### 3. Node Health Monitoring Check if your BSC node is synced: ```javascript async function checkNodeHealth(provider) { try { const blockNumber = await provider.getBlockNumber(); const block = await provider.getBlock(blockNumber); const now = Date.now() / 1000; const blockAge = now - block.timestamp; if (blockAge > 60) { console.warn(`Node may be behind. Last block was ${blockAge}s ago`); return false; } console.log(`Node healthy. Latest block: ${blockNumber}`); return true; } catch (error) { console.error('Node unreachable:', error); return false; } } ``` ## Performance Optimization ### Caching Strategy Cache block numbers to reduce API calls: ```javascript class BlockNumberCache { constructor(ttl = 2000) { this.cache = null; this.timestamp = 0; this.ttl = ttl; } async get(provider) { const now = Date.now(); if (this.cache && (now - this.timestamp) < this.ttl) { return this.cache; } this.cache = await provider.getBlockNumber(); this.timestamp = now; return this.cache; } invalidate() { this.cache = null; this.timestamp = 0; } } const blockCache = new BlockNumberCache(); ``` ### Batch Requests Combine with other calls for efficiency: ```javascript const batch = [ { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }, { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 }, { jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 } ]; const response = await fetch('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await response.json(); ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32603 | Internal error | Retry with exponential backoff | | -32005 | Rate limit exceeded | Implement rate limiting client-side | | -32000 | Execution reverted | Check node sync status | ```javascript async function safeGetBlockNumber(provider, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await provider.getBlockNumber(); } catch (error) { if (error.code === -32005) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } else if (i === maxRetries - 1) { throw error; } } } } ``` ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) — Get full block details by number - [`eth_getBlockByHash`](./eth_getBlockByHash) — Get block details by hash - [`eth_syncing`](./eth_syncing) — Check if node is still syncing --- ## eth_call - BSC RPC Method # eth_call Executes a new message call immediately without creating a transaction on Binance Smart Chain. Used for reading smart contract state. > **Why BSC?** Build on the third-largest blockchain by market cap with $12B+ TVL and 37%+ DEX market share with sub-$0.10 fees, 2.6M daily active users, full EVM compatibility, and direct Binance integration. ## Use Cases The `eth_call` method is essential for: - **Reading contract state** - Query view/pure functions - **Simulating transactions** - Test execution without gas costs - **DeFi integrations** - Check prices, balances, allowances for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications - **Complex queries** - Execute multi-step contract logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | 20-byte address executing the call | | `to` | `DATA` | Yes | 20-byte contract address | | `gas` | `QUANTITY` | No | Gas limit for the call | | `gasPrice` | `QUANTITY` | No | Gas price in wei | | `value` | `QUANTITY` | No | Value to send in wei | | `data` | `DATA` | Yes | Encoded function call data | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_call", "params": [ { "to": "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "data": "0x70a082310000000000000000000000008894E0a0c962CB723c1976a4421c95949bE2D4E3" }, "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | The return value of the executed contract function | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000" } ``` ## Code Examples ```bash # Call ERC20 balanceOf function curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{ "to": "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "data": "0x70a082310000000000000000000000008894E0a0c962CB723c1976a4421c95949bE2D4E3" }, "latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); // ERC20 ABI for common functions const ERC20_ABI = [ "function balanceOf(address owner) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function totalSupply() view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)" ]; // Read ERC20 token balance async function getTokenBalance(tokenAddress, walletAddress) { const contract = new Contract(tokenAddress, ERC20_ABI, provider); const balance = await contract.balanceOf(walletAddress); const decimals = await contract.decimals(); const symbol = await contract.symbol(); return { raw: balance.toString(), formatted: (Number(balance) / Math.pow(10, decimals)).toFixed(4), symbol: symbol }; } // Direct eth_call async function directCall(to, data) { const result = await provider.call({ to, data }); return result; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) def get_erc20_balance(token_address, wallet_address): # balanceOf(address) selector function_signature = "balanceOf(address)" function_selector = w3.keccak(text=function_signature)[:4].hex() # Encode address parameter encoded_address = wallet_address[2:].lower().zfill(64) data = function_selector + encoded_address # Make the call result = w3.eth.call({ 'to': token_address, 'data': data }) return int(result.hex(), 16) balance = get_erc20_balance( '0x8894E0a0c962CB723c1976a4421c95949bE2D4E3', '0x8894E0a0c962CB723c1976a4421c95949bE2D4E3' ) print(f'Balance: {balance}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0x8894E0a0c962CB723c1976a4421c95949bE2D4E3") data := common.FromHex("0x70a082310000000000000000000000008894E0a0c962CB723c1976a4421c95949bE2D4E3") msg := ethereum.CallMsg{ To: &contractAddress, Data: data, } result, err := client.CallContract(context.Background(), msg, nil) if err != nil { log.Fatal(err) } fmt.Printf("Result: 0x%x\n", result) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Contract function reverted | | -32602 | Invalid parameters | Invalid data encoding | | -32015 | VM execution error | Contract logic error | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas for transaction - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send actual transaction --- ## eth_chainId - BSC RPC Method # eth_chainId Returns the chain ID used for transaction signing on Binance Smart Chain. > **Why BSC?** Build on the third-largest blockchain by market cap with $12B+ TVL and 37%+ DEX market share with sub-$0.10 fees, 2.6M daily active users, full EVM compatibility, and direct Binance integration. ## Use Cases The `eth_chainId` method is essential for: - **Transaction signing** - Ensure transactions are signed for the correct network - **Network verification** - Confirm connection to the expected chain - **Multi-chain apps** - Handle different networks programmatically - **Wallet integration** - Validate network before transactions ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Chain ID in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1" } ``` ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const network = await provider.getNetwork(); console.log('Chain ID:', network.chainId); // Verify network before transaction async function verifyNetwork(expectedChainId) { const network = await provider.getNetwork(); if (network.chainId !== BigInt(expectedChainId)) { throw new Error(`Wrong network. Expected ${expectedChainId}, got ${network.chainId}`); } return true; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) chain_id = w3.eth.chain_id print(f'Chain ID: {chain_id}') # Verify network def verify_network(expected_chain_id): chain_id = w3.eth.chain_id if chain_id != expected_chain_id: raise ValueError(f'Wrong network. Expected {expected_chain_id}, got {chain_id}') return True ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } chainID, err := client.ChainID(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Chain ID: %d\n", chainID) } ``` ## Related Methods - [`net_version`](./net_version) - Get network version - [`eth_syncing`](./eth_syncing) - Check sync status --- ## eth_coinbase - Get coinbase address(Bsc) # eth_coinbase Get coinbase address on the Binance Smart Chain network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_coinbase](https://ethereum.org/developers/docs/apis/json-rpc/#eth_coinbase) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_coinbase", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_coinbase', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Binance Smart Chain documentation](/docs/bsc).* --- ## eth_estimateGas - BSC RPC Method # eth_estimateGas Estimates the gas necessary to execute a transaction on Binance Smart Chain. > **Why BSC?** Build on the third-largest blockchain by market cap with $12B+ TVL and 37%+ DEX market share with sub-$0.10 fees, 2.6M daily active users, full EVM compatibility, and direct Binance integration. ## Use Cases The `eth_estimateGas` method is essential for: - **Transaction preparation** - Set appropriate gas limits - **Cost estimation** - Calculate transaction costs before sending - **Error detection** - Identify reverts before spending gas - **DeFi operations** - Estimate costs for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | Sender address | | `to` | `DATA` | No | Recipient address | | `gas` | `QUANTITY` | No | Gas limit | | `gasPrice` | `QUANTITY` | No | Gas price | | `value` | `QUANTITY` | No | Value in wei | | `data` | `DATA` | No | Transaction data | ## Request ```json { "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "to": "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "value": "0x1" }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Estimated gas amount in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5208" } ``` **Note**: `0x5208` = 21000 gas (standard ETH transfer) ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "to": "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "value": "0x1" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); // Estimate simple transfer async function estimateTransfer(to, value) { const gasEstimate = await provider.estimateGas({ to: to, value: parseEther(value) }); console.log('Estimated gas:', gasEstimate.toString()); return gasEstimate; } // Estimate contract call async function estimateContractCall(contract, method, args) { const gasEstimate = await contract[method].estimateGas(...args); console.log('Estimated gas:', gasEstimate.toString()); // Add 20% buffer for safety return gasEstimate * 120n / 100n; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) def estimate_transfer(to, value_in_ether): gas_estimate = w3.eth.estimate_gas({ 'to': to, 'value': w3.to_wei(value_in_ether, 'ether') }) print(f'Estimated gas: {gas_estimate}') return gas_estimate def estimate_contract_call(contract, method, args): func = getattr(contract.functions, method) gas_estimate = func(*args).estimate_gas() # Add 20% buffer return int(gas_estimate * 1.2) # Estimate simple transfer gas = estimate_transfer('0x8894E0a0c962CB723c1976a4421c95949bE2D4E3', 0.1) ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } toAddress := common.HexToAddress("0x8894E0a0c962CB723c1976a4421c95949bE2D4E3") msg := ethereum.CallMsg{ To: &toAddress, Value: big.NewInt(1000000000000000000), } gasLimit, err := client.EstimateGas(context.Background(), msg) if err != nil { log.Fatal(err) } fmt.Printf("Estimated gas: %d\n", gasLimit) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Transaction would fail | | -32602 | Invalid params | Invalid transaction parameters | **Tip**: If estimation fails, the transaction would likely revert if sent. ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_feeHistory - BSC RPC Method # eth_feeHistory Returns historical gas information on Binance Smart Chain for fee estimation. ## Use Cases - **Fee prediction** - Estimate future gas prices based on history - **Gas analytics** - Analyze fee trends over time - **Optimal timing** - Find best times for transactions on high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockCount` | `QUANTITY` | Yes | Number of blocks in the range | | `newestBlock` | `QUANTITY\|TAG` | Yes | Highest block of the range | | `rewardPercentiles` | `Array` | Yes | Percentiles to sample for priority fees | ## Request ```json { "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const feeHistory = await provider.send('eth_feeHistory', ['0xa', 'latest', [25, 50, 75]]); console.log('Base fees:', feeHistory.baseFeePerGas.map(f => formatUnits(f, 'gwei'))); console.log('Reward (25th percentile):', feeHistory.reward.map(r => formatUnits(r[0], 'gwei'))); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) fee_history = w3.eth.fee_history(10, 'latest', [25, 50, 75]) print(f'Base fees: {[w3.from_wei(f, "gwei") for f in fee_history["baseFeePerGas"]]}') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee --- ## eth_gasPrice - BSC RPC Method # eth_gasPrice Returns the current gas price on Binance Smart Chain in wei. > **Why BSC?** Build on the third-largest blockchain by market cap with $12B+ TVL and 37%+ DEX market share with sub-$0.10 fees, 2.6M daily active users, full EVM compatibility, and direct Binance integration. ## Use Cases The `eth_gasPrice` method is essential for: - **Transaction pricing** - Set appropriate gas prices - **Cost estimation** - Calculate transaction costs before sending - **Gas monitoring** - Track network congestion - **DeFi operations** - Optimize costs for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Current gas price in wei (hexadecimal) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x3b9aca00" } ``` **Note**: `0x3b9aca00` = 1 Gwei (1,000,000,000 wei) ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); const gasPrice = feeData.gasPrice; console.log('Gas Price:', formatUnits(gasPrice, 'gwei'), 'Gwei'); // Calculate transaction cost async function estimateTransactionCost(gasLimit) { const feeData = await provider.getFeeData(); const cost = feeData.gasPrice * BigInt(gasLimit); return formatUnits(cost, 'ether'); } const cost = await estimateTransactionCost(21000); console.log('Transfer cost:', cost, 'ETH'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) gas_price = w3.eth.gas_price print(f'Gas Price: {w3.from_wei(gas_price, "gwei")} Gwei') # Calculate transaction cost def estimate_transaction_cost(gas_limit): gas_price = w3.eth.gas_price cost = gas_price * gas_limit return w3.from_wei(cost, 'ether') cost = estimate_transaction_cost(21000) print(f'Transfer cost: {cost} ETH') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } gasPrice, err := client.SuggestGasPrice(context.Background()) if err != nil { log.Fatal(err) } // Convert to Gwei gwei := new(big.Float).Quo( new(big.Float).SetInt(gasPrice), big.NewFloat(1e9), ) fmt.Printf("Gas Price: %f Gwei\n", gwei) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32603 | Internal error | Node error | ## Related Methods - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee (EIP-1559) - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas needed --- ## eth_getBalance - BSC RPC Method # eth_getBalance Returns the balance of a given address on Binance Smart Chain. > **Why BSC?** Build on the third-largest blockchain by market cap with $12B+ TVL and 37%+ DEX market share with sub-$0.10 fees, 2.6M daily active users, full EVM compatibility, and direct Binance integration. ## Use Cases The `eth_getBalance` method is essential for: - **Wallet applications** - Display user balances - **Transaction validation** - Check if account has sufficient funds - **DeFi applications** - Monitor collateral and liquidity for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications - **Account monitoring** - Track balance changes over time ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address to check balance for | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Integer of the current balance in wei (hexadecimal) | **Note**: 1 native token = 10^18 wei. Convert using `balance / 10^18`. ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1a055690d9db80000" } ``` ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const address = '0x8894E0a0c962CB723c1976a4421c95949bE2D4E3'; const balanceWei = await provider.getBalance(address); const balance = formatEther(balanceWei); console.log(`Balance: ${balance}`); // Get balance at specific block const historicalBalance = await provider.getBalance(address, 1000000); console.log(`Historical balance: ${formatEther(historicalBalance)}`); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) address = '0x8894E0a0c962CB723c1976a4421c95949bE2D4E3' balance_wei = w3.eth.get_balance(address) balance = w3.from_wei(balance_wei, 'ether') print(f'Balance: {balance}') # Get balance at specific block historical_balance = w3.eth.get_balance(address, block_identifier=1000000) print(f'Historical balance: {w3.from_wei(historical_balance, "ether")}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0x8894E0a0c962CB723c1976a4421c95949bE2D4E3") balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } // Convert to ether fbalance := new(big.Float).SetInt(balance) ethValue := new(big.Float).Quo(fbalance, big.NewFloat(1e18)) fmt.Printf("Balance: %f\n", ethValue) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid address format or block parameter | | -32000 | Execution error | Node execution error | ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_getTransactionCount`](./eth_getTransactionCount) - Get account nonce --- ## eth_getBlockByHash - BSC RPC Method # eth_getBlockByHash Returns information about a block by hash on Binance Smart Chain. > **Why BSC?** Build on the third-largest blockchain by market cap with $12B+ TVL and 37%+ DEX market share with sub-$0.10 fees, 2.6M daily active users, full EVM compatibility, and direct Binance integration. ## Use Cases The `eth_getBlockByHash` method is essential for: - **Block verification** - Verify block data using its unique hash - **Chain reorganization handling** - Track blocks during reorgs - **Cross-chain bridges** - Verify block finality for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications - **Deterministic queries** - Get consistent block data regardless of chain state ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0xc2b1f9c182513683b2358397114147563e5eb5a0be5d153487f15bb32ea559ff", false ], "id": 1 } ``` ## Returns Returns the same block object as `eth_getBlockByNumber`, or `null` if no block is found. | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used | | `transactions` | `Array` | Transaction objects or hashes | ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0xc2b1f9c182513683b2358397114147563e5eb5a0be5d153487f15bb32ea559ff", false ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0xc2b1f9c182513683b2358397114147563e5eb5a0be5d153487f15bb32ea559ff'; const block = await provider.getBlock(blockHash); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) block_hash = '0xc2b1f9c182513683b2358397114147563e5eb5a0be5d153487f15bb32ea559ff' block = w3.eth.get_block(block_hash) print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockHash := common.HexToHash("0xc2b1f9c182513683b2358397114147563e5eb5a0be5d153487f15bb32ea559ff") block, err := client.BlockByHash(context.Background(), blockHash) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block hash format | | -32000 | Block not found | Block with this hash does not exist | ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) - Get block by number - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number --- ## eth_getBlockByNumber - BSC RPC Method # eth_getBlockByNumber Returns information about a block by block number on Binance Smart Chain. > **Why BSC?** Build on the third-largest blockchain by market cap with $12B+ TVL and 37%+ DEX market share with sub-$0.10 fees, 2.6M daily active users, full EVM compatibility, and direct Binance integration. ## Use Cases The `eth_getBlockByNumber` method is essential for: - **Block explorers** - Display complete block information - **Transaction indexers** - Process all transactions in a block - **Analytics platforms** - Analyze blockchain data for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications - **Timestamp verification** - Get block timestamps for time-based logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used by all transactions | | `gasLimit` | `QUANTITY` | Maximum gas allowed in block | | `transactions` | `Array` | Array of transaction objects or hashes | | `baseFeePerGas` | `QUANTITY` | Base fee per gas (EIP-1559) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": { "number": "0x5BAD55", "hash": "0xc2b1f9c182513683b2358397114147563e5eb5a0be5d153487f15bb32ea559ff", "parentHash": "0x...", "timestamp": "0x64d8f6d0", "gasUsed": "0x1234", "gasLimit": "0x1c9c380", "transactions": [], "baseFeePerGas": "0x5f5e100" } } ``` ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); // Get latest block const block = await provider.getBlock('latest'); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); console.log('Transactions:', block.transactions.length); // Get block with full transactions const blockWithTxs = await provider.getBlock('latest', true); for (const tx of blockWithTxs.prefetchedTransactions) { console.log('Transaction:', tx.hash); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) # Get latest block block = w3.eth.get_block('latest') print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') print(f'Transactions: {len(block.transactions)}') # Get block with full transactions block_full = w3.eth.get_block('latest', full_transactions=True) for tx in block_full.transactions: print(f'Transaction: {tx.hash.hex()}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } // Get latest block block, err := client.BlockByNumber(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) fmt.Printf("Timestamp: %d\n", block.Time()) fmt.Printf("Transactions: %d\n", len(block.Transactions())) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block number or parameter format | | -32000 | Block not found | Block does not exist | ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number - [`eth_getBlockByHash`](./eth_getBlockByHash) - Get block by hash - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_getCode - BSC RPC Method # eth_getCode Returns the bytecode at a given address on Binance Smart Chain. > **Why BSC?** Build on the third-largest blockchain by market cap with $12B+ TVL and 37%+ DEX market share with sub-$0.10 fees, 2.6M daily active users, full EVM compatibility, and direct Binance integration. ## Use Cases The `eth_getCode` method is essential for: - **Contract verification** - Check if address is a contract - **Security analysis** - Verify deployed bytecode matches expected - **DeFi integrations** - Validate contracts before interactions - **Protocol analysis** - Analyze contract deployments for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Contract bytecode or `0x` if EOA | ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const address = '0x8894E0a0c962CB723c1976a4421c95949bE2D4E3'; const code = await provider.getCode(address); if (code === '0x') { console.log('Address is an EOA (externally owned account)'); } else { console.log('Address is a contract'); console.log('Bytecode length:', code.length); } // Check if address is a contract async function isContract(address) { const code = await provider.getCode(address); return code !== '0x'; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) address = '0x8894E0a0c962CB723c1976a4421c95949bE2D4E3' code = w3.eth.get_code(address) if code == b'': print('Address is an EOA') else: print('Address is a contract') print(f'Bytecode length: {len(code.hex())}') # Check if address is a contract def is_contract(address): code = w3.eth.get_code(address) return code != b'' ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0x8894E0a0c962CB723c1976a4421c95949bE2D4E3") code, err := client.CodeAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } if len(code) == 0 { fmt.Println("Address is an EOA") } else { fmt.Printf("Contract bytecode length: %d\n", len(code)) } } ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_getStorageAt`](./eth_getStorageAt) - Get contract storage --- ## eth_getFilterChanges - BSC RPC Method # eth_getFilterChanges Polling method for a filter on Binance Smart Chain, returns an array of logs since last poll. ## Use Cases - **Event streaming** - Get new events incrementally - **Real-time monitoring** - Track contract activity for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications - **Efficient indexing** - Process only new events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); // Poll loop async function pollFilter(filterId, interval = 2000) { while (true) { const changes = await provider.send('eth_getFilterChanges', [filterId]); if (changes.length > 0) { console.log('New events:', changes); } await new Promise(r => setTimeout(r, interval)); } } ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter --- ## eth_getFilterLogs - BSC RPC Method # eth_getFilterLogs Returns an array of all logs matching filter with given ID on Binance Smart Chain. ## Use Cases - **Historical queries** - Get all matching logs for a filter - **Full event history** - Retrieve complete event data for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const logs = await provider.send('eth_getFilterLogs', [filterId]); console.log('All matching logs:', logs.length); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_getLogs - BSC RPC Method # eth_getLogs Returns an array of all logs matching a given filter object on Binance Smart Chain. > **Why BSC?** Build on the third-largest blockchain by market cap with $12B+ TVL and 37%+ DEX market share with sub-$0.10 fees, 2.6M daily active users, full EVM compatibility, and direct Binance integration. ## Use Cases The `eth_getLogs` method is essential for: - **Event indexing** - Track contract events for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications - **Token transfers** - Monitor ERC20/ERC721 transfers - **DeFi analytics** - Track swaps, liquidity events, and more - **Notification systems** - Alert on specific on-chain events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block (default: `"latest"`) | | `toBlock` | `QUANTITY\|TAG` | No | Ending block (default: `"latest"`) | | `address` | `DATA\|Array` | No | Contract address(es) to filter | | `topics` | `Array` | No | Array of topic filters | | `blockHash` | `DATA` | No | Filter single block by hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns Array of log objects: | Field | Type | Description | |-------|------|-------------| | `address` | `DATA` | Contract that emitted the log | | `topics` | `Array` | Array of indexed topics | | `data` | `DATA` | Non-indexed log data | | `blockNumber` | `QUANTITY` | Block number | | `transactionHash` | `DATA` | Transaction hash | | `logIndex` | `QUANTITY` | Log index in block | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": [{ "address": "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."], "data": "0x...", "blockNumber": "0x5BAD55", "transactionHash": "0x...", "logIndex": "0x0" }] } ``` ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); // Get Transfer events const TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'; async function getTransferEvents(tokenAddress, fromBlock, toBlock) { const logs = await provider.getLogs({ address: tokenAddress, topics: [TRANSFER_TOPIC], fromBlock: fromBlock, toBlock: toBlock }); return logs.map(log => ({ from: '0x' + log.topics[1].slice(26), to: '0x' + log.topics[2].slice(26), blockNumber: log.blockNumber, transactionHash: log.transactionHash })); } const events = await getTransferEvents( '0x8894E0a0c962CB723c1976a4421c95949bE2D4E3', 'latest', 'latest' ); console.log('Transfer events:', events); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' def get_transfer_events(token_address, from_block, to_block): logs = w3.eth.get_logs({ 'address': token_address, 'topics': [TRANSFER_TOPIC], 'fromBlock': from_block, 'toBlock': to_block }) events = [] for log in logs: events.append({ 'from': '0x' + log['topics'][1].hex()[26:], 'to': '0x' + log['topics'][2].hex()[26:], 'block': log['blockNumber'], 'tx': log['transactionHash'].hex() }) return events events = get_transfer_events( '0x8894E0a0c962CB723c1976a4421c95949bE2D4E3', 'latest', 'latest' ) print(f'Found {len(events)} transfer events') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0x8894E0a0c962CB723c1976a4421c95949bE2D4E3") transferTopic := common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef") query := ethereum.FilterQuery{ FromBlock: big.NewInt(0), ToBlock: nil, Addresses: []common.Address{contractAddress}, Topics: [][]common.Hash, } logs, err := client.FilterLogs(context.Background(), query) if err != nil { log.Fatal(err) } fmt.Printf("Found %d events\n", len(logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32005 | Query returned more than 10000 results | Reduce block range | | -32602 | Invalid params | Invalid filter parameters | ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create a filter for logs - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for new logs --- ## eth_getStorageAt - BSC RPC Method # eth_getStorageAt Returns the value from a storage position at a given address on Binance Smart Chain. ## Use Cases - **Contract analysis** - Read raw storage values - **State verification** - Verify contract state - **Security auditing** - Analyze storage layout for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications - **Protocol monitoring** - Track state changes ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte contract address | | `position` | `QUANTITY` | Yes | Storage slot position | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "0x0", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "0x0", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const address = '0x8894E0a0c962CB723c1976a4421c95949bE2D4E3'; const slot = 0; const storage = await provider.getStorage(address, slot); console.log('Storage at slot 0:', storage); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) address = '0x8894E0a0c962CB723c1976a4421c95949bE2D4E3' storage = w3.eth.get_storage_at(address, 0) print(f'Storage at slot 0: {storage.hex()}') ``` ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_call`](./eth_call) - Call contract functions --- ## eth_getTransactionByHash - BSC RPC Method # eth_getTransactionByHash Returns the information about a transaction by transaction hash on Binance Smart Chain. > **Why BSC?** Build on the third-largest blockchain by market cap with $12B+ TVL and 37%+ DEX market share with sub-$0.10 fees, 2.6M daily active users, full EVM compatibility, and direct Binance integration. ## Use Cases The `eth_getTransactionByHash` method is essential for: - **Transaction tracking** - Get details of pending or confirmed transactions - **Payment verification** - Verify transaction parameters - **Debugging** - Analyze transaction data for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications - **Block explorers** - Display transaction information ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x15f20ca5615d94cc4685b9132ce7d5aafd5a4967197a2b3eec0bbbfef5eba10c"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `hash` | `DATA` | Transaction hash | | `from` | `DATA` | Sender address | | `to` | `DATA` | Recipient address | | `value` | `QUANTITY` | Value in wei | | `gas` | `QUANTITY` | Gas provided | | `gasPrice` | `QUANTITY` | Gas price in wei | | `input` | `DATA` | Transaction input data | | `nonce` | `QUANTITY` | Sender's nonce | | `blockHash` | `DATA` | Block hash (null if pending) | | `blockNumber` | `QUANTITY` | Block number (null if pending) | ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x15f20ca5615d94cc4685b9132ce7d5aafd5a4967197a2b3eec0bbbfef5eba10c"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x15f20ca5615d94cc4685b9132ce7d5aafd5a4967197a2b3eec0bbbfef5eba10c'; const tx = await provider.getTransaction(txHash); if (tx) { console.log('From:', tx.from); console.log('To:', tx.to); console.log('Value:', formatEther(tx.value)); console.log('Block:', tx.blockNumber); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x15f20ca5615d94cc4685b9132ce7d5aafd5a4967197a2b3eec0bbbfef5eba10c' tx = w3.eth.get_transaction(tx_hash) if tx: print(f'From: {tx["from"]}') print(f'To: {tx["to"]}') print(f'Value: {w3.from_wei(tx["value"], "ether")}') print(f'Block: {tx["blockNumber"]}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x15f20ca5615d94cc4685b9132ce7d5aafd5a4967197a2b3eec0bbbfef5eba10c") tx, isPending, err := client.TransactionByHash(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Pending: %v\n", isPending) fmt.Printf("Value: %s\n", tx.Value().String()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash format | ## Related Methods - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction receipt - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionCount - BSC RPC Method # eth_getTransactionCount Returns the number of transactions sent from an address on Binance Smart Chain (the nonce). ## Use Cases - **Transaction building** - Get correct nonce for new transactions - **Account analysis** - Count total outgoing transactions - **Nonce management** - Handle pending transaction queues - **Wallet operations** - Prepare transactions for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag (`pending` for next nonce) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const address = '0x8894E0a0c962CB723c1976a4421c95949bE2D4E3'; const nonce = await provider.getTransactionCount(address); console.log('Nonce:', nonce); // Get pending nonce for new transaction const pendingNonce = await provider.getTransactionCount(address, 'pending'); console.log('Next nonce:', pendingNonce); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) address = '0x8894E0a0c962CB723c1976a4421c95949bE2D4E3' nonce = w3.eth.get_transaction_count(address) print(f'Nonce: {nonce}') # Get pending nonce pending_nonce = w3.eth.get_transaction_count(address, 'pending') print(f'Next nonce: {pending_nonce}') ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionReceipt - BSC RPC Method # eth_getTransactionReceipt Returns the receipt of a transaction by transaction hash on Binance Smart Chain. Receipt is only available for mined transactions. > **Why BSC?** Build on the third-largest blockchain by market cap with $12B+ TVL and 37%+ DEX market share with sub-$0.10 fees, 2.6M daily active users, full EVM compatibility, and direct Binance integration. ## Use Cases The `eth_getTransactionReceipt` method is essential for: - **Transaction confirmation** - Verify transaction was mined successfully - **Gas analysis** - Check actual gas used vs estimated - **Event parsing** - Read emitted events from logs - **Status verification** - Confirm success/failure for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x15f20ca5615d94cc4685b9132ce7d5aafd5a4967197a2b3eec0bbbfef5eba10c"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `status` | `QUANTITY` | `1` (success) or `0` (failure) | | `transactionHash` | `DATA` | Transaction hash | | `blockHash` | `DATA` | Block hash | | `blockNumber` | `QUANTITY` | Block number | | `gasUsed` | `QUANTITY` | Gas used by this transaction | | `cumulativeGasUsed` | `QUANTITY` | Total gas used in block up to this tx | | `logs` | `Array` | Array of log objects | | `contractAddress` | `DATA` | Created contract address (if deployment) | ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x15f20ca5615d94cc4685b9132ce7d5aafd5a4967197a2b3eec0bbbfef5eba10c"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x15f20ca5615d94cc4685b9132ce7d5aafd5a4967197a2b3eec0bbbfef5eba10c'; const receipt = await provider.getTransactionReceipt(txHash); if (receipt) { console.log('Status:', receipt.status === 1 ? 'Success' : 'Failed'); console.log('Gas Used:', receipt.gasUsed.toString()); console.log('Block:', receipt.blockNumber); console.log('Logs:', receipt.logs.length); // Parse specific events for (const log of receipt.logs) { console.log('Event from:', log.address); } } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x15f20ca5615d94cc4685b9132ce7d5aafd5a4967197a2b3eec0bbbfef5eba10c' receipt = w3.eth.get_transaction_receipt(tx_hash) if receipt: status = 'Success' if receipt['status'] == 1 else 'Failed' print(f'Status: {status}') print(f'Gas Used: {receipt["gasUsed"]}') print(f'Block: {receipt["blockNumber"]}') print(f'Logs: {len(receipt["logs"])}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x15f20ca5615d94cc4685b9132ce7d5aafd5a4967197a2b3eec0bbbfef5eba10c") receipt, err := client.TransactionReceipt(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Status: %d\n", receipt.Status) fmt.Printf("Gas Used: %d\n", receipt.GasUsed) fmt.Printf("Logs: %d\n", len(receipt.Logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash | **Note**: Returns `null` if transaction is not yet mined. ## Related Methods - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details - [`eth_getLogs`](./eth_getLogs) - Query logs by filter --- ## eth_hashrate - Get node hashrate(Bsc) # eth_hashrate Get node hashrate on the Binance Smart Chain network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_hashrate](https://ethereum.org/developers/docs/apis/json-rpc/#eth_hashrate) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_hashrate", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_hashrate', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Binance Smart Chain documentation](/docs/bsc).* --- ## eth_maxPriorityFeePerGas - BSC RPC Method # eth_maxPriorityFeePerGas Returns the current recommended priority fee per gas on Binance Smart Chain for EIP-1559 transactions. ## Use Cases - **EIP-1559 transactions** - Set appropriate priority fees - **Transaction acceleration** - Calculate tips for faster inclusion - **Gas optimization** - Balance speed vs cost for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); console.log('Max Priority Fee:', formatUnits(feeData.maxPriorityFeePerGas, 'gwei'), 'Gwei'); console.log('Max Fee Per Gas:', formatUnits(feeData.maxFeePerGas, 'gwei'), 'Gwei'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) priority_fee = w3.eth.max_priority_fee print(f'Max Priority Fee: {w3.from_wei(priority_fee, "gwei")} Gwei') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get legacy gas price - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data --- ## eth_mining - Check if node is mi... # eth_mining Check if node is mining on the Binance Smart Chain network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_mining](https://ethereum.org/developers/docs/apis/json-rpc/#eth_mining) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_mining', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Binance Smart Chain documentation](/docs/bsc).* --- ## eth_newBlockFilter - BSC RPC Method # eth_newBlockFilter Creates a filter on Binance Smart Chain to notify when a new block arrives. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newBlockFilter', []); // Poll for new blocks const newBlocks = await provider.send('eth_getFilterChanges', [filterId]); console.log('New block hashes:', newBlocks); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_blockNumber`](./eth_blockNumber) - Get current block --- ## eth_newFilter - BSC RPC Method # eth_newFilter Creates a filter object on Binance Smart Chain to notify when state changes (logs). ## Use Cases - **Event monitoring** - Subscribe to contract events - **Real-time updates** - Track events for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications - **Indexing** - Build event indexes incrementally ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block | | `toBlock` | `QUANTITY\|TAG` | No | Ending block | | `address` | `DATA\|Array` | No | Contract address(es) | | `topics` | `Array` | No | Topic filters | ## Request ```json { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0x8894E0a0c962CB723c1976a4421c95949bE2D4E3" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); // Create filter const filterId = await provider.send('eth_newFilter', [{ fromBlock: 'latest', address: '0x8894E0a0c962CB723c1976a4421c95949bE2D4E3', topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'] }]); // Poll for changes const changes = await provider.send('eth_getFilterChanges', [filterId]); console.log('New events:', changes); // Cleanup await provider.send('eth_uninstallFilter', [filterId]); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for changes - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_newPendingTransactionFilter - BSC RPC Method # eth_newPendingTransactionFilter Creates a filter on Binance Smart Chain to notify when new pending transactions arrive. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newPendingTransactionFilter', []); // Poll for pending transactions const pendingTxs = await provider.send('eth_getFilterChanges', [filterId]); console.log('Pending transaction hashes:', pendingTxs); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_protocolVersion - Get protoc... # eth_protocolVersion Get protocol version on the Binance Smart Chain network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_protocolVersion](https://ethereum.org/developers/docs/apis/json-rpc/#eth_protocolversion) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_protocolVersion", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_protocolVersion', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Binance Smart Chain documentation](/docs/bsc).* --- ## eth_sendRawTransaction - BSC RPC Method # eth_sendRawTransaction Submits a pre-signed transaction for broadcast to Binance Smart Chain. > **Why BSC?** Build on the third-largest blockchain by market cap with $12B+ TVL and 37%+ DEX market share with sub-$0.10 fees, 2.6M daily active users, full EVM compatibility, and direct Binance integration. ## Use Cases The `eth_sendRawTransaction` method is essential for: - **Broadcasting transactions** - Submit signed transactions to the network - **Wallet operations** - Send native tokens and interact with contracts - **DeFi operations** - Execute swaps, provide liquidity for high-frequency DeFi (PancakeSwap), NFT marketplaces, and GameFi applications - **Batch operations** - Submit multiple transactions efficiently ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `signedTransactionData` | `DATA` | Yes | The signed transaction data (RLP encoded) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | 32-byte transaction hash | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c808504a817c80082520894..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const wallet = new Wallet('YOUR_PRIVATE_KEY', provider); // Send native tokens async function sendTransaction(to, value) { const tx = await wallet.sendTransaction({ to: to, value: parseEther(value) }); console.log('Transaction hash:', tx.hash); // Wait for confirmation const receipt = await tx.wait(); console.log('Confirmed in block:', receipt.blockNumber); return receipt; } // Send to contract async function sendContractTransaction(contract, method, args, value = '0') { const tx = await contract[method](...args, { value: parseEther(value) }); return await tx.wait(); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY')) def send_transaction(private_key, to, value_in_ether): account = w3.eth.account.from_key(private_key) # Build transaction tx = { 'nonce': w3.eth.get_transaction_count(account.address), 'to': to, 'value': w3.to_wei(value_in_ether, 'ether'), 'gas': 21000, 'gasPrice': w3.eth.gas_price, 'chainId': w3.eth.chain_id } # Sign transaction signed_tx = account.sign_transaction(tx) # Send transaction tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) print(f'Transaction hash: {tx_hash.hex()}') # Wait for confirmation receipt = w3.eth.wait_for_transaction_receipt(tx_hash) print(f'Confirmed in block: {receipt["blockNumber"]}') return receipt ``` ```go package main "context" "crypto/ecdsa" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY") if err != nil { log.Fatal(err) } publicKey := privateKey.Public() publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey) fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA) nonce, _ := client.PendingNonceAt(context.Background(), fromAddress) value := big.NewInt(1000000000000000000) gasLimit := uint64(21000) gasPrice, _ := client.SuggestGasPrice(context.Background()) toAddress := common.HexToAddress("0x8894E0a0c962CB723c1976a4421c95949bE2D4E3") tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil) chainID, _ := client.NetworkID(context.Background()) signedTx, _ := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey) err = client.SendTransaction(context.Background(), signedTx) if err != nil { log.Fatal(err) } fmt.Printf("Transaction hash: %s\n", signedTx.Hash().Hex()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Nonce too low | Transaction nonce already used | | -32000 | Insufficient funds | Account has insufficient balance | | -32000 | Gas too low | Gas limit insufficient | | -32000 | Replacement underpriced | Gas price too low for replacement | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas required - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction result --- ## eth_sendTransaction - Send trans... # eth_sendTransaction > **Important**: Dwellir's shared BNB Smart Chain endpoints do not manage user private keys. JSON-RPC nodes cannot unlock your account, so `eth_sendTransaction` calls will fail. Sign transactions client-side and broadcast them with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Why this method is disabled on shared nodes - [`eth_sendTransaction` requires the node to hold and unlock the `from` account's private key](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction). - Managed infrastructure providers disable it for security reasons rather than storing customer keys on shared servers (for example, [Infura explicitly blocks the method on shared endpoints](https://docs.infura.io/api/networks/ethereum/json-rpc-methods/eth_sendtransaction)). ## Recommended workflow 1. Build the raw transaction locally with your wallet or SDK. 2. Sign the payload client-side (hardware wallet, custodial service, or library). 3. Submit the signed hex string with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Example response from the shared endpoint ```bash curl -s -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"0x0000000000000000000000000000000000000000"}],"id":1}' ``` ```json {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"unknown account"}} ``` Need help? Contact our [support team](mailto:support@dwellir.com) or use the dedicated [`eth_sendRawTransaction`](./eth_sendRawTransaction) guide. --- ## eth_signTransaction - Sign trans... # eth_signTransaction Signs a transaction using an unlocked account on the node. **Important**: Most RPC providers don't support this method for security reasons, as it requires private keys to be stored on the server. ## Security Considerations - This method requires an unlocked account on the node - Private keys must be available to the RPC server - Most production RPC providers disable this method - Use client-side signing libraries instead for better security ## Parameters 1. `Object` - The transaction object: - `from`: `DATA`, 20 Bytes - The address the transaction is sent from - `to`: `DATA`, 20 Bytes - (optional) The address the transaction is directed to - `gas`: `QUANTITY` - (optional) Integer of the gas provided for the transaction execution - `gasPrice`: `QUANTITY` - (optional) Integer of the gasPrice used for each paid gas - `value`: `QUANTITY` - (optional) Integer of the value sent with this transaction - `data`: `DATA` - (optional) The compiled code of a contract OR the hash of the invoked method signature and encoded parameters ## Returns `DATA` - The signed transaction data, ready for transmission via `eth_sendRawTransaction`. ## Implementation Example ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_signTransaction", "params": [{ "from": "0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a", "nonce": "0x0" }], "id": 1 }' ``` ```javascript const response = await fetch('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_signTransaction', params: [{ from: '0x9b2055d370f73ec7d8a03e965129118dc8f5bf83', to: '0xd46e8dd67c5d32be8058bb8eb970870f07244567', gas: '0x76c0', gasPrice: '0x9184e72a000', value: '0x9184e72a' }], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0xf86c808504a817c8008276c094d46e8dd67c5d32be8058bb8eb970870f072445675849184e72a8001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804" } ``` **Note**: This method is typically not available on hosted RPC providers for security reasons. The response shows a signed transaction ready for broadcast. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Binance Smart Chain documentation](/docs/bsc).* --- ## eth_syncing - BSC RPC Method # eth_syncing Returns syncing status of Binance Smart Chain node. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 } ``` ## Returns Returns `false` if not syncing, or an object with sync status. ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const syncing = await provider.send('eth_syncing', []); if (syncing === false) { console.log('Node is fully synced'); } else { console.log('Syncing:', syncing); } ``` ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get current block - [`net_peerCount`](./net_peerCount) - Get peer count --- ## eth_uninstallFilter - BSC RPC Method # eth_uninstallFilter Uninstalls a filter on Binance Smart Chain. Should be called when no longer needed. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID to uninstall | ## Request ```json { "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if filter was found and uninstalled | ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const success = await provider.send('eth_uninstallFilter', [filterId]); console.log('Filter removed:', success); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter --- ## Binance Smart Chain - BNB Chain Documentation # Binance Smart Chain - Build on the BNB Ecosystem ## Why Build on Binance Smart Chain? Binance Smart Chain (BSC) is a fast, low-cost blockchain that runs parallel to Binance Chain, offering EVM compatibility and a thriving ecosystem: ### ⚡ **High Performance** - **3-second block times** - Fast transaction confirmations - **Low transaction costs** - Significantly cheaper than Ethereum - **High throughput** - Handles high transaction volumes efficiently ### 🏗️ **EVM Compatibility** - **Binance ecosystem** - Backed by world's largest crypto exchange - **Ethereum compatibility** - Deploy Ethereum dApps without changes - **Mature infrastructure** - Battle-tested with billions in TVL ### 🌐 **Vibrant Ecosystem** - **PancakeSwap** - Leading DEX with massive liquidity - **BNB token integration** - Native support for BNB ecosystem - **Cross-chain bridges** - Easy asset transfers from other chains ## Quick Start with Binance Smart Chain Connect to Binance Smart Chain in seconds with Dwellir's optimized endpoints: ### Installation & Setup ```javascript // Connect to BSC mainnet const provider = new JsonRpcProvider( 'https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY' ); // Get the latest block const block = await provider.getBlock('latest'); console.log('Latest block:', block.number); // Query account balance const balance = await provider.getBalance('0x...'); console.log('Balance:', balance.toString()); ``` ```javascript const Web3 = require('web3'); // Connect to BSC mainnet const web3 = new Web3( 'https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY' ); // Get chain ID to verify connection const chainId = await web3.eth.getChainId(); console.log('Connected to BSC:', chainId === 56); // Get gas price for optimal transaction pricing const gasPrice = await web3.eth.getGasPrice(); console.log('Current gas price:', gasPrice); ``` ```typescript // Create BSC client const client = createPublicClient({ chain: bsc, transport: http('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'), }); // Read contract data const data = await client.readContract({ address: '0x...', abi: contractAbi, functionName: 'balanceOf', args: ['0x...'], }); ``` ## Network Information Chain ID 56 Mainnet Block Time 3 seconds Average Gas Token BNB Native token RPC Standard Ethereum JSON-RPC 2.0 ## JSON-RPC API Reference Binance Smart Chain supports the full [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/) with EVM compatibility. Access all standard Ethereum methods on the BNB ecosystem. ## Common Integration Patterns ### 🔄 Transaction Monitoring Monitor pending and confirmed transactions efficiently on BSC: ```javascript // Watch for transaction confirmation async function waitForTransaction(txHash) { const receipt = await provider.waitForTransaction(txHash, 1); // BSC has fast 3-second block times console.log('Transaction confirmed in block:', receipt.blockNumber); console.log('Gas used:', receipt.gasUsed.toString()); return receipt; } ``` ### 💰 Gas Optimization Optimize gas costs on Binance Smart Chain: ```javascript // Estimate gas for BSC transaction const gasEstimate = await provider.estimateGas(tx); // Get current gas price (BSC uses standard gas pricing) const gasPrice = await provider.getGasPrice(); // Calculate total cost in BNB const totalCost = gasEstimate * gasPrice; console.log('Total cost in BNB:', formatEther(totalCost)); ``` ### 🔍 Event Filtering Efficiently query contract events on BSC: ```javascript // Query events with automatic retry and pagination async function getEvents(contract, eventName, fromBlock = 0) { const filter = contract.filters[eventName](); const events = []; const batchSize = 5000; // BSC can handle larger batch sizes for (let i = fromBlock; i <= currentBlock; i += batchSize) { const batch = await contract.queryFilter( filter, i, Math.min(i + batchSize - 1, currentBlock) ); events.push(...batch); return events; } ``` ## Performance Best Practices ### 1. **Batch Requests** Combine multiple RPC calls for optimal performance: ```javascript const batch = [ { method: 'eth_blockNumber', params: [] }, { method: 'eth_gasPrice', params: [] }, { method: 'eth_getBalance', params: [address, 'latest'] } ]; const results = await provider.send(batch); ``` ### 2. **Connection Pooling** Reuse provider instances to minimize connection overhead: ```javascript // Singleton pattern for provider class BSCProvider { static instance = null; static getInstance() { if (!this.instance) { this.instance = new JsonRpcProvider( 'https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY' ); } return this.instance; } } ``` ### 3. **Smart Caching** Cache immutable data to reduce API calls: ```javascript const cache = new Map(); async function getCachedBlockData(blockNumber) { const key = `block_${blockNumber}`; if (!cache.has(key)) { const block = await provider.getBlock(blockNumber); cache.set(key, block); } return cache.get(key); } ``` ## Troubleshooting Common Issues ### Error: "Insufficient funds" BSC transactions require BNB for gas fees: ```javascript // Check BNB balance for gas fees const balance = await provider.getBalance(address); const gasEstimate = await provider.estimateGas(tx); const gasPrice = await provider.getGasPrice(); const totalRequired = gasEstimate * gasPrice + tx.value; if (balance < totalRequired) { const needed = formatEther(totalRequired - balance); throw new Error(`Need ${needed} more BNB`); } ``` ### Error: "Transaction underpriced" BSC uses legacy gas pricing. Use current gas price: ```javascript // Get current gas price const gasPrice = await provider.getGasPrice(); const tx = { to: recipient, value: amount, gasPrice: gasPrice, gasLimit: 21000n, type: 0 // Legacy transaction type }; ``` ### Error: "Rate limit exceeded" Implement exponential backoff for resilient applications: ```javascript async function callWithRetry(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error.code === 429 && i < maxRetries - 1) { await new Promise(r => setTimeout(r, 2 ** i * 1000)); } else { throw error; } } } } ``` ## Migration Guide ### From Ethereum Mainnet Moving from Ethereum to Binance Smart Chain requires minimal changes: ```javascript // Before (Ethereum) const provider = new JsonRpcProvider('https://eth-rpc.example.com'); // After (BSC) const provider = new JsonRpcProvider( 'https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY' ); // ✅ Smart contracts work identically // ✅ Same tooling and libraries // ⚠️ Different chain ID (56) // ⚠️ Separate block numbers // ⚠️ Different gas token (BNB instead of ETH) // ⚠️ Legacy gas pricing (no EIP-1559) ``` ## Resources & Tools ### Official Resources - [BSC Documentation](https://docs.bnbchain.org/) - [BSC Bridge](https://www.bnbchain.org/en/bridge) - [BscScan Block Explorer](https://bscscan.com/) ### Developer Tools - [Developer Tools](https://docs.bnbchain.org/) - [Remix IDE](https://remix.ethereum.org/) ### Need Help? - 📧 **Email**: support@dwellir.com - 📚 **Docs**: You're here! - 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com) --- *Start building on Binance Smart Chain with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)* --- ## net_listening - BSC RPC Method # net_listening Returns `true` if client is actively listening for network connections on Binance Smart Chain. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if listening | ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const listening = await provider.send('net_listening', []); console.log('Node listening:', listening); ``` ## Related Methods - [`net_peerCount`](./net_peerCount) - Get peer count --- ## net_peerCount - BSC RPC Method # net_peerCount Returns number of peers currently connected to Binance Smart Chain client. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Number of connected peers (hexadecimal) | ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const peerCount = await provider.send('net_peerCount', []); console.log('Peer count:', parseInt(peerCount, 16)); ``` ## Related Methods - [`net_listening`](./net_listening) - Check if listening --- ## net_version - BSC RPC Method # net_version Returns the current network ID on Binance Smart Chain. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Network ID as a string | ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const networkId = await provider.send('net_version', []); console.log('Network ID:', networkId); ``` ## Related Methods - [`eth_chainId`](./eth_chainId) - Get chain ID --- ## web3_clientVersion - BSC RPC Method # web3_clientVersion Returns the current client version on Binance Smart Chain. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Client version string | ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); const version = await provider.send('web3_clientVersion', []); console.log('Client version:', version); ``` --- ## web3_sha3 - BSC RPC Method # web3_sha3 Returns Keccak-256 (not standard SHA3-256) of the given data on Binance Smart Chain. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `data` | `DATA` | Yes | Data to hash | ## Request ```json { "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Keccak-256 hash of the data | ## Code Examples ```bash curl -X POST https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-bsc-mainnet-full.n.dwellir.com/YOUR_API_KEY'); // Using RPC const hash = await provider.send('web3_sha3', ['0x68656c6c6f']); console.log('Hash:', hash); // Using ethers directly (faster) const localHash = keccak256(toUtf8Bytes('hello')); console.log('Local hash:', localHash); ``` --- ## debug_traceBlock - Celo RPC Method # debug_traceBlock Traces all transactions in a block on Celo by block RLP. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Analyze transaction execution step-by-step - **Smart contract analysis** - Debug contract interactions - **Security auditing** - Trace internal calls for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockRlp` | `DATA` | Yes | RLP-encoded block data | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Use debug_traceBlockByNumber instead (more practical) const traces = await provider.send('debug_traceBlockByNumber', ['latest', {}]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by block number - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by block hash --- ## debug_traceBlockByHash - Celo RPC Method # debug_traceBlockByHash Traces all transactions in a block on Celo by block hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0x37e4542c2bba6522a2dde06f9b0c584520f113e794a10636a8f00f195c74ec16", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0x37e4542c2bba6522a2dde06f9b0c584520f113e794a10636a8f00f195c74ec16", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0x37e4542c2bba6522a2dde06f9b0c584520f113e794a10636a8f00f195c74ec16'; const traces = await provider.send('debug_traceBlockByHash', [blockHash, { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by number - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceBlockByNumber - Celo RPC Method # debug_traceBlockByNumber Traces all transactions in a block on Celo by block number. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('debug_traceBlockByNumber', ['latest', { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by hash - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceCall - Celo RPC Method # debug_traceCall Traces a call without creating a transaction on Celo. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction simulation** - Debug before sending - **Gas analysis** - Analyze gas usage per opcode - **Contract debugging** - Step through execution for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `call` | `Object` | Yes | Call object (same as eth_call) | | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ { "to": "0x471EcE3750Da237f93B8E339c536989b8978a438", "data": "0x70a08231000000000000000000000000471EcE3750Da237f93B8E339c536989b8978a438" }, "latest", {} ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ {"to": "0x471EcE3750Da237f93B8E339c536989b8978a438", "data": "0x70a08231000000000000000000000000471EcE3750Da237f93B8E339c536989b8978a438"}, "latest", {"tracer": "callTracer"} ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const trace = await provider.send('debug_traceCall', [ { to: '0x471EcE3750Da237f93B8E339c536989b8978a438', data: '0x70a08231000000000000000000000000471EcE3750Da237f93B8E339c536989b8978a438' }, 'latest', { tracer: 'callTracer' } ]); console.log('Trace:', trace); ``` ## Related Methods - [`eth_call`](./eth_call) - Execute call without trace - [`debug_traceTransaction`](./debug_traceTransaction) - Trace actual transaction --- ## debug_traceTransaction - Celo RPC Method # debug_traceTransaction Traces a transaction execution on Celo by transaction hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Understand exactly what happened - **Failure analysis** - Find where and why a transaction reverted - **Gas optimization** - Analyze gas usage for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Tracer Options - `{}` - Default opcode tracer (verbose) - `{ tracer: "callTracer" }` - Call tree tracer - `{ tracer: "prestateTracer" }` - Pre-state tracer ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x69d8e9317be809224e01515be6cf3d0716e92b340a680832c45e5e668ff05abe", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x69d8e9317be809224e01515be6cf3d0716e92b340a680832c45e5e668ff05abe", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x69d8e9317be809224e01515be6cf3d0716e92b340a680832c45e5e668ff05abe'; // Call tracer - shows internal calls const callTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'callTracer' } ]); console.log('Type:', callTrace.type); console.log('From:', callTrace.from); console.log('To:', callTrace.to); console.log('Gas used:', parseInt(callTrace.gasUsed, 16)); // Prestate tracer - shows state before execution const prestateTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'prestateTracer' } ]); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x69d8e9317be809224e01515be6cf3d0716e92b340a680832c45e5e668ff05abe' # Call tracer trace = w3.provider.make_request('debug_traceTransaction', [ tx_hash, {'tracer': 'callTracer'} ]) print(f'Trace type: {trace["result"]["type"]}') print(f'Gas used: {int(trace["result"]["gasUsed"], 16)}') ``` ## Related Methods - [`debug_traceCall`](./debug_traceCall) - Trace without executing - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace entire block --- ## eth_accounts - Celo RPC Method # eth_accounts Returns a list of addresses owned by the client on Celo. > **Why Celo?** Build on the mobile-first L2 powering 500K+ daily active users and $2B+ monthly stablecoin volume with phone number-based addressing, sub-cent fees, 150+ country adoption, Nightfall privacy layer, and Opera browser integration. ## Important Note On public RPC endpoints like Dwellir, `eth_accounts` returns an empty array because the node does not hold any private keys. This method is primarily useful for: - Local development nodes (Ganache, Hardhat, Anvil) - Private nodes with managed accounts - Wallet provider connections (MetaMask injects accounts) ## When to Use This Method `eth_accounts` is relevant for mobile payment developers, fintech builders, and teams targeting emerging markets in specific scenarios: - **Development Testing** — Retrieve test accounts from local nodes - **Wallet Detection** — Check if a wallet provider has connected accounts - **Client Verification** — Confirm node account access capabilities ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `Array` | List of 20-byte account addresses owned by the client | **Return format**: Array of `0x` prefixed hexadecimal addresses (typically empty for public nodes) ## Request ```json { "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 } ``` ## Response ### Successful Response (Public Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [] } ``` ### Successful Response (Local Development Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [ "0x407d73d8a49eeb85d32cf465507dd71d507100c1", "0x85d32cf465507dd71d507100c1407d73d8a49eeb" ] } ``` ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_accounts', params: [], id: 1 }) }); const { result } = await response.json(); console.log('Accounts:', result); // Using ethers.js const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const accounts = await provider.listAccounts(); console.log('Accounts:', accounts); ``` ```python def get_accounts(): response = requests.post( 'https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_accounts', 'params': [], 'id': 1 } ) return response.json()['result'] accounts = get_accounts() print(f'Accounts: {accounts}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) print(f'Accounts: {w3.eth.accounts}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/rpc" ) func main() { client, err := rpc.Dial("https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } var accounts []string err = client.CallContext(context.Background(), &accounts, "eth_accounts") if err != nil { log.Fatal(err) } fmt.Printf("Accounts: %v\n", accounts) } ``` ## Common Use Cases ### 1. Development Environment Detection Check if running against a development node with test accounts: ```javascript async function isDevEnvironment(provider) { const accounts = await provider.listAccounts(); return accounts.length > 0; } const isDev = await isDevEnvironment(provider); if (isDev) { console.log('Development environment detected'); } ``` ### 2. Wallet Connection Check Verify wallet provider has connected accounts: ```javascript async function checkWalletConnection() { if (typeof window.ethereum === 'undefined') { return { connected: false, reason: 'No wallet detected' }; } const accounts = await window.ethereum.request({ method: 'eth_accounts' }); return { connected: accounts.length > 0, accounts: accounts }; } ``` ### 3. Fallback Account Selection Use first available account or request connection: ```javascript async function getActiveAccount() { // Check existing connections let accounts = await window.ethereum.request({ method: 'eth_accounts' }); // Request connection if no accounts if (accounts.length === 0) { accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); } return accounts[0] || null; } ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32601 | Method not found | Node may not support this method | | -32603 | Internal error | Retry with exponential backoff | ```javascript async function safeGetAccounts(provider) { try { const accounts = await provider.listAccounts(); return { success: true, accounts }; } catch (error) { if (error.code === -32601) { console.warn('eth_accounts not supported on this node'); return { success: false, accounts: [], reason: 'unsupported' }; } throw error; } } ``` ## Related Methods - [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102) — Request wallet connection (browser wallets) - [`eth_getBalance`](./eth_getBalance) — Get account balance - [`eth_getTransactionCount`](./eth_getTransactionCount) — Get account nonce --- ## eth_blockNumber - Celo RPC Method # eth_blockNumber Returns the number of the most recent block on Celo. > **Why Celo?** Build on the mobile-first L2 powering 500K+ daily active users and $2B+ monthly stablecoin volume with phone number-based addressing, sub-cent fees, 150+ country adoption, Nightfall privacy layer, and Opera browser integration. ## When to Use This Method `eth_blockNumber` is fundamental for mobile payment developers, fintech builders, and teams targeting emerging markets: - **Syncing Applications** — Keep your dApp in sync with the latest Celo blockchain state - **Transaction Monitoring** — Verify confirmations by comparing block numbers - **Event Filtering** — Set the correct block range for querying logs on mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) - **Health Checks** — Monitor node connectivity and sync status ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `QUANTITY` | Hexadecimal string representing the current block number | **Return format**: `0x` prefixed hexadecimal (e.g., `0x5BAD55` = 6,008,149 in decimal) ## Request ```json { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } ``` ## Response ### Successful Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5BAD55" } ``` ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error" } } ``` ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }) }); const { result } = await response.json(); const blockNumber = parseInt(result, 16); console.log('Celo block:', blockNumber); // Using ethers.js const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockNumber = await provider.getBlockNumber(); console.log('Celo block:', blockNumber); ``` ```python def get_block_number(): response = requests.post( 'https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_blockNumber', 'params': [], 'id': 1 } ) result = response.json()['result'] return int(result, 16) block_number = get_block_number() print(f'Celo block: {block_number}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) print(f'Celo block: {w3.eth.block_number}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockNumber, err := client.BlockNumber(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Celo block: %d\n", blockNumber) } ``` ## Common Use Cases ### 1. Block Confirmation Counter Monitor transaction confirmations on Celo: ```javascript async function getConfirmations(provider, txHash) { const tx = await provider.getTransaction(txHash); if (!tx || !tx.blockNumber) return 0; const currentBlock = await provider.getBlockNumber(); return currentBlock - tx.blockNumber + 1; } // Wait for specific confirmations async function waitForConfirmations(provider, txHash, confirmations = 6) { let currentConfirmations = 0; while (currentConfirmations < confirmations) { currentConfirmations = await getConfirmations(provider, txHash); console.log(`Confirmations: ${currentConfirmations}/${confirmations}`); await new Promise(r => setTimeout(r, 2000)); } return true; } ``` ### 2. Event Log Filtering Query events from recent blocks on Celo: ```javascript async function getRecentEvents(provider, contract, eventName, blockRange = 100) { const currentBlock = await provider.getBlockNumber(); const fromBlock = currentBlock - blockRange; const filter = contract.filters[eventName](); const events = await contract.queryFilter(filter, fromBlock, currentBlock); return events; } ``` ### 3. Node Health Monitoring Check if your Celo node is synced: ```javascript async function checkNodeHealth(provider) { try { const blockNumber = await provider.getBlockNumber(); const block = await provider.getBlock(blockNumber); const now = Date.now() / 1000; const blockAge = now - block.timestamp; if (blockAge > 60) { console.warn(`Node may be behind. Last block was ${blockAge}s ago`); return false; } console.log(`Node healthy. Latest block: ${blockNumber}`); return true; } catch (error) { console.error('Node unreachable:', error); return false; } } ``` ## Performance Optimization ### Caching Strategy Cache block numbers to reduce API calls: ```javascript class BlockNumberCache { constructor(ttl = 2000) { this.cache = null; this.timestamp = 0; this.ttl = ttl; } async get(provider) { const now = Date.now(); if (this.cache && (now - this.timestamp) < this.ttl) { return this.cache; } this.cache = await provider.getBlockNumber(); this.timestamp = now; return this.cache; } invalidate() { this.cache = null; this.timestamp = 0; } } const blockCache = new BlockNumberCache(); ``` ### Batch Requests Combine with other calls for efficiency: ```javascript const batch = [ { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }, { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 }, { jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 } ]; const response = await fetch('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await response.json(); ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32603 | Internal error | Retry with exponential backoff | | -32005 | Rate limit exceeded | Implement rate limiting client-side | | -32000 | Execution reverted | Check node sync status | ```javascript async function safeGetBlockNumber(provider, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await provider.getBlockNumber(); } catch (error) { if (error.code === -32005) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } else if (i === maxRetries - 1) { throw error; } } } } ``` ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) — Get full block details by number - [`eth_getBlockByHash`](./eth_getBlockByHash) — Get block details by hash - [`eth_syncing`](./eth_syncing) — Check if node is still syncing --- ## eth_call - Celo RPC Method # eth_call Executes a new message call immediately without creating a transaction on Celo. Used for reading smart contract state. > **Why Celo?** Build on the mobile-first L2 powering 500K+ daily active users and $2B+ monthly stablecoin volume with phone number-based addressing, sub-cent fees, 150+ country adoption, Nightfall privacy layer, and Opera browser integration. ## Use Cases The `eth_call` method is essential for: - **Reading contract state** - Query view/pure functions - **Simulating transactions** - Test execution without gas costs - **DeFi integrations** - Check prices, balances, allowances for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) - **Complex queries** - Execute multi-step contract logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | 20-byte address executing the call | | `to` | `DATA` | Yes | 20-byte contract address | | `gas` | `QUANTITY` | No | Gas limit for the call | | `gasPrice` | `QUANTITY` | No | Gas price in wei | | `value` | `QUANTITY` | No | Value to send in wei | | `data` | `DATA` | Yes | Encoded function call data | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_call", "params": [ { "to": "0x471EcE3750Da237f93B8E339c536989b8978a438", "data": "0x70a08231000000000000000000000000471EcE3750Da237f93B8E339c536989b8978a438" }, "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | The return value of the executed contract function | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000" } ``` ## Code Examples ```bash # Call ERC20 balanceOf function curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{ "to": "0x471EcE3750Da237f93B8E339c536989b8978a438", "data": "0x70a08231000000000000000000000000471EcE3750Da237f93B8E339c536989b8978a438" }, "latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // ERC20 ABI for common functions const ERC20_ABI = [ "function balanceOf(address owner) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function totalSupply() view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)" ]; // Read ERC20 token balance async function getTokenBalance(tokenAddress, walletAddress) { const contract = new Contract(tokenAddress, ERC20_ABI, provider); const balance = await contract.balanceOf(walletAddress); const decimals = await contract.decimals(); const symbol = await contract.symbol(); return { raw: balance.toString(), formatted: (Number(balance) / Math.pow(10, decimals)).toFixed(4), symbol: symbol }; } // Direct eth_call async function directCall(to, data) { const result = await provider.call({ to, data }); return result; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) def get_erc20_balance(token_address, wallet_address): # balanceOf(address) selector function_signature = "balanceOf(address)" function_selector = w3.keccak(text=function_signature)[:4].hex() # Encode address parameter encoded_address = wallet_address[2:].lower().zfill(64) data = function_selector + encoded_address # Make the call result = w3.eth.call({ 'to': token_address, 'data': data }) return int(result.hex(), 16) balance = get_erc20_balance( '0x471EcE3750Da237f93B8E339c536989b8978a438', '0x471EcE3750Da237f93B8E339c536989b8978a438' ) print(f'Balance: {balance}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0x471EcE3750Da237f93B8E339c536989b8978a438") data := common.FromHex("0x70a08231000000000000000000000000471EcE3750Da237f93B8E339c536989b8978a438") msg := ethereum.CallMsg{ To: &contractAddress, Data: data, } result, err := client.CallContract(context.Background(), msg, nil) if err != nil { log.Fatal(err) } fmt.Printf("Result: 0x%x\n", result) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Contract function reverted | | -32602 | Invalid parameters | Invalid data encoding | | -32015 | VM execution error | Contract logic error | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas for transaction - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send actual transaction --- ## eth_chainId - Celo RPC Method # eth_chainId Returns the chain ID used for transaction signing on Celo. > **Why Celo?** Build on the mobile-first L2 powering 500K+ daily active users and $2B+ monthly stablecoin volume with phone number-based addressing, sub-cent fees, 150+ country adoption, Nightfall privacy layer, and Opera browser integration. ## Use Cases The `eth_chainId` method is essential for: - **Transaction signing** - Ensure transactions are signed for the correct network - **Network verification** - Confirm connection to the expected chain - **Multi-chain apps** - Handle different networks programmatically - **Wallet integration** - Validate network before transactions ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Chain ID in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1" } ``` ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const network = await provider.getNetwork(); console.log('Chain ID:', network.chainId); // Verify network before transaction async function verifyNetwork(expectedChainId) { const network = await provider.getNetwork(); if (network.chainId !== BigInt(expectedChainId)) { throw new Error(`Wrong network. Expected ${expectedChainId}, got ${network.chainId}`); } return true; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) chain_id = w3.eth.chain_id print(f'Chain ID: {chain_id}') # Verify network def verify_network(expected_chain_id): chain_id = w3.eth.chain_id if chain_id != expected_chain_id: raise ValueError(f'Wrong network. Expected {expected_chain_id}, got {chain_id}') return True ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } chainID, err := client.ChainID(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Chain ID: %d\n", chainID) } ``` ## Related Methods - [`net_version`](./net_version) - Get network version - [`eth_syncing`](./eth_syncing) - Check sync status --- ## eth_coinbase - Get coinbase address(Celo) # eth_coinbase Get coinbase address on the Celo network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_coinbase](https://ethereum.org/developers/docs/apis/json-rpc/#eth_coinbase) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_coinbase", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_coinbase', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Celo documentation](/docs/celo).* --- ## eth_estimateGas - Celo RPC Method # eth_estimateGas Estimates the gas necessary to execute a transaction on Celo. > **Why Celo?** Build on the mobile-first L2 powering 500K+ daily active users and $2B+ monthly stablecoin volume with phone number-based addressing, sub-cent fees, 150+ country adoption, Nightfall privacy layer, and Opera browser integration. ## Use Cases The `eth_estimateGas` method is essential for: - **Transaction preparation** - Set appropriate gas limits - **Cost estimation** - Calculate transaction costs before sending - **Error detection** - Identify reverts before spending gas - **DeFi operations** - Estimate costs for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | Sender address | | `to` | `DATA` | No | Recipient address | | `gas` | `QUANTITY` | No | Gas limit | | `gasPrice` | `QUANTITY` | No | Gas price | | `value` | `QUANTITY` | No | Value in wei | | `data` | `DATA` | No | Transaction data | ## Request ```json { "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0x471EcE3750Da237f93B8E339c536989b8978a438", "to": "0x471EcE3750Da237f93B8E339c536989b8978a438", "value": "0x1" }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Estimated gas amount in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5208" } ``` **Note**: `0x5208` = 21000 gas (standard ETH transfer) ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0x471EcE3750Da237f93B8E339c536989b8978a438", "to": "0x471EcE3750Da237f93B8E339c536989b8978a438", "value": "0x1" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Estimate simple transfer async function estimateTransfer(to, value) { const gasEstimate = await provider.estimateGas({ to: to, value: parseEther(value) }); console.log('Estimated gas:', gasEstimate.toString()); return gasEstimate; } // Estimate contract call async function estimateContractCall(contract, method, args) { const gasEstimate = await contract[method].estimateGas(...args); console.log('Estimated gas:', gasEstimate.toString()); // Add 20% buffer for safety return gasEstimate * 120n / 100n; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) def estimate_transfer(to, value_in_ether): gas_estimate = w3.eth.estimate_gas({ 'to': to, 'value': w3.to_wei(value_in_ether, 'ether') }) print(f'Estimated gas: {gas_estimate}') return gas_estimate def estimate_contract_call(contract, method, args): func = getattr(contract.functions, method) gas_estimate = func(*args).estimate_gas() # Add 20% buffer return int(gas_estimate * 1.2) # Estimate simple transfer gas = estimate_transfer('0x471EcE3750Da237f93B8E339c536989b8978a438', 0.1) ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } toAddress := common.HexToAddress("0x471EcE3750Da237f93B8E339c536989b8978a438") msg := ethereum.CallMsg{ To: &toAddress, Value: big.NewInt(1000000000000000000), } gasLimit, err := client.EstimateGas(context.Background(), msg) if err != nil { log.Fatal(err) } fmt.Printf("Estimated gas: %d\n", gasLimit) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Transaction would fail | | -32602 | Invalid params | Invalid transaction parameters | **Tip**: If estimation fails, the transaction would likely revert if sent. ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_feeHistory - Celo RPC Method # eth_feeHistory Returns historical gas information on Celo for fee estimation. ## Use Cases - **Fee prediction** - Estimate future gas prices based on history - **Gas analytics** - Analyze fee trends over time - **Optimal timing** - Find best times for transactions on mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockCount` | `QUANTITY` | Yes | Number of blocks in the range | | `newestBlock` | `QUANTITY\|TAG` | Yes | Highest block of the range | | `rewardPercentiles` | `Array` | Yes | Percentiles to sample for priority fees | ## Request ```json { "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const feeHistory = await provider.send('eth_feeHistory', ['0xa', 'latest', [25, 50, 75]]); console.log('Base fees:', feeHistory.baseFeePerGas.map(f => formatUnits(f, 'gwei'))); console.log('Reward (25th percentile):', feeHistory.reward.map(r => formatUnits(r[0], 'gwei'))); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) fee_history = w3.eth.fee_history(10, 'latest', [25, 50, 75]) print(f'Base fees: {[w3.from_wei(f, "gwei") for f in fee_history["baseFeePerGas"]]}') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee --- ## eth_gasPrice - Celo RPC Method # eth_gasPrice Returns the current gas price on Celo in wei. > **Why Celo?** Build on the mobile-first L2 powering 500K+ daily active users and $2B+ monthly stablecoin volume with phone number-based addressing, sub-cent fees, 150+ country adoption, Nightfall privacy layer, and Opera browser integration. ## Use Cases The `eth_gasPrice` method is essential for: - **Transaction pricing** - Set appropriate gas prices - **Cost estimation** - Calculate transaction costs before sending - **Gas monitoring** - Track network congestion - **DeFi operations** - Optimize costs for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Current gas price in wei (hexadecimal) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x3b9aca00" } ``` **Note**: `0x3b9aca00` = 1 Gwei (1,000,000,000 wei) ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); const gasPrice = feeData.gasPrice; console.log('Gas Price:', formatUnits(gasPrice, 'gwei'), 'Gwei'); // Calculate transaction cost async function estimateTransactionCost(gasLimit) { const feeData = await provider.getFeeData(); const cost = feeData.gasPrice * BigInt(gasLimit); return formatUnits(cost, 'ether'); } const cost = await estimateTransactionCost(21000); console.log('Transfer cost:', cost, 'ETH'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) gas_price = w3.eth.gas_price print(f'Gas Price: {w3.from_wei(gas_price, "gwei")} Gwei') # Calculate transaction cost def estimate_transaction_cost(gas_limit): gas_price = w3.eth.gas_price cost = gas_price * gas_limit return w3.from_wei(cost, 'ether') cost = estimate_transaction_cost(21000) print(f'Transfer cost: {cost} ETH') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } gasPrice, err := client.SuggestGasPrice(context.Background()) if err != nil { log.Fatal(err) } // Convert to Gwei gwei := new(big.Float).Quo( new(big.Float).SetInt(gasPrice), big.NewFloat(1e9), ) fmt.Printf("Gas Price: %f Gwei\n", gwei) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32603 | Internal error | Node error | ## Related Methods - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee (EIP-1559) - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas needed --- ## eth_getBalance - Celo RPC Method # eth_getBalance Returns the balance of a given address on Celo. > **Why Celo?** Build on the mobile-first L2 powering 500K+ daily active users and $2B+ monthly stablecoin volume with phone number-based addressing, sub-cent fees, 150+ country adoption, Nightfall privacy layer, and Opera browser integration. ## Use Cases The `eth_getBalance` method is essential for: - **Wallet applications** - Display user balances - **Transaction validation** - Check if account has sufficient funds - **DeFi applications** - Monitor collateral and liquidity for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) - **Account monitoring** - Track balance changes over time ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address to check balance for | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0x471EcE3750Da237f93B8E339c536989b8978a438", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Integer of the current balance in wei (hexadecimal) | **Note**: 1 native token = 10^18 wei. Convert using `balance / 10^18`. ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1a055690d9db80000" } ``` ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0x471EcE3750Da237f93B8E339c536989b8978a438", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x471EcE3750Da237f93B8E339c536989b8978a438'; const balanceWei = await provider.getBalance(address); const balance = formatEther(balanceWei); console.log(`Balance: ${balance}`); // Get balance at specific block const historicalBalance = await provider.getBalance(address, 1000000); console.log(`Historical balance: ${formatEther(historicalBalance)}`); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x471EcE3750Da237f93B8E339c536989b8978a438' balance_wei = w3.eth.get_balance(address) balance = w3.from_wei(balance_wei, 'ether') print(f'Balance: {balance}') # Get balance at specific block historical_balance = w3.eth.get_balance(address, block_identifier=1000000) print(f'Historical balance: {w3.from_wei(historical_balance, "ether")}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0x471EcE3750Da237f93B8E339c536989b8978a438") balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } // Convert to ether fbalance := new(big.Float).SetInt(balance) ethValue := new(big.Float).Quo(fbalance, big.NewFloat(1e18)) fmt.Printf("Balance: %f\n", ethValue) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid address format or block parameter | | -32000 | Execution error | Node execution error | ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_getTransactionCount`](./eth_getTransactionCount) - Get account nonce --- ## eth_getBlockByHash - Celo RPC Method # eth_getBlockByHash Returns information about a block by hash on Celo. > **Why Celo?** Build on the mobile-first L2 powering 500K+ daily active users and $2B+ monthly stablecoin volume with phone number-based addressing, sub-cent fees, 150+ country adoption, Nightfall privacy layer, and Opera browser integration. ## Use Cases The `eth_getBlockByHash` method is essential for: - **Block verification** - Verify block data using its unique hash - **Chain reorganization handling** - Track blocks during reorgs - **Cross-chain bridges** - Verify block finality for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) - **Deterministic queries** - Get consistent block data regardless of chain state ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0x37e4542c2bba6522a2dde06f9b0c584520f113e794a10636a8f00f195c74ec16", false ], "id": 1 } ``` ## Returns Returns the same block object as `eth_getBlockByNumber`, or `null` if no block is found. | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used | | `transactions` | `Array` | Transaction objects or hashes | ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0x37e4542c2bba6522a2dde06f9b0c584520f113e794a10636a8f00f195c74ec16", false ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0x37e4542c2bba6522a2dde06f9b0c584520f113e794a10636a8f00f195c74ec16'; const block = await provider.getBlock(blockHash); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) block_hash = '0x37e4542c2bba6522a2dde06f9b0c584520f113e794a10636a8f00f195c74ec16' block = w3.eth.get_block(block_hash) print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockHash := common.HexToHash("0x37e4542c2bba6522a2dde06f9b0c584520f113e794a10636a8f00f195c74ec16") block, err := client.BlockByHash(context.Background(), blockHash) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block hash format | | -32000 | Block not found | Block with this hash does not exist | ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) - Get block by number - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number --- ## eth_getBlockByNumber - Celo RPC Method # eth_getBlockByNumber Returns information about a block by block number on Celo. > **Why Celo?** Build on the mobile-first L2 powering 500K+ daily active users and $2B+ monthly stablecoin volume with phone number-based addressing, sub-cent fees, 150+ country adoption, Nightfall privacy layer, and Opera browser integration. ## Use Cases The `eth_getBlockByNumber` method is essential for: - **Block explorers** - Display complete block information - **Transaction indexers** - Process all transactions in a block - **Analytics platforms** - Analyze blockchain data for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) - **Timestamp verification** - Get block timestamps for time-based logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used by all transactions | | `gasLimit` | `QUANTITY` | Maximum gas allowed in block | | `transactions` | `Array` | Array of transaction objects or hashes | | `baseFeePerGas` | `QUANTITY` | Base fee per gas (EIP-1559) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": { "number": "0x5BAD55", "hash": "0x37e4542c2bba6522a2dde06f9b0c584520f113e794a10636a8f00f195c74ec16", "parentHash": "0x...", "timestamp": "0x64d8f6d0", "gasUsed": "0x1234", "gasLimit": "0x1c9c380", "transactions": [], "baseFeePerGas": "0x5f5e100" } } ``` ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Get latest block const block = await provider.getBlock('latest'); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); console.log('Transactions:', block.transactions.length); // Get block with full transactions const blockWithTxs = await provider.getBlock('latest', true); for (const tx of blockWithTxs.prefetchedTransactions) { console.log('Transaction:', tx.hash); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) # Get latest block block = w3.eth.get_block('latest') print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') print(f'Transactions: {len(block.transactions)}') # Get block with full transactions block_full = w3.eth.get_block('latest', full_transactions=True) for tx in block_full.transactions: print(f'Transaction: {tx.hash.hex()}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } // Get latest block block, err := client.BlockByNumber(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) fmt.Printf("Timestamp: %d\n", block.Time()) fmt.Printf("Transactions: %d\n", len(block.Transactions())) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block number or parameter format | | -32000 | Block not found | Block does not exist | ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number - [`eth_getBlockByHash`](./eth_getBlockByHash) - Get block by hash - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_getCode - Celo RPC Method # eth_getCode Returns the bytecode at a given address on Celo. > **Why Celo?** Build on the mobile-first L2 powering 500K+ daily active users and $2B+ monthly stablecoin volume with phone number-based addressing, sub-cent fees, 150+ country adoption, Nightfall privacy layer, and Opera browser integration. ## Use Cases The `eth_getCode` method is essential for: - **Contract verification** - Check if address is a contract - **Security analysis** - Verify deployed bytecode matches expected - **DeFi integrations** - Validate contracts before interactions - **Protocol analysis** - Analyze contract deployments for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0x471EcE3750Da237f93B8E339c536989b8978a438", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Contract bytecode or `0x` if EOA | ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0x471EcE3750Da237f93B8E339c536989b8978a438", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x471EcE3750Da237f93B8E339c536989b8978a438'; const code = await provider.getCode(address); if (code === '0x') { console.log('Address is an EOA (externally owned account)'); } else { console.log('Address is a contract'); console.log('Bytecode length:', code.length); } // Check if address is a contract async function isContract(address) { const code = await provider.getCode(address); return code !== '0x'; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x471EcE3750Da237f93B8E339c536989b8978a438' code = w3.eth.get_code(address) if code == b'': print('Address is an EOA') else: print('Address is a contract') print(f'Bytecode length: {len(code.hex())}') # Check if address is a contract def is_contract(address): code = w3.eth.get_code(address) return code != b'' ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0x471EcE3750Da237f93B8E339c536989b8978a438") code, err := client.CodeAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } if len(code) == 0 { fmt.Println("Address is an EOA") } else { fmt.Printf("Contract bytecode length: %d\n", len(code)) } } ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_getStorageAt`](./eth_getStorageAt) - Get contract storage --- ## eth_getFilterChanges - Celo RPC Method # eth_getFilterChanges Polling method for a filter on Celo, returns an array of logs since last poll. ## Use Cases - **Event streaming** - Get new events incrementally - **Real-time monitoring** - Track contract activity for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) - **Efficient indexing** - Process only new events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Poll loop async function pollFilter(filterId, interval = 2000) { while (true) { const changes = await provider.send('eth_getFilterChanges', [filterId]); if (changes.length > 0) { console.log('New events:', changes); } await new Promise(r => setTimeout(r, interval)); } } ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter --- ## eth_getFilterLogs - Celo RPC Method # eth_getFilterLogs Returns an array of all logs matching filter with given ID on Celo. ## Use Cases - **Historical queries** - Get all matching logs for a filter - **Full event history** - Retrieve complete event data for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const logs = await provider.send('eth_getFilterLogs', [filterId]); console.log('All matching logs:', logs.length); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_getLogs - Celo RPC Method # eth_getLogs Returns an array of all logs matching a given filter object on Celo. > **Why Celo?** Build on the mobile-first L2 powering 500K+ daily active users and $2B+ monthly stablecoin volume with phone number-based addressing, sub-cent fees, 150+ country adoption, Nightfall privacy layer, and Opera browser integration. ## Use Cases The `eth_getLogs` method is essential for: - **Event indexing** - Track contract events for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) - **Token transfers** - Monitor ERC20/ERC721 transfers - **DeFi analytics** - Track swaps, liquidity events, and more - **Notification systems** - Alert on specific on-chain events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block (default: `"latest"`) | | `toBlock` | `QUANTITY\|TAG` | No | Ending block (default: `"latest"`) | | `address` | `DATA\|Array` | No | Contract address(es) to filter | | `topics` | `Array` | No | Array of topic filters | | `blockHash` | `DATA` | No | Filter single block by hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0x471EcE3750Da237f93B8E339c536989b8978a438", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns Array of log objects: | Field | Type | Description | |-------|------|-------------| | `address` | `DATA` | Contract that emitted the log | | `topics` | `Array` | Array of indexed topics | | `data` | `DATA` | Non-indexed log data | | `blockNumber` | `QUANTITY` | Block number | | `transactionHash` | `DATA` | Transaction hash | | `logIndex` | `QUANTITY` | Log index in block | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": [{ "address": "0x471EcE3750Da237f93B8E339c536989b8978a438", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."], "data": "0x...", "blockNumber": "0x5BAD55", "transactionHash": "0x...", "logIndex": "0x0" }] } ``` ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0x471EcE3750Da237f93B8E339c536989b8978a438", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Get Transfer events const TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'; async function getTransferEvents(tokenAddress, fromBlock, toBlock) { const logs = await provider.getLogs({ address: tokenAddress, topics: [TRANSFER_TOPIC], fromBlock: fromBlock, toBlock: toBlock }); return logs.map(log => ({ from: '0x' + log.topics[1].slice(26), to: '0x' + log.topics[2].slice(26), blockNumber: log.blockNumber, transactionHash: log.transactionHash })); } const events = await getTransferEvents( '0x471EcE3750Da237f93B8E339c536989b8978a438', 'latest', 'latest' ); console.log('Transfer events:', events); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' def get_transfer_events(token_address, from_block, to_block): logs = w3.eth.get_logs({ 'address': token_address, 'topics': [TRANSFER_TOPIC], 'fromBlock': from_block, 'toBlock': to_block }) events = [] for log in logs: events.append({ 'from': '0x' + log['topics'][1].hex()[26:], 'to': '0x' + log['topics'][2].hex()[26:], 'block': log['blockNumber'], 'tx': log['transactionHash'].hex() }) return events events = get_transfer_events( '0x471EcE3750Da237f93B8E339c536989b8978a438', 'latest', 'latest' ) print(f'Found {len(events)} transfer events') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0x471EcE3750Da237f93B8E339c536989b8978a438") transferTopic := common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef") query := ethereum.FilterQuery{ FromBlock: big.NewInt(0), ToBlock: nil, Addresses: []common.Address{contractAddress}, Topics: [][]common.Hash, } logs, err := client.FilterLogs(context.Background(), query) if err != nil { log.Fatal(err) } fmt.Printf("Found %d events\n", len(logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32005 | Query returned more than 10000 results | Reduce block range | | -32602 | Invalid params | Invalid filter parameters | ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create a filter for logs - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for new logs --- ## eth_getStorageAt - Celo RPC Method # eth_getStorageAt Returns the value from a storage position at a given address on Celo. ## Use Cases - **Contract analysis** - Read raw storage values - **State verification** - Verify contract state - **Security auditing** - Analyze storage layout for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) - **Protocol monitoring** - Track state changes ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte contract address | | `position` | `QUANTITY` | Yes | Storage slot position | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0x471EcE3750Da237f93B8E339c536989b8978a438", "0x0", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0x471EcE3750Da237f93B8E339c536989b8978a438", "0x0", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x471EcE3750Da237f93B8E339c536989b8978a438'; const slot = 0; const storage = await provider.getStorage(address, slot); console.log('Storage at slot 0:', storage); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x471EcE3750Da237f93B8E339c536989b8978a438' storage = w3.eth.get_storage_at(address, 0) print(f'Storage at slot 0: {storage.hex()}') ``` ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_call`](./eth_call) - Call contract functions --- ## eth_getTransactionByHash - Celo RPC Method # eth_getTransactionByHash Returns the information about a transaction by transaction hash on Celo. > **Why Celo?** Build on the mobile-first L2 powering 500K+ daily active users and $2B+ monthly stablecoin volume with phone number-based addressing, sub-cent fees, 150+ country adoption, Nightfall privacy layer, and Opera browser integration. ## Use Cases The `eth_getTransactionByHash` method is essential for: - **Transaction tracking** - Get details of pending or confirmed transactions - **Payment verification** - Verify transaction parameters - **Debugging** - Analyze transaction data for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) - **Block explorers** - Display transaction information ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x69d8e9317be809224e01515be6cf3d0716e92b340a680832c45e5e668ff05abe"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `hash` | `DATA` | Transaction hash | | `from` | `DATA` | Sender address | | `to` | `DATA` | Recipient address | | `value` | `QUANTITY` | Value in wei | | `gas` | `QUANTITY` | Gas provided | | `gasPrice` | `QUANTITY` | Gas price in wei | | `input` | `DATA` | Transaction input data | | `nonce` | `QUANTITY` | Sender's nonce | | `blockHash` | `DATA` | Block hash (null if pending) | | `blockNumber` | `QUANTITY` | Block number (null if pending) | ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x69d8e9317be809224e01515be6cf3d0716e92b340a680832c45e5e668ff05abe"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x69d8e9317be809224e01515be6cf3d0716e92b340a680832c45e5e668ff05abe'; const tx = await provider.getTransaction(txHash); if (tx) { console.log('From:', tx.from); console.log('To:', tx.to); console.log('Value:', formatEther(tx.value)); console.log('Block:', tx.blockNumber); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x69d8e9317be809224e01515be6cf3d0716e92b340a680832c45e5e668ff05abe' tx = w3.eth.get_transaction(tx_hash) if tx: print(f'From: {tx["from"]}') print(f'To: {tx["to"]}') print(f'Value: {w3.from_wei(tx["value"], "ether")}') print(f'Block: {tx["blockNumber"]}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x69d8e9317be809224e01515be6cf3d0716e92b340a680832c45e5e668ff05abe") tx, isPending, err := client.TransactionByHash(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Pending: %v\n", isPending) fmt.Printf("Value: %s\n", tx.Value().String()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash format | ## Related Methods - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction receipt - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionCount - Celo RPC Method # eth_getTransactionCount Returns the number of transactions sent from an address on Celo (the nonce). ## Use Cases - **Transaction building** - Get correct nonce for new transactions - **Account analysis** - Count total outgoing transactions - **Nonce management** - Handle pending transaction queues - **Wallet operations** - Prepare transactions for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag (`pending` for next nonce) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x471EcE3750Da237f93B8E339c536989b8978a438", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x471EcE3750Da237f93B8E339c536989b8978a438", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x471EcE3750Da237f93B8E339c536989b8978a438'; const nonce = await provider.getTransactionCount(address); console.log('Nonce:', nonce); // Get pending nonce for new transaction const pendingNonce = await provider.getTransactionCount(address, 'pending'); console.log('Next nonce:', pendingNonce); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x471EcE3750Da237f93B8E339c536989b8978a438' nonce = w3.eth.get_transaction_count(address) print(f'Nonce: {nonce}') # Get pending nonce pending_nonce = w3.eth.get_transaction_count(address, 'pending') print(f'Next nonce: {pending_nonce}') ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionReceipt - Celo RPC Method # eth_getTransactionReceipt Returns the receipt of a transaction by transaction hash on Celo. Receipt is only available for mined transactions. > **Why Celo?** Build on the mobile-first L2 powering 500K+ daily active users and $2B+ monthly stablecoin volume with phone number-based addressing, sub-cent fees, 150+ country adoption, Nightfall privacy layer, and Opera browser integration. ## Use Cases The `eth_getTransactionReceipt` method is essential for: - **Transaction confirmation** - Verify transaction was mined successfully - **Gas analysis** - Check actual gas used vs estimated - **Event parsing** - Read emitted events from logs - **Status verification** - Confirm success/failure for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x69d8e9317be809224e01515be6cf3d0716e92b340a680832c45e5e668ff05abe"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `status` | `QUANTITY` | `1` (success) or `0` (failure) | | `transactionHash` | `DATA` | Transaction hash | | `blockHash` | `DATA` | Block hash | | `blockNumber` | `QUANTITY` | Block number | | `gasUsed` | `QUANTITY` | Gas used by this transaction | | `cumulativeGasUsed` | `QUANTITY` | Total gas used in block up to this tx | | `logs` | `Array` | Array of log objects | | `contractAddress` | `DATA` | Created contract address (if deployment) | ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x69d8e9317be809224e01515be6cf3d0716e92b340a680832c45e5e668ff05abe"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x69d8e9317be809224e01515be6cf3d0716e92b340a680832c45e5e668ff05abe'; const receipt = await provider.getTransactionReceipt(txHash); if (receipt) { console.log('Status:', receipt.status === 1 ? 'Success' : 'Failed'); console.log('Gas Used:', receipt.gasUsed.toString()); console.log('Block:', receipt.blockNumber); console.log('Logs:', receipt.logs.length); // Parse specific events for (const log of receipt.logs) { console.log('Event from:', log.address); } } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x69d8e9317be809224e01515be6cf3d0716e92b340a680832c45e5e668ff05abe' receipt = w3.eth.get_transaction_receipt(tx_hash) if receipt: status = 'Success' if receipt['status'] == 1 else 'Failed' print(f'Status: {status}') print(f'Gas Used: {receipt["gasUsed"]}') print(f'Block: {receipt["blockNumber"]}') print(f'Logs: {len(receipt["logs"])}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x69d8e9317be809224e01515be6cf3d0716e92b340a680832c45e5e668ff05abe") receipt, err := client.TransactionReceipt(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Status: %d\n", receipt.Status) fmt.Printf("Gas Used: %d\n", receipt.GasUsed) fmt.Printf("Logs: %d\n", len(receipt.Logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash | **Note**: Returns `null` if transaction is not yet mined. ## Related Methods - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details - [`eth_getLogs`](./eth_getLogs) - Query logs by filter --- ## eth_hashrate - Get node hashrate(Celo) # eth_hashrate Get node hashrate on the Celo network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_hashrate](https://ethereum.org/developers/docs/apis/json-rpc/#eth_hashrate) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_hashrate", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_hashrate', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Celo documentation](/docs/celo).* --- ## eth_maxPriorityFeePerGas - Celo RPC Method # eth_maxPriorityFeePerGas Returns the current recommended priority fee per gas on Celo for EIP-1559 transactions. ## Use Cases - **EIP-1559 transactions** - Set appropriate priority fees - **Transaction acceleration** - Calculate tips for faster inclusion - **Gas optimization** - Balance speed vs cost for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); console.log('Max Priority Fee:', formatUnits(feeData.maxPriorityFeePerGas, 'gwei'), 'Gwei'); console.log('Max Fee Per Gas:', formatUnits(feeData.maxFeePerGas, 'gwei'), 'Gwei'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) priority_fee = w3.eth.max_priority_fee print(f'Max Priority Fee: {w3.from_wei(priority_fee, "gwei")} Gwei') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get legacy gas price - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data --- ## eth_mining - Check if node is mining(Celo) # eth_mining Check if node is mining on the Celo network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_mining](https://ethereum.org/developers/docs/apis/json-rpc/#eth_mining) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_mining', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Celo documentation](/docs/celo).* --- ## eth_newBlockFilter - Celo RPC Method # eth_newBlockFilter Creates a filter on Celo to notify when a new block arrives. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newBlockFilter', []); // Poll for new blocks const newBlocks = await provider.send('eth_getFilterChanges', [filterId]); console.log('New block hashes:', newBlocks); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_blockNumber`](./eth_blockNumber) - Get current block --- ## eth_newFilter - Celo RPC Method # eth_newFilter Creates a filter object on Celo to notify when state changes (logs). ## Use Cases - **Event monitoring** - Subscribe to contract events - **Real-time updates** - Track events for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) - **Indexing** - Build event indexes incrementally ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block | | `toBlock` | `QUANTITY\|TAG` | No | Ending block | | `address` | `DATA\|Array` | No | Contract address(es) | | `topics` | `Array` | No | Topic filters | ## Request ```json { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0x471EcE3750Da237f93B8E339c536989b8978a438", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0x471EcE3750Da237f93B8E339c536989b8978a438" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Create filter const filterId = await provider.send('eth_newFilter', [{ fromBlock: 'latest', address: '0x471EcE3750Da237f93B8E339c536989b8978a438', topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'] }]); // Poll for changes const changes = await provider.send('eth_getFilterChanges', [filterId]); console.log('New events:', changes); // Cleanup await provider.send('eth_uninstallFilter', [filterId]); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for changes - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_newPendingTransactionFilter - Celo RPC Method # eth_newPendingTransactionFilter Creates a filter on Celo to notify when new pending transactions arrive. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newPendingTransactionFilter', []); // Poll for pending transactions const pendingTxs = await provider.send('eth_getFilterChanges', [filterId]); console.log('Pending transaction hashes:', pendingTxs); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_protocolVersion - Get protocol version(Celo) # eth_protocolVersion Get protocol version on the Celo network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_protocolVersion](https://ethereum.org/developers/docs/apis/json-rpc/#eth_protocolversion) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_protocolVersion", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_protocolVersion', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Celo documentation](/docs/celo).* --- ## eth_sendRawTransaction - Celo RPC Method # eth_sendRawTransaction Submits a pre-signed transaction for broadcast to Celo. > **Why Celo?** Build on the mobile-first L2 powering 500K+ daily active users and $2B+ monthly stablecoin volume with phone number-based addressing, sub-cent fees, 150+ country adoption, Nightfall privacy layer, and Opera browser integration. ## Use Cases The `eth_sendRawTransaction` method is essential for: - **Broadcasting transactions** - Submit signed transactions to the network - **Wallet operations** - Send native tokens and interact with contracts - **DeFi operations** - Execute swaps, provide liquidity for mobile stablecoin payments (MiniPay 10M+ wallets), remittances, humanitarian aid, and local currency stablecoins (cUSD, cNGN, cEUR) - **Batch operations** - Submit multiple transactions efficiently ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `signedTransactionData` | `DATA` | Yes | The signed transaction data (RLP encoded) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | 32-byte transaction hash | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c808504a817c80082520894..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const wallet = new Wallet('YOUR_PRIVATE_KEY', provider); // Send native tokens async function sendTransaction(to, value) { const tx = await wallet.sendTransaction({ to: to, value: parseEther(value) }); console.log('Transaction hash:', tx.hash); // Wait for confirmation const receipt = await tx.wait(); console.log('Confirmed in block:', receipt.blockNumber); return receipt; } // Send to contract async function sendContractTransaction(contract, method, args, value = '0') { const tx = await contract[method](...args, { value: parseEther(value) }); return await tx.wait(); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) def send_transaction(private_key, to, value_in_ether): account = w3.eth.account.from_key(private_key) # Build transaction tx = { 'nonce': w3.eth.get_transaction_count(account.address), 'to': to, 'value': w3.to_wei(value_in_ether, 'ether'), 'gas': 21000, 'gasPrice': w3.eth.gas_price, 'chainId': w3.eth.chain_id } # Sign transaction signed_tx = account.sign_transaction(tx) # Send transaction tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) print(f'Transaction hash: {tx_hash.hex()}') # Wait for confirmation receipt = w3.eth.wait_for_transaction_receipt(tx_hash) print(f'Confirmed in block: {receipt["blockNumber"]}') return receipt ``` ```go package main "context" "crypto/ecdsa" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY") if err != nil { log.Fatal(err) } publicKey := privateKey.Public() publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey) fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA) nonce, _ := client.PendingNonceAt(context.Background(), fromAddress) value := big.NewInt(1000000000000000000) gasLimit := uint64(21000) gasPrice, _ := client.SuggestGasPrice(context.Background()) toAddress := common.HexToAddress("0x471EcE3750Da237f93B8E339c536989b8978a438") tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil) chainID, _ := client.NetworkID(context.Background()) signedTx, _ := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey) err = client.SendTransaction(context.Background(), signedTx) if err != nil { log.Fatal(err) } fmt.Printf("Transaction hash: %s\n", signedTx.Hash().Hex()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Nonce too low | Transaction nonce already used | | -32000 | Insufficient funds | Account has insufficient balance | | -32000 | Gas too low | Gas limit insufficient | | -32000 | Replacement underpriced | Gas price too low for replacement | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas required - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction result --- ## eth_sendTransaction - Send transaction (wallet...(Celo) # eth_sendTransaction > **Important**: Dwellir's shared Celo endpoints do not manage user private keys. JSON-RPC nodes cannot unlock your account, so `eth_sendTransaction` calls will fail. Sign transactions client-side and broadcast them with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Why this method is disabled on shared nodes - [`eth_sendTransaction` requires the node to hold and unlock the `from` account's private key](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction). - Managed infrastructure providers disable it for security reasons rather than storing customer keys on shared servers (for example, [Infura explicitly blocks the method on shared endpoints](https://docs.infura.io/api/networks/ethereum/json-rpc-methods/eth_sendtransaction)). ## Recommended workflow 1. Build the raw transaction locally with your wallet or SDK. 2. Sign the payload client-side (hardware wallet, custodial service, or library). 3. Submit the signed hex string with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Example response from the shared endpoint ```bash curl -s -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"0x0000000000000000000000000000000000000000"}],"id":1}' ``` ```json {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"unknown account"}} ``` Need help? Contact our [support team](mailto:support@dwellir.com) or use the dedicated [`eth_sendRawTransaction`](./eth_sendRawTransaction) guide. --- ## eth_signTransaction - Sign transaction (rarely...(Celo) # eth_signTransaction Signs a transaction using an unlocked account on the node. **Important**: Most RPC providers don't support this method for security reasons, as it requires private keys to be stored on the server. ## Security Considerations - This method requires an unlocked account on the node - Private keys must be available to the RPC server - Most production RPC providers disable this method - Use client-side signing libraries instead for better security ## Parameters 1. `Object` - The transaction object: - `from`: `DATA`, 20 Bytes - The address the transaction is sent from - `to`: `DATA`, 20 Bytes - (optional) The address the transaction is directed to - `gas`: `QUANTITY` - (optional) Integer of the gas provided for the transaction execution - `gasPrice`: `QUANTITY` - (optional) Integer of the gasPrice used for each paid gas - `value`: `QUANTITY` - (optional) Integer of the value sent with this transaction - `data`: `DATA` - (optional) The compiled code of a contract OR the hash of the invoked method signature and encoded parameters ## Returns `DATA` - The signed transaction data, ready for transmission via `eth_sendRawTransaction`. ## Implementation Example ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_signTransaction", "params": [{ "from": "0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a" }], "id": 1 }' ``` ```javascript const response = await fetch('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_signTransaction', params: [{ from: '0x9b2055d370f73ec7d8a03e965129118dc8f5bf83', to: '0xd46e8dd67c5d32be8058bb8eb970870f07244567', gas: '0x76c0', gasPrice: '0x9184e72a000', value: '0x9184e72a' }], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0xf86c808504a817c8008276c094d46e8dd67c5d32be8058bb8eb970870f072445675849184e72a8001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804" } ``` **Note**: This method is typically not available on hosted RPC providers for security reasons. The response shows a signed transaction ready for broadcast. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Celo documentation](/docs/celo).* --- ## eth_syncing - Celo RPC Method # eth_syncing Returns syncing status of Celo node. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 } ``` ## Returns Returns `false` if not syncing, or an object with sync status. ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const syncing = await provider.send('eth_syncing', []); if (syncing === false) { console.log('Node is fully synced'); } else { console.log('Syncing:', syncing); } ``` ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get current block - [`net_peerCount`](./net_peerCount) - Get peer count --- ## eth_uninstallFilter - Celo RPC Method # eth_uninstallFilter Uninstalls a filter on Celo. Should be called when no longer needed. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID to uninstall | ## Request ```json { "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if filter was found and uninstalled | ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const success = await provider.send('eth_uninstallFilter', [filterId]); console.log('Filter removed:', success); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter --- ## Celo - Mobile-First Blockchain Platform Documentation # Celo - Build Mobile-First Financial Applications ## Why Build on Celo? Celo is a mobile-first, EVM-compatible blockchain platform designed to make decentralized financial tools accessible to anyone with a mobile phone. As a carbon-negative blockchain, Celo leads the way in sustainable Web3 development. ### 📱 **Mobile-First Architecture** - **Ultralight client** - Sync and verify on low-end smartphones - **Phone number mapping** - Send crypto using just phone numbers - **Gas fee abstraction** - Pay fees with any Celo native asset - **Offline transactions** - Support for areas with limited connectivity ### 🌍 **Financial Inclusion** - **Stable value currencies** - Native stablecoins (cUSD, cEUR, cREAL) - **Low transaction costs** - Transactions under $0.01 - **Fast finality** - 5-second block times with instant finality - **Multi-currency gas** - Pay transaction fees in stable tokens ### 🌱 **Sustainability Leadership** - **Carbon negative** - First carbon-negative blockchain - **Regenerative finance** - Built-in climate action programs - **Natural capital backing** - Reserve includes tokenized rainforest - **Climate collective** - Supporting ecosystem climate initiatives ## Quick Start with Celo Connect to Celo in seconds with Dwellir's high-performance endpoints: ### Installation & Setup ```javascript // Connect to Celo mainnet const provider = new JsonRpcProvider( 'https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); // Get the latest block const block = await provider.getBlock('latest'); console.log('Latest block:', block.number); // Query cUSD balance const cUSD = '0x765DE816845861e75A25fCA122bb6898B8B1282a'; const balance = await provider.getBalance('0x...', cUSD); console.log('cUSD Balance:', balance.toString()); ``` ```javascript const Web3 = require('web3'); // Connect to Celo mainnet const web3 = new Web3( 'https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); // Get chain ID to verify connection const chainId = await web3.eth.getChainId(); console.log('Connected to Celo:', chainId === 42220); // Get gas price in CELO const gasPrice = await web3.eth.getGasPrice(); console.log('Current gas price:', gasPrice); ``` ```typescript // Create Celo client const client = createPublicClient({ chain: celo, transport: http('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'), }); // Read stable token balance const cUSDAddress = '0x765DE816845861e75A25fCA122bb6898B8B1282a'; const balance = await client.readContract({ address: cUSDAddress, abi: erc20Abi, functionName: 'balanceOf', args: ['0x...'], }); ``` ```javascript // Connect using ContractKit (Celo's SDK) const kit = newKit('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Get stable token contracts const cUSD = await kit.contracts.getStableToken(); const cEUR = await kit.contracts.getStableToken('cEUR'); // Get account balance in multiple currencies const address = '0x...'; const [celoBalance, cUsdBalance] = await Promise.all([ kit.getTotalBalance(address), cUSD.balanceOf(address) ]); console.log('CELO:', celoBalance.CELO.toString()); console.log('cUSD:', cUsdBalance.toString()); ``` ## Network Information Chain ID 42220 Mainnet Block Time 5 seconds With instant finality Gas Token CELO Multi-asset fees Consensus PBFT Proof of Stake ## JSON-RPC API Reference Celo supports the full [Ethereum JSON-RPC API](https://ethereum.org/developers/docs/apis/json-rpc/) plus additional Celo-specific methods for mobile and stable currency features. ## Celo-Specific Features ### 🪙 Native Stable Currencies Work with Celo's algorithmic stablecoins: ```javascript // Stable token addresses on Celo Mainnet const STABLE_TOKENS = { cUSD: '0x765DE816845861e75A25fCA122bb6898B8B1282a', cEUR: '0xD8763CBa276a3738E6DE85b4b3bF5FDed6D6cA73', cREAL: '0xe8537a3d056DA446677B9E9d6c5dB704EaAb4787' }; // Transfer cUSD async function transferCUSD(to, amount) { const cUSD = new ethers.Contract( STABLE_TOKENS.cUSD, ['function transfer(address to, uint256 amount) returns (bool)'], signer ); const tx = await cUSD.transfer(to, ethers.parseUnits(amount, 18)); await tx.wait(); return tx.hash; } ``` ### 📞 Phone Number Verification Integrate Celo's identity protocol: ```javascript // Verify phone number ownership (using Celo SDK) async function verifyPhoneNumber(phoneNumber, address) { // Get attestation service const attestations = await kit.contracts.getAttestations(); // Request attestations const tx = await attestations.request( phoneNumber, 3, // Number of attestations address ); await tx.waitReceipt(); // Complete verification process const attestationCode = await getAttestationCode(); // SMS verification await attestations.complete(phoneNumber, address, attestationCode); } ``` ### 💰 Fee Currency Selection Pay gas fees with stable tokens: ```javascript // Configure transaction to pay fees in cUSD async function sendWithStableFees(to, value) { const tx = { to, value: ethers.parseEther(value), feeCurrency: STABLE_TOKENS.cUSD, // Pay fees in cUSD gasLimit: 21000, gasPrice: await provider.getGasPrice() }; const signedTx = await signer.signTransaction(tx); const receipt = await provider.sendTransaction(signedTx); return receipt; } ``` ## Common Integration Patterns ### 🔄 Multi-Currency Wallets Build wallets supporting multiple Celo assets: ```javascript class CeloWallet { constructor(provider, address) { this.provider = provider; this.address = address; } async getBalances() { const balances = {}; // Get CELO balance balances.CELO = await this.provider.getBalance(this.address); // Get stable token balances for (const [symbol, address] of Object.entries(STABLE_TOKENS)) { const contract = new ethers.Contract( address, ['function balanceOf(address) view returns (uint256)'], this.provider ); balances[symbol] = await contract.balanceOf(this.address); } return balances; } async getUSDValue() { const balances = await this.getBalances(); let totalUSD = 0; // cUSD is pegged 1:1 totalUSD += Number(ethers.formatUnits(balances.cUSD, 18)); // Get CELO price from oracle const celoPrice = await this.getCELOPrice(); totalUSD += Number(ethers.formatUnits(balances.CELO, 18)) * celoPrice; return totalUSD; } } ``` ### 🌐 Mobile Light Client Optimize for mobile devices: ```javascript // Ultralight client configuration class MobileCeloClient { constructor(rpcUrl) { this.provider = new JsonRpcProvider(rpcUrl, { // Optimize for mobile timeout: 30000, throttleLimit: 1, throttleSlotInterval: 1000 }); // Cache frequently accessed data this.cache = new Map(); } async getBlockHeader(blockNumber) { const key = `block_${blockNumber}`; if (this.cache.has(key)) { return this.cache.get(key); } // Fetch only essential fields for mobile const block = await this.provider.send('eth_getBlockByNumber', [ ethers.toQuantity(blockNumber), false // Don't include transactions ]); const header = { number: block.number, hash: block.hash, timestamp: block.timestamp, gasUsed: block.gasUsed }; this.cache.set(key, header); return header; } } ``` ### 🔐 Validator Operations Interact with Celo's proof-of-stake system: ```javascript // Stake CELO with validators async function stakeCELO(validatorAddress, amount) { const election = await kit.contracts.getElection(); const lockedGold = await kit.contracts.getLockedGold(); // Lock CELO first await lockedGold.lock().sendAndWaitForReceipt({ value: amount }); // Vote for validator await election.vote(validatorAddress, amount) .sendAndWaitForReceipt(); console.log(`Staked ${amount} CELO with validator ${validatorAddress}`); } // Get validator rewards async function getRewards(address) { const election = await kit.contracts.getElection(); const rewards = await election.getVoterRewards(address); return rewards; } ``` ## Performance Optimization ### 1. **Batch Operations** Minimize RPC calls with multicall: ```javascript async function batchTokenBalances(addresses) { const multicall = new Multicall(kit); const calls = addresses.flatMap(addr => Object.entries(STABLE_TOKENS).map(([symbol, token]) => ({ target: token, callData: encodeBalanceOf(addr), symbol, address: addr })) ); const results = await multicall.aggregate(calls); return parseResults(results); } ``` ### 2. **Archive Node Access** Leverage Dwellir's archive nodes for historical data: ```javascript // Query historical stable token prices async function getHistoricalPrice(blockNumber) { const oracle = new ethers.Contract( ORACLE_ADDRESS, ['function getExchangeRate(address) view returns (uint256, uint256)'], provider ); // Use archive node to query past state const [numerator, denominator] = await oracle.getExchangeRate( STABLE_TOKENS.cUSD, { blockTag: blockNumber } ); return numerator / denominator; } ``` ### 3. **Event Indexing** Efficiently sync events with filters: ```javascript async function syncTransfers(fromBlock, toBlock) { const filter = { address: STABLE_TOKENS.cUSD, topics: [ethers.id('Transfer(address,address,uint256)')], fromBlock, toBlock }; // Process in chunks to avoid timeouts const chunkSize = 1000; const events = []; for (let i = fromBlock; i <= toBlock; i += chunkSize) { const chunk = await provider.getLogs({ ...filter, fromBlock: i, toBlock: Math.min(i + chunkSize - 1, toBlock) }); events.push(...chunk); } return events; } ``` ## Developer Resources ### Getting Started Guides #### 🚀 **Quick Start Tutorial** Build your first Celo dApp in 10 minutes: 1. **Setup Development Environment** ```bash # Install Celo CLI npm install -g @celo/celocli # Create new project npx create-react-app my-celo-dapp cd my-celo-dapp # Install Celo dependencies npm install @celo/contractkit ethers ``` 2. **Connect to Celo** ```javascript // src/celo.js export const kit = newKit( 'https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); ``` 3. **Build UI Components** ```jsx // src/App.js function App() { const [account, setAccount] = useState(''); const [balance, setBalance] = useState('0'); useEffect(() => { connectWallet(); }, []); async function connectWallet() { // Connect to Celo wallet const accounts = await kit.web3.eth.getAccounts(); setAccount(accounts[0]); // Get balance const bal = await kit.getTotalBalance(accounts[0]); setBalance(bal.CELO.toString()); } return ( My Celo dApp Account: {account} Balance: {balance} CELO ); } ``` #### 📱 **Mobile Integration Guide** Optimize your dApp for mobile users: ```javascript // Mobile-optimized provider configuration const mobileConfig = { // Reduce timeout for mobile networks timeout: 20000, // Enable compression headers: { 'Accept-Encoding': 'gzip, deflate' }, // Retry logic for unstable connections retry: { retries: 3, minTimeout: 1000, maxTimeout: 5000 } }; // Detect mobile and adjust accordingly const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent); const provider = new JsonRpcProvider( 'https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY', isMobile ? mobileConfig : {} ); ``` ### Troubleshooting #### Common Issues and Solutions | Issue | Description | Solution | |-------|------------|----------| | "Insufficient fee currency balance" | Not enough of selected fee currency | Ensure account has sufficient cUSD/cEUR or switch to CELO for fees | | "Invalid feeCurrency address" | Fee currency not supported | Use only approved stable tokens: cUSD, cEUR, cREAL | | "Phone number already verified" | Number linked to another address | Use Celo's re-verification process or contact support | | "Validator not registered" | Trying to vote for invalid validator | Check validator status with `election.getValidatorGroups()` | ### Testing on Alfajores Testnet Get started with Celo's testnet: ```javascript // Connect to Alfajores testnet const testnetProvider = new JsonRpcProvider( 'https://api-celo-alfajores.n.dwellir.com/YOUR_API_KEY' ); // Alfajores faucet // Visit: https://faucet.celo.org // Testnet stable tokens const ALFAJORES_TOKENS = { cUSD: '0x874069Fa1Eb16D44d622F2e0Ca25eeA172369bC1', cEUR: '0x10c892A6EC43a53E45D0B916B4b7D383B1b78C0F' }; ``` ## Migration Guide ### From Ethereum to Celo Migrating Ethereum dApps to Celo is straightforward: ```javascript // Before (Ethereum) const provider = new JsonRpcProvider('https://eth-rpc.example.com'); const tx = { to: recipient, value: amount, gasPrice: await provider.getGasPrice() }; // After (Celo) const provider = new JsonRpcProvider( 'https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); const tx = { to: recipient, value: amount, gasPrice: await provider.getGasPrice(), feeCurrency: STABLE_TOKENS.cUSD // Optional: pay fees in cUSD }; // ✅ EVM compatible - contracts work without changes // ✅ Same Web3 libraries and tools // ⚠️ Different chain ID (42220) // ⚠️ Additional features: stable tokens, phone verification // ✨ New capability: multi-currency gas payments ``` ## Ecosystem & Tools ### DeFi on Celo - **Ubeswap** - Leading DEX on Celo - **Moola Market** - Lending and borrowing - **Mento** - Decentralized stable asset protocol - **Valora** - Mobile-first Celo wallet ### Developer Tools - [Celo Composer](https://github.com/celo-org/celo-composer) - Full-stack starter kit - [Remix IDE](https://remix.ethereum.org) - Deploy contracts to Celo - [Celo Explorer](https://explorer.celo.org) - Block explorer - [ContractKit](https://docs.celo.org/developer/contractkit) - Celo SDK ### Community Resources - [Discord](https://discord.gg/celo) - Developer community - [Forum](https://forum.celo.org) - Technical discussions - [GitHub](https://github.com/celo-org) - Open source repositories ### Need Help? - 📧 **Email**: support@dwellir.com - 📚 **Celo Docs**: [docs.celo.org](https://docs.celo.org) - 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com) --- *Build the future of regenerative finance on Celo with Dwellir's reliable RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)* --- ## net_listening - Celo RPC Method # net_listening Returns `true` if client is actively listening for network connections on Celo. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if listening | ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const listening = await provider.send('net_listening', []); console.log('Node listening:', listening); ``` ## Related Methods - [`net_peerCount`](./net_peerCount) - Get peer count --- ## net_peerCount - Celo RPC Method # net_peerCount Returns number of peers currently connected to Celo client. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Number of connected peers (hexadecimal) | ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const peerCount = await provider.send('net_peerCount', []); console.log('Peer count:', parseInt(peerCount, 16)); ``` ## Related Methods - [`net_listening`](./net_listening) - Check if listening --- ## net_version - Celo RPC Method # net_version Returns the current network ID on Celo. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Network ID as a string | ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const networkId = await provider.send('net_version', []); console.log('Network ID:', networkId); ``` ## Related Methods - [`eth_chainId`](./eth_chainId) - Get chain ID --- ## web3_clientVersion - Celo RPC Method # web3_clientVersion Returns the current client version on Celo. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Client version string | ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const version = await provider.send('web3_clientVersion', []); console.log('Client version:', version); ``` --- ## web3_sha3 - Celo RPC Method # web3_sha3 Returns Keccak-256 (not standard SHA3-256) of the given data on Celo. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `data` | `DATA` | Yes | Data to hash | ## Request ```json { "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Keccak-256 hash of the data | ## Code Examples ```bash curl -X POST https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-celo-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Using RPC const hash = await provider.send('web3_sha3', ['0x68656c6c6f']); console.log('Hash:', hash); // Using ethers directly (faster) const localHash = keccak256(toUtf8Bytes('hello')); console.log('Local hash:', localHash); ``` --- ## author_pendingExtrinsics - Centrifuge RPC Method # author_pendingExtrinsics Returns all pending extrinsics in the transaction pool on Centrifuge. ## Use Cases - **Mempool monitoring** - Track pending transactions - **Transaction status** - Check if your transaction is pending for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Pool analysis** - Monitor network activity ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "author_pendingExtrinsics", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_pendingExtrinsics", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const pending = await api.rpc.author.pendingExtrinsics(); console.log('Pending extrinsics:', pending.length); pending.forEach((ext, idx) => { console.log(`${idx}: ${ext.method.section}.${ext.method.method}`); }); await api.disconnect(); ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction --- ## author_rotateKeys - Centrifuge RPC Method # author_rotateKeys Generate a new set of session keys on Centrifuge. This method creates fresh cryptographic keys for validator operations and stores them in the node's keystore. The returned keys must be registered on-chain via `session.setKeys`. ## Use Cases - **Validator setup** - Generate initial session keys for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Key rotation** - Periodically rotate keys for security best practices - **Recovery** - Generate new keys after potential key compromise ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | `Bytes` | Concatenated SCALE-encoded public keys for all session key types | ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_rotateKeys", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Generate new session keys const keys = await api.rpc.author.rotateKeys(); console.log('New session keys:', keys.toHex()); // These keys need to be registered on-chain: // api.tx.session.setKeys(keys, proof) await api.disconnect(); ``` ```python url = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'author_rotateKeys', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json() if 'result' in result: session_keys = result['result'] print(f'New session keys: {session_keys}') print('Register these keys using session.setKeys extrinsic') else: print(f"Error: {result.get('error')}") ``` ## Validator Setup Workflow 1. **Generate keys** - Call `author_rotateKeys` on your validator node 2. **Register on-chain** - Submit `session.setKeys(keys, proof)` extrinsic 3. **Wait for session** - Keys become active in the next session 4. **Verify** - Check `session.nextKeys` storage ## Security Considerations - Only call this method on your own validator node - Session keys are stored in the node's keystore - Rotate keys periodically and after any security incident - Never expose this RPC method publicly ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit setKeys transaction - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - View pending transactions --- ## author_submitAndWatchExtrinsic - Centrifuge RPC Method # author_submitAndWatchExtrinsic Submit a signed extrinsic to and subscribe to status updates. This WebSocket method provides real-time feedback on transaction progress from submission through finalization. ## Use Cases - **Transaction tracking** - Monitor extrinsic lifecycle for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **UI feedback** - Show users real-time transaction status - **Confirmation workflows** - Wait for specific finality level before proceeding ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `Bytes` | Yes | SCALE-encoded signed extrinsic | ## Returns Returns a subscription that emits `ExtrinsicStatus` updates: | Status | Description | |--------|-------------| | `future` | In future queue (nonce too high) | | `ready` | In ready queue, waiting for block | | `broadcast` | Broadcast to peers | | `inBlock` | Included in block (hash provided) | | `retracted` | Block retracted (reorg) | | `finalityTimeout` | Finality timeout | | `finalized` | Finalized in block (hash provided) | | `usurped` | Replaced by another extrinsic | | `dropped` | Dropped from pool | | `invalid` | Invalid extrinsic | ## Code Examples ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const keyring = new Keyring({ type: 'sr25519' }); // Create and sign a transfer const sender = keyring.addFromUri('//Alice'); const transfer = api.tx.balances.transferKeepAlive( '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 1000000000000n ); // Submit and watch const unsub = await transfer.signAndSend(sender, ({ status, events }) => { console.log(`Status: ${status.type}`); if (status.isInBlock) { console.log(`Included in block: ${status.asInBlock.toHex()}`); } if (status.isFinalized) { console.log(`Finalized in block: ${status.asFinalized.toHex()}`); unsub(); } }); ``` ```python async def submit_and_watch(signed_extrinsic_hex): uri = 'wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: # Submit and subscribe await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'author_submitAndWatchExtrinsic', 'params': [signed_extrinsic_hex], 'id': 1 })) # Get subscription ID response = json.loads(await ws.recv()) if 'error' in response: print(f"Error: {response['error']}") return sub_id = response['result'] print(f'Watching with subscription: {sub_id}') # Listen for status updates while True: message = json.loads(await ws.recv()) if 'params' in message: status = message['params']['result'] print(f"Status: {status}") # Check for finalization if isinstance(status, dict) and 'finalized' in status: print(f"Finalized in: {status['finalized']}") break # asyncio.run(submit_and_watch('0x...')) ``` ## Status Flow ``` ready → broadcast → inBlock → finalized ↘ retracted (if reorg) ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit without watching (fire-and-forget) - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - View transaction pool - [`payment_queryInfo`](./payment_queryInfo) - Estimate fees before submission --- ## author_submitExtrinsic - Centrifuge RPC Method # author_submitExtrinsic Submit a signed extrinsic to Centrifuge for inclusion in a block. ## Use Cases - **Transaction submission** - Broadcast signed transactions - **dApp interactions** - Execute on-chain operations for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Automated systems** - Submit programmatic transactions ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `String` | Yes | Hex-encoded signed extrinsic | ## Request ```json { "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": ["0x..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Transaction hash | ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": ["0x..."], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const keyring = new Keyring({ type: 'sr25519' }); const sender = keyring.addFromUri('//Alice'); // Build and sign transaction const transfer = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000); const hash = await transfer.signAndSend(sender); console.log('Transaction hash:', hash.toHex()); await api.disconnect(); ``` ## Related Methods - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - Get pending transactions - [`payment_queryInfo`](./payment_queryInfo) - Estimate fees --- ## beefy_getFinalizedHead - Centrifuge RPC Method # beefy_getFinalizedHead Returns the block hash of the latest BEEFY-finalized block on Centrifuge. BEEFY (Bridge Efficiency Enabling Finality Yielder) provides additional finality proofs optimized for light clients and bridges. ## Use Cases - **Cross-chain bridges** - Verify finality proofs for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Light clients** - Efficient finality verification without full GRANDPA proofs - **Trustless bridges** - Generate compact finality proofs for external chains ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | `Hash` | Block hash of the latest BEEFY-finalized block | ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "beefy_getFinalizedHead", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get BEEFY finalized head const beefyHead = await api.rpc.beefy.getFinalizedHead(); console.log('BEEFY finalized:', beefyHead.toHex()); // Compare with GRANDPA finalized const grandpaHead = await api.rpc.chain.getFinalizedHead(); console.log('GRANDPA finalized:', grandpaHead.toHex()); await api.disconnect(); ``` ```python url = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'beefy_getFinalizedHead', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json() if 'result' in result: print(f"BEEFY finalized: {result['result']}") else: print(f"Error: {result.get('error')}") ``` ## BEEFY vs GRANDPA Finality | Aspect | GRANDPA | BEEFY | |--------|---------|-------| | **Purpose** | Primary finality | Bridge-optimized finality | | **Proof size** | Larger (full validator set) | Compact (aggregated signatures) | | **Latency** | Immediate | Slightly delayed | | **Use case** | On-chain finality | Cross-chain bridges | ## Availability BEEFY is enabled on relay chains and some parachains. If BEEFY is not enabled, this method will return an error. ## Related Methods - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - GRANDPA finalized head - [`grandpa_roundState`](./grandpa_roundState) - GRANDPA consensus state - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks --- ## chain_getBlock - Centrifuge RPC Method # chain_getBlock Retrieves complete block information from Centrifuge, including the block header, extrinsics, and justifications. > **Why Centrifuge?** Build on the RWA tokenization platform bridging traditional finance with $1B+ Janus Henderson backing with ERC-7540 RWA standards, multichain via Wormhole, 97% securitization cost savings, and BlockTower $220M fund integration. ## Use Cases The `chain_getBlock` method is essential for: - **Block explorers** - Display complete block information - **Chain analysis** - Analyze block production patterns - **Transaction verification** - Confirm extrinsic inclusion for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Data indexing** - Build historical blockchain databases ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Hex-encoded block hash. If omitted, returns latest block | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getBlock", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `block` | `Object` | Complete block data | | `block.header` | `Object` | Block header information | | `block.header.parentHash` | `String` | Hash of the parent block | | `block.header.number` | `String` | Block number (hex-encoded) | | `block.header.stateRoot` | `String` | Root of the state trie | | `block.header.extrinsicsRoot` | `String` | Root of the extrinsics trie | | `block.extrinsics` | `Array` | Array of extrinsics in the block | | `justifications` | `Array` | Block justifications (if available) | ## Code Examples ```bash # Get latest block curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": [], "id": 1 }' # Get specific block curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get latest block const latestHash = await api.rpc.chain.getBlockHash(); const latestBlock = await api.rpc.chain.getBlock(latestHash); console.log('Latest block:', { number: latestBlock.block.header.number.toNumber(), hash: latestHash.toHex(), extrinsicsCount: latestBlock.block.extrinsics.length }); // Get specific block const blockHash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'; const block = await api.rpc.chain.getBlock(blockHash); console.log('Block extrinsics:', block.block.extrinsics.length); await api.disconnect(); ``` ```python def get_block(block_hash=None): url = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY' params = [block_hash] if block_hash else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getBlock', 'params': params, 'id': 1 } response = requests.post(url, json=payload) data = response.json() if 'error' in data: raise Exception(f"RPC Error: {data['error']}") return data['result'] # Get latest block latest_block = get_block() block_number = int(latest_block['block']['header']['number'], 16) print(f'Latest block number: {block_number}') # Get specific block specific_block = get_block('0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3') print(f"Extrinsics count: {len(specific_block['block']['extrinsics'])}") ``` ## Related Methods - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number - [`chain_getHeader`](./chain_getHeader) - Get block header only - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get finalized block hash --- ## chain_getBlockHash - Centrifuge RPC Method # chain_getBlockHash Returns the block hash for a given block number on Centrifuge. ## Use Cases - **Historical queries** - Convert block numbers to hashes - **Block navigation** - Navigate blockchain history for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Data indexing** - Build block number to hash mappings ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `Number` | No | Block number. If omitted, returns latest block hash | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getBlockHash", "params": [1000000], "id": 1 } ``` ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlockHash", "params": [1000000], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get hash for specific block number const blockNumber = 1000000; const blockHash = await api.rpc.chain.getBlockHash(blockNumber); console.log(`Block ${blockNumber} hash:`, blockHash.toHex()); await api.disconnect(); ``` ```python def get_block_hash(block_number=None): url = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY' params = [block_number] if block_number is not None else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getBlockHash', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] block_hash = get_block_hash(1000000) print(f'Block hash: {block_hash}') ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get block by hash - [`chain_getHeader`](./chain_getHeader) - Get block header --- ## chain_getFinalizedHead - Centrifuge RPC Method # chain_getFinalizedHead Returns the hash of the last finalized block on Centrifuge. ## Use Cases - **Confirmed state** - Query state that cannot be reverted - **Transaction confirmation** - Verify transaction finality for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Safe checkpoints** - Use finalized blocks for critical operations ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const finalizedHash = await api.rpc.chain.getFinalizedHead(); console.log('Finalized block hash:', finalizedHash.toHex()); // Get finalized block details const block = await api.rpc.chain.getBlock(finalizedHash); console.log('Finalized block number:', block.block.header.number.toNumber()); await api.disconnect(); ``` ```python def get_finalized_head(): url = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'chain_getFinalizedHead', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] finalized_hash = get_finalized_head() print(f'Finalized block hash: {finalized_hash}') ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get block by hash - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number --- ## chain_getHeader - Centrifuge RPC Method # chain_getHeader Returns the block header for a given hash on Centrifuge. ## Use Cases - **Lightweight queries** - Get header without full block data - **Chain synchronization** - Track block production for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Parent chain navigation** - Follow parentHash links ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash. If omitted, returns latest header | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getHeader", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 } ``` ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getHeader", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get latest header const header = await api.rpc.chain.getHeader(); console.log('Block number:', header.number.toNumber()); console.log('Parent hash:', header.parentHash.toHex()); await api.disconnect(); ``` ```python def get_header(block_hash=None): url = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY' params = [block_hash] if block_hash else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getHeader', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] header = get_header() print(f"Block number: {int(header['number'], 16)}") ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get full block with extrinsics - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number --- ## chain_subscribeFinalizedHeads - Centrifuge RPC Method # chain_subscribeFinalizedHeads Subscribe to receive notifications when blocks are finalized on Centrifuge. Finalized blocks are guaranteed to never be reverted, making this essential for applications requiring strong consistency. ## Use Cases - **Exchange deposits** - Only credit funds after finalization for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Bridge operations** - Wait for finality before cross-chain transfers - **Critical state changes** - Ensure irreversibility for important transactions ## Parameters This method takes no parameters. ## Returns Returns a subscription ID. The subscription emits `Header` objects for each finalized block: | Field | Type | Description | |-------|------|-------------| | `parentHash` | `Hash` | Parent block hash | | `number` | `BlockNumber` | Block number | | `stateRoot` | `Hash` | State trie root hash | | `extrinsicsRoot` | `Hash` | Extrinsics trie root hash | | `digest` | `Digest` | Block digest with consensus logs | ## Code Examples ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Subscribe to finalized heads const unsubscribe = await api.rpc.chain.subscribeFinalizedHeads((header) => { console.log(`Finalized block #${header.number}`); console.log(` Hash: ${header.hash.toHex()}`); // Safe to consider this block permanent processConfirmedBlock(header); }); // Later: unsubscribe() ``` ```python async def subscribe_finalized(): uri = 'wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'chain_subscribeFinalizedHeads', 'params': [], 'id': 1 })) response = json.loads(await ws.recv()) sub_id = response['result'] print(f'Subscribed to finalized heads: {sub_id}') while True: message = json.loads(await ws.recv()) if 'params' in message: header = message['params']['result'] block_num = int(header['number'], 16) print(f"Finalized: #{block_num}") asyncio.run(subscribe_finalized()) ``` ## Finality Lag Finalized blocks typically lag behind the best block by a few blocks due to GRANDPA consensus requirements. This is normal and ensures Byzantine fault tolerance. ## Related Methods - [`chain_subscribeNewHeads`](./chain_subscribeNewHeads) - Subscribe to all new blocks (not just finalized) - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get current finalized block hash - [`grandpa_roundState`](./grandpa_roundState) - Monitor GRANDPA consensus progress --- ## chain_subscribeNewHeads - Centrifuge RPC Method # chain_subscribeNewHeads Subscribe to receive notifications when new block headers are produced on Centrifuge. This WebSocket subscription provides real-time updates for each new block. ## Use Cases - **Block monitoring** - Track new blocks in real-time for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Event indexing** - Trigger processing when new blocks arrive - **Chain synchronization** - Keep external systems in sync with the chain ## Parameters This method takes no parameters. ## Returns Returns a subscription ID. The subscription emits `Header` objects for each new block: | Field | Type | Description | |-------|------|-------------| | `parentHash` | `Hash` | Parent block hash | | `number` | `BlockNumber` | Block number | | `stateRoot` | `Hash` | State trie root hash | | `extrinsicsRoot` | `Hash` | Extrinsics trie root hash | | `digest` | `Digest` | Block digest with consensus logs | ## Code Examples ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Subscribe to new heads const unsubscribe = await api.rpc.chain.subscribeNewHeads((header) => { console.log(`New block #${header.number}`); console.log(` Hash: ${header.hash.toHex()}`); console.log(` Parent: ${header.parentHash.toHex()}`); console.log(` State root: ${header.stateRoot.toHex()}`); }); // Later: unsubscribe() ``` ```python async def subscribe_new_heads(): uri = 'wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: # Subscribe to new heads await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'chain_subscribeNewHeads', 'params': [], 'id': 1 })) # Get subscription ID response = json.loads(await ws.recv()) sub_id = response['result'] print(f'Subscribed with ID: {sub_id}') # Listen for new headers while True: message = json.loads(await ws.recv()) if 'params' in message: header = message['params']['result'] print(f"Block #{int(header['number'], 16)}") print(f" Hash: {header['parentHash']}") asyncio.run(subscribe_new_heads()) ``` ## Subscription vs Polling | Approach | Latency | Resource Usage | Use Case | |----------|---------|----------------|----------| | `subscribeNewHeads` | Immediate | Low (push-based) | Real-time monitoring | | Polling `getHeader` | Block time + poll interval | Higher (repeated requests) | Simple integrations | ## Related Methods - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks only - [`chain_getHeader`](./chain_getHeader) - Get a specific block header - [`chain_getBlock`](./chain_getBlock) - Get full block with extrinsics --- ## eth_accounts - List available accounts # eth_accounts List available accounts on the Centrifuge network. ## Parameters Varies by method. Please refer to the official [Centrifuge JSON-RPC: eth_accounts](https://ethereum.org/developers/docs/apis/json-rpc/#eth_accounts) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_accounts', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_blockNumber - Get Latest Block Number # eth_blockNumber Returns the number of the most recent block on Centrifuge Mainnet. ## When to Use This Method `eth_blockNumber` is fundamental for: - **Syncing Applications** - Keep your dApp in sync with the latest blockchain state - **Transaction Monitoring** - Verify confirmations by comparing block numbers - **Event Filtering** - Set the correct block range for querying logs - **Health Checks** - Monitor node connectivity and sync status ## Parameters This method accepts no parameters. ```json { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } ``` ## Returns `QUANTITY` - Integer of the current block number the node is synced to. - **Type**: Hexadecimal string - **Format**: `0x` prefixed - **Example**: `0x5bad55` (6008149 in decimal) ## Implementation Examples ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 }' ``` ```javascript // Using fetch API const getBlockNumber = async () => { const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }) }); const data = await response.json(); const blockNumber = parseInt(data.result, 16); console.log('Current block:', blockNumber); return blockNumber; }; // Using ethers.js const provider = new JsonRpcProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const blockNumber = await provider.getBlockNumber(); console.log('Current block:', blockNumber); ``` ```python def get_block_number(): url = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY' payload = { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } response = requests.post(url, json=payload) data = response.json() # Convert hex to decimal block_number = int(data['result'], 16) print(f"Current block: {block_number}") return block_number # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY')) block_number = w3.eth.block_number print(f"Current block: {block_number}") ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-centrifuge.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockNumber, err := client.BlockNumber(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Current block: %d\n", blockNumber) } ``` ## Response Example ### Successful Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5bad55" } ``` ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error" } } ``` ## Common Use Cases ### 1. Block Confirmation Counter Monitor transaction confirmations: ```javascript async function getConfirmations(txHash) { const tx = await provider.getTransaction(txHash); if (!tx || !tx.blockNumber) return 0; const currentBlock = await provider.getBlockNumber(); return currentBlock - tx.blockNumber + 1; } // Wait for specific confirmations async function waitForConfirmations(txHash, confirmations = 6) { let currentConfirmations = 0; while (currentConfirmations < confirmations) { currentConfirmations = await getConfirmations(txHash); console.log(`Confirmations: ${currentConfirmations}/${confirmations}`); await new Promise(r => setTimeout(r, 2000)); // Check every 2 seconds } return true; } ``` ### 2. Event Log Filtering Query events from recent blocks: ```javascript async function getRecentEvents(contract, eventName, blockRange = 100) { const currentBlock = await provider.getBlockNumber(); const fromBlock = currentBlock - blockRange; const filter = contract.filters[eventName](); const events = await contract.queryFilter(filter, fromBlock, currentBlock); return events; } ``` ### 3. Node Health Monitoring Check if your node is synced: ```javascript async function checkNodeHealth() { try { const blockNumber = await provider.getBlockNumber(); const block = await provider.getBlock(blockNumber); const now = Date.now() / 1000; const blockAge = now - block.timestamp; if (blockAge > 60) { console.warn(`Node may be behind. Last block was ${blockAge}s ago`); return false; } console.log(`Node healthy. Latest block: ${blockNumber}`); return true; } catch (error) { console.error('Node unreachable:', error); return false; } } ``` ## Performance Optimization ### Caching Strategy Cache block numbers to reduce API calls: ```javascript class BlockNumberCache { constructor(ttl = 2000) { // 2 second cache this.cache = null; this.timestamp = 0; this.ttl = ttl; } async get(provider) { const now = Date.now(); if (this.cache && (now - this.timestamp) < this.ttl) { return this.cache; } this.cache = await provider.getBlockNumber(); this.timestamp = now; return this.cache; } invalidate() { this.cache = null; this.timestamp = 0; } } const blockCache = new BlockNumberCache(); ``` ### Batch Requests Combine with other calls for efficiency: ```javascript const batch = [ { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }, { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 }, { jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 } ]; const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await response.json(); ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32603 | Internal error | Retry with exponential backoff | | -32005 | Rate limit exceeded | Implement rate limiting client-side | | -32000 | Execution reverted | Check node sync status | ```javascript async function safeGetBlockNumber(maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await provider.getBlockNumber(); } catch (error) { if (error.code === -32005) { // Rate limited, wait exponentially await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } else if (i === maxRetries - 1) { throw error; } } } } ``` --- ## eth_call - Execute Smart Contract Calls # eth_call :::tip Save 80% on `eth_call` Requests **Alchemy** = $11.70 per million `eth_call` requests **Quicknode** = $12.40 per million `eth_call` requests **Dwellir** = $2 per million `eth_call` requests Quicknode is **6X more expensive** for `eth_call`s! [Switch to Dwellir today →](https://dashboard.dwellir.com/register) ::: Executes a new message call immediately without creating a transaction on the blockchain. Used for reading smart contract state. ## When to Use This Method `eth_call` is essential for: - **Reading Contract State** - Query view/pure functions - **Simulating Transactions** - Test execution without gas costs - **DeFi Integrations** - Check prices, balances, allowances - **Complex Queries** - Execute multi-step contract logic ## Parameters 1. **Transaction Object** - `from` - (optional) Address executing the call - `to` - Contract address to call - `gas` - (optional) Gas limit for the call - `gasPrice` - (optional) Gas price in wei - `value` - (optional) Value to send in wei - `data` - Encoded function call data 2. **Block Parameter** - `QUANTITY|TAG` - `"latest"` - Most recent block - `"pending"` - Pending state - Block number in hex ```json { "jsonrpc": "2.0", "method": "eth_call", "params": [ { "to": "0x6B175474E89094C44Da98b954EedeAC495271d0F", "data": "0x70a08231000000000000000000000000742d35cc6634c0532925a3b844bc9e7595f0beb" }, "latest" ], "id": 1 } ``` ## Returns `DATA` - The return value of the executed contract function. ## Implementation Examples ```javascript const provider = new JsonRpcProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); // ERC20 ABI for common functions const ERC20_ABI = [ "function balanceOf(address owner) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function totalSupply() view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)", "function name() view returns (string)" ]; // Read ERC20 token balance async function getTokenBalance(tokenAddress, walletAddress) { const contract = new Contract(tokenAddress, ERC20_ABI, provider); const balance = await contract.balanceOf(walletAddress); const decimals = await contract.decimals(); const symbol = await contract.symbol(); return { raw: balance.toString(), formatted: (Number(balance) / Math.pow(10, decimals)).toFixed(4), symbol: symbol }; } // Direct eth_call for custom encoding async function directCall(to, data) { const result = await provider.call({ to: to, data: data }); return result; } // Simulate transaction without sending async function simulateTransaction(from, to, value, data) { try { const result = await provider.call({ from: from, to: to, value: value, data: data, gasLimit: 3000000 // High limit for simulation }); return { success: true, result: result }; } catch (error) { return { success: false, error: error.message }; } } ``` ```python from web3 import Web3 from eth_abi import encode, decode w3 = Web3(Web3.HTTPProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY')) def call_contract_function(contract_address, function_signature, params): """Generic contract call function""" # Encode function call function_selector = w3.keccak(text=function_signature)[:4] encoded_params = encode(params['types'], params['values']) data = function_selector + encoded_params # Make the call result = w3.eth.call({ 'to': contract_address, 'data': data }) return result def get_erc20_balance(token_address, wallet_address): """Get ERC20 token balance""" # balanceOf(address) selector function_signature = "balanceOf(address)" function_selector = w3.keccak(text=function_signature)[:4].hex() # Encode address parameter encoded_address = wallet_address[2:].lower().zfill(64) data = function_selector + encoded_address # Make the call result = w3.eth.call({ 'to': token_address, 'data': data }) # Decode result balance = int(result.hex(), 16) return balance def batch_token_balances(token_addresses, wallet_address): """Get multiple token balances efficiently""" balances = {} for token in token_addresses: try: balance = get_erc20_balance(token, wallet_address) balances[token] = balance except Exception as e: balances[token] = {'error': str(e)} return balances ``` ## Common Use Cases ### 1. DeFi Price Queries ```javascript // Uniswap V3 Pool Price Query async function getPoolPrice(poolAddress) { const poolABI = [ "function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked)", "function token0() view returns (address)", "function token1() view returns (address)" ]; const pool = new Contract(poolAddress, poolABI, provider); const [slot0, token0, token1] = await Promise.all([ pool.slot0(), pool.token0(), pool.token1() ]); // Calculate price from sqrtPriceX96 const sqrtPriceX96 = slot0.sqrtPriceX96; const price = (Number(sqrtPriceX96) / (2 ** 96)) ** 2; return { token0: token0, token1: token1, price: price, tick: slot0.tick }; } ``` ### 2. Multi-Contract Queries ```javascript // Batch multiple contract calls async function multicall(calls) { const multicallABI = [ "function aggregate(tuple(address target, bytes callData)[] calls) view returns (uint256 blockNumber, bytes[] returnData)" ]; const multicallAddress = "0xcA11bde05977b3631167028862bE2a173976CA11"; // Centrifuge Multicall3 const multicall = new Contract(multicallAddress, multicallABI, provider); const results = await multicall.aggregate(calls); return results.returnData; } ``` ### 3. Access Control Checks ```javascript // Check permissions before transaction async function checkPermissions(contractAddress, userAddress, role) { const accessControlABI = [ "function hasRole(bytes32 role, address account) view returns (bool)", "function getRoleAdmin(bytes32 role) view returns (bytes32)" ]; const contract = new Contract(contractAddress, accessControlABI, provider); const hasRole = await contract.hasRole(role, userAddress); return hasRole; } ``` ## Error Handling | Error Code | Description | Solution | |------------|-------------|----------| | -32000 | Execution reverted | Check function requirements | | -32602 | Invalid parameters | Verify data encoding | | -32015 | VM execution error | Check contract logic | ```javascript async function safeCall(to, data) { try { const result = await provider.call({ to, data }); return { success: true, data: result }; } catch (error) { if (error.message.includes('revert')) { // Try to decode revert reason const reason = error.data?.replace('0x08c379a0', ''); if (reason) { const decoded = ethers.utils.toUtf8String('0x' + reason.slice(8)); return { success: false, error: decoded }; } } return { success: false, error: error.message }; } } ``` *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_chainId - Get chain ID # eth_chainId Get chain ID on the Centrifuge network. ## Parameters Varies by method. Please refer to the official [Centrifuge JSON-RPC: eth_chainId](https://ethereum.org/developers/docs/apis/json-rpc/#eth_chainid) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1" } ``` **Note:** Chain ID 1 (0x1 in hexadecimal) identifies the Centrifuge mainnet. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_coinbase - Get coinbase address(Centrifuge) # eth_coinbase Get coinbase address on the Centrifuge network. ## Parameters Varies by method. Please refer to the official [Centrifuge JSON-RPC: eth_coinbase](https://ethereum.org/developers/docs/apis/json-rpc/#eth_coinbase) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_coinbase", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_coinbase', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_estimateGas - Estimate Transaction Gas # eth_estimateGas Generates and returns an estimate of how much gas is necessary to allow the transaction to complete. The transaction will not be added to the blockchain. ## When to Use This Method `eth_estimateGas` is crucial for: - **Transaction Preparation** - Calculate gas limits before sending - **Cost Estimation** - Preview transaction fees for users - **Gas Optimization** - Find optimal gas usage for complex operations - **Error Prevention** - Detect failures before broadcasting ## Parameters 1. **Transaction Object** - `from` - (optional) Address sending the transaction - `to` - Address of receiver or contract - `gas` - (optional) Gas limit for estimation - `gasPrice` - (optional) Gas price in wei - `value` - (optional) Value to send in wei - `data` - (optional) Hash of method signature and encoded parameters 2. **Block Parameter** - `QUANTITY|TAG` (optional) - `"latest"` - Most recent block (default) - `"pending"` - Pending state - Block number in hex ```json { "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [ { "from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "value": "0x9184e72a", "data": "0xd46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675" } ], "id": 1 } ``` ## Returns `QUANTITY` - The estimated gas amount in hexadecimal. ## Implementation Examples ```javascript const provider = new JsonRpcProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); // Gas estimation utility class GasEstimator { constructor(provider) { this.provider = provider; this.cache = new Map(); } async estimateETHTransfer(from, to, value) { try { const gasEstimate = await this.provider.estimateGas({ from: from, to: to, value: parseEther(value) }); // Add 10% buffer for safety const gasWithBuffer = gasEstimate * 110n / 100n; // Get current gas prices const feeData = await this.provider.getFeeData(); // Calculate costs const estimatedCost = gasWithBuffer * feeData.gasPrice; const estimatedCostEIP1559 = gasWithBuffer * feeData.maxFeePerGas; return { gasLimit: gasWithBuffer.toString(), gasPrice: feeData.gasPrice.toString(), maxFeePerGas: feeData.maxFeePerGas.toString(), maxPriorityFeePerGas: feeData.maxPriorityFeePerGas.toString(), estimatedCostWei: estimatedCost.toString(), estimatedCostETH: ethers.formatEther(estimatedCost), estimatedCostEIP1559Wei: estimatedCostEIP1559.toString(), estimatedCostEIP1559ETH: ethers.formatEther(estimatedCostEIP1559) }; } catch (error) { throw new Error(`Gas estimation failed: ${error.message}`); } } async estimateContractCall(contractAddress, abi, method, params, from) { const contract = new Contract(contractAddress, abi, this.provider); try { // Build transaction const tx = await contract[method].populateTransaction(...params); tx.from = from; // Estimate gas const gasEstimate = await this.provider.estimateGas(tx); // Get L1 fee estimate for Centrifuge Mainnet const l1FeeEstimate = await this.estimateL1Fee(tx); // Calculate total with buffer const gasWithBuffer = gasEstimate * 115n / 100n; // 15% buffer for contracts const feeData = await this.provider.getFeeData(); const l2Cost = gasWithBuffer * feeData.maxFeePerGas; const totalCost = l2Cost + l1FeeEstimate; return { gasLimit: gasWithBuffer.toString(), l2GasEstimate: gasEstimate.toString(), l1FeeEstimate: l1FeeEstimate.toString(), maxFeePerGas: feeData.maxFeePerGas.toString(), l2CostWei: l2Cost.toString(), l2CostETH: ethers.formatEther(l2Cost), totalCostWei: totalCost.toString(), totalCostETH: ethers.formatEther(totalCost), method: method, contract: contractAddress }; } catch (error) { // Parse revert reason if available if (error.data) { const reason = this.parseRevertReason(error.data); throw new Error(`Estimation failed: ${reason}`); } throw error; } } async estimateL1Fee(transaction) { // Centrifuge Mainnet specific - estimate L1 data posting fee try { // This would call a Ethereum-specific method if available // For now, estimate based on transaction size const txData = JSON.stringify(transaction); const dataSize = new Blob([txData]).size; // Rough estimate: ~16 gas per byte on L1 const l1GasEstimate = BigInt(dataSize * 16); const l1GasPrice = await this.provider.getGasPrice(); // L1 gas price return l1GasEstimate * l1GasPrice / 10n; // Adjusted for L2 economics } catch { return 0n; } } parseRevertReason(data) { if (typeof data === 'string' && data.startsWith('0x08c379a0')) { // Standard revert string const reason = ethers.AbiCoder.defaultAbiCoder().decode( ['string'], '0x' + data.slice(10) )[0]; return reason; } return 'Unknown error'; } async batchEstimate(transactions) { const estimates = []; for (const tx of transactions) { try { const gasEstimate = await this.provider.estimateGas(tx); const feeData = await this.provider.getFeeData(); estimates.push({ transaction: tx, gasLimit: gasEstimate.toString(), estimatedCost: (gasEstimate * feeData.maxFeePerGas).toString(), success: true }); } catch (error) { estimates.push({ transaction: tx, error: error.message, success: false }); } } return estimates; } async compareGasStrategies(transaction) { const gasEstimate = await this.provider.estimateGas(transaction); const feeData = await this.provider.getFeeData(); const block = await this.provider.getBlock('latest'); // Different gas strategies const strategies = { conservative: { gasLimit: gasEstimate * 150n / 100n, // 50% buffer maxFeePerGas: feeData.maxFeePerGas * 120n / 100n, maxPriorityFeePerGas: feeData.maxPriorityFeePerGas * 120n / 100n }, standard: { gasLimit: gasEstimate * 110n / 100n, // 10% buffer maxFeePerGas: feeData.maxFeePerGas, maxPriorityFeePerGas: feeData.maxPriorityFeePerGas }, aggressive: { gasLimit: gasEstimate * 105n / 100n, // 5% buffer maxFeePerGas: block.baseFeePerGas * 2n + feeData.maxPriorityFeePerGas / 2n, maxPriorityFeePerGas: feeData.maxPriorityFeePerGas / 2n } }; const results = {}; for (const [name, strategy] of Object.entries(strategies)) { const maxCost = strategy.gasLimit * strategy.maxFeePerGas; const likelyCost = strategy.gasLimit * (block.baseFeePerGas + strategy.maxPriorityFeePerGas); results[name] = { ...strategy, maxCostWei: maxCost.toString(), maxCostETH: ethers.formatEther(maxCost), likelyCostWei: likelyCost.toString(), likelyCostETH: ethers.formatEther(likelyCost) }; } return results; } } // Usage example const estimator = new GasEstimator(provider); // Estimate simple transfer const transferEstimate = await estimator.estimateETHTransfer( '0xYourAddress', '0xRecipientAddress', '0.1' ); console.log('Transfer cost:', transferEstimate.estimatedCostETH, 'ETH'); // Estimate contract interaction const contractEstimate = await estimator.estimateContractCall( '0xContractAddress', ['function transfer(address to, uint256 amount)'], 'transfer', ['0xRecipient', parseUnits('100', 18)], '0xYourAddress' ); console.log('Contract call cost:', contractEstimate.totalCostETH, 'ETH'); ``` ```python from web3 import Web3 from eth_utils import to_wei, from_wei from typing import Dict, Any, List, Optional w3 = Web3(Web3.HTTPProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY')) class GasCalculator: """Calculate and optimize gas for Centrifuge Mainnet transactions""" def __init__(self, w3_instance): self.w3 = w3_instance def estimate_transfer( self, from_address: str, to_address: str, value_eth: float ) -> Dict[str, Any]: """Estimate gas for ETH transfer""" try: # Build transaction transaction = { 'from': from_address, 'to': to_address, 'value': to_wei(value_eth, 'ether') } # Estimate gas gas_estimate = self.w3.eth.estimate_gas(transaction) # Add buffer gas_limit = int(gas_estimate * 1.1) # 10% buffer # Get current gas prices gas_price = self.w3.eth.gas_price base_fee = self.w3.eth.get_block('latest')['baseFeePerGas'] max_priority_fee = self.w3.eth.max_priority_fee # Calculate costs estimated_cost = gas_limit * gas_price max_cost = gas_limit * (base_fee * 2 + max_priority_fee) return { 'gas_estimate': gas_estimate, 'gas_limit': gas_limit, 'gas_price_gwei': from_wei(gas_price, 'gwei'), 'base_fee_gwei': from_wei(base_fee, 'gwei'), 'priority_fee_gwei': from_wei(max_priority_fee, 'gwei'), 'estimated_cost_eth': from_wei(estimated_cost, 'ether'), 'max_cost_eth': from_wei(max_cost, 'ether') } except Exception as e: return {'error': str(e)} def estimate_contract_call( self, from_address: str, to_address: str, data: str, value: int = 0 ) -> Dict[str, Any]: """Estimate gas for contract interaction""" transaction = { 'from': from_address, 'to': to_address, 'data': data, 'value': value } try: # Estimate gas gas_estimate = self.w3.eth.estimate_gas(transaction) # Estimate L1 fee component (Centrifuge specific) l1_fee = self._estimate_l1_fee(transaction) # Calculate with buffer gas_limit = int(gas_estimate * 1.15) # 15% buffer for contracts # Get fee data gas_price = self.w3.eth.gas_price # Calculate costs l2_cost = gas_limit * gas_price total_cost = l2_cost + l1_fee return { 'success': True, 'gas_estimate': gas_estimate, 'gas_limit': gas_limit, 'l1_fee_wei': l1_fee, 'l2_cost_wei': l2_cost, 'total_cost_wei': total_cost, 'total_cost_eth': from_wei(total_cost, 'ether'), 'breakdown': { 'l2_cost_eth': from_wei(l2_cost, 'ether'), 'l1_fee_eth': from_wei(l1_fee, 'ether') } } except Exception as e: # Try to extract revert reason error_msg = str(e) if 'execution reverted' in error_msg: return { 'success': False, 'error': 'Transaction would revert', 'reason': self._extract_revert_reason(error_msg) } return {'success': False, 'error': error_msg} def _estimate_l1_fee(self, transaction: Dict) -> int: """Estimate L1 data posting fee for Centrifuge Mainnet""" # Serialize transaction to estimate size tx_data = self.w3.to_json(transaction) data_size = len(tx_data.encode('utf-8')) # Centrifuge Mainnet formula approximation # L1 fee = data_size * l1_gas_price * scalar l1_gas_price = self.w3.eth.gas_price # Use current L1 gas price scalar = 0.684 # Centrifuge Mainnet scalar (this changes over time) l1_fee = int(data_size * 16 * l1_gas_price * scalar) return l1_fee def _extract_revert_reason(self, error_msg: str) -> str: """Extract revert reason from error message""" # Common patterns if 'insufficient balance' in error_msg.lower(): return 'Insufficient balance' elif 'transfer amount exceeds allowance' in error_msg.lower(): return 'Transfer amount exceeds allowance' elif 'transfer amount exceeds balance' in error_msg.lower(): return 'Transfer amount exceeds balance' # Try to extract custom revert message if '0x08c379a0' in error_msg: # Standard revert string try: start = error_msg.index('0x08c379a0') hex_msg = error_msg[start:start+138] # Standard length # Decode would go here return 'Contract reverted' except: pass return 'Unknown revert reason' def optimize_gas_settings( self, transaction: Dict, speed: str = 'standard' ) -> Dict[str, Any]: """Get optimized gas settings based on network conditions""" # Get current network state latest_block = self.w3.eth.get_block('latest') base_fee = latest_block['baseFeePerGas'] # Get gas estimate gas_estimate = self.w3.eth.estimate_gas(transaction) # Speed presets presets = { 'slow': { 'buffer': 1.05, 'priority_multiplier': 0.8 }, 'standard': { 'buffer': 1.1, 'priority_multiplier': 1.0 }, 'fast': { 'buffer': 1.2, 'priority_multiplier': 1.5 }, 'instant': { 'buffer': 1.3, 'priority_multiplier': 2.0 } } preset = presets.get(speed, presets['standard']) # Calculate optimized settings gas_limit = int(gas_estimate * preset['buffer']) max_priority_fee = int( self.w3.eth.max_priority_fee * preset['priority_multiplier'] ) max_fee_per_gas = base_fee * 2 + max_priority_fee # Calculate estimated cost estimated_cost = gas_limit * (base_fee + max_priority_fee) max_cost = gas_limit * max_fee_per_gas return { 'speed': speed, 'gas_limit': gas_limit, 'max_fee_per_gas': max_fee_per_gas, 'max_priority_fee_per_gas': max_priority_fee, 'estimated_cost_eth': from_wei(estimated_cost, 'ether'), 'max_cost_eth': from_wei(max_cost, 'ether'), 'estimated_confirmation_time': self._estimate_confirmation_time(speed) } def _estimate_confirmation_time(self, speed: str) -> str: """Estimate confirmation time based on speed setting""" times = { 'slow': '2-5 minutes', 'standard': '15-30 seconds', 'fast': '5-15 seconds', 'instant': '< 5 seconds' } return times.get(speed, 'Unknown') def batch_estimate(self, transactions: List[Dict]) -> List[Dict[str, Any]]: """Estimate gas for multiple transactions""" results = [] total_gas = 0 total_cost = 0 for i, tx in enumerate(transactions): try: gas_estimate = self.w3.eth.estimate_gas(tx) gas_price = self.w3.eth.gas_price cost = gas_estimate * gas_price results.append({ 'index': i, 'gas_estimate': gas_estimate, 'cost_wei': cost, 'cost_eth': from_wei(cost, 'ether'), 'success': True }) total_gas += gas_estimate total_cost += cost except Exception as e: results.append({ 'index': i, 'error': str(e), 'success': False }) return { 'estimates': results, 'summary': { 'total_gas': total_gas, 'total_cost_wei': total_cost, 'total_cost_eth': from_wei(total_cost, 'ether'), 'successful': len([r for r in results if r['success']]), 'failed': len([r for r in results if not r['success']]) } } # Usage examples calculator = GasCalculator(w3) # Estimate ETH transfer transfer_estimate = calculator.estimate_transfer( '0xFromAddress', '0xToAddress', 0.1 # 0.1 ETH ) print(f"Gas needed: {transfer_estimate['gas_limit']}") print(f"Estimated cost: {transfer_estimate['estimated_cost_eth']} ETH") # Estimate contract call contract_estimate = calculator.estimate_contract_call( '0xFromAddress', '0xContractAddress', '0xa9059cbb000000000000000000000000....' # transfer function data ) print(f"Total cost: {contract_estimate['total_cost_eth']} ETH") # Get optimized settings optimized = calculator.optimize_gas_settings( {'from': '0xFrom', 'to': '0xTo', 'value': to_wei(0.1, 'ether')}, speed='fast' ) print(f"Optimized gas limit: {optimized['gas_limit']}") print(f"Max fee: {optimized['max_fee_per_gas']} wei") ``` ## Common Use Cases ### 1. Pre-Transaction Validation ```javascript // Validate transaction before sending async function validateTransaction(from, to, value, data) { try { const gasEstimate = await provider.estimateGas({ from: from, to: to, value: value, data: data }); // Check if account has enough balance const balance = await provider.getBalance(from); const feeData = await provider.getFeeData(); const maxCost = value + (gasEstimate * feeData.maxFeePerGas); if (balance < maxCost) { return { valid: false, reason: 'Insufficient balance', required: ethers.formatEther(maxCost), available: ethers.formatEther(balance) }; } return { valid: true, gasLimit: gasEstimate.toString(), estimatedFee: ethers.formatEther(gasEstimate * feeData.gasPrice) }; } catch (error) { return { valid: false, reason: error.message }; } } ``` ### 2. Dynamic Gas Pricing UI ```javascript // Real-time gas price updates for UI class GasPriceMonitor { constructor(provider) { this.provider = provider; this.listeners = []; } async getCurrentPrices() { const [feeData, block] = await Promise.all([ this.provider.getFeeData(), this.provider.getBlock('latest') ]); return { slow: { maxFeePerGas: feeData.maxFeePerGas * 90n / 100n, maxPriorityFeePerGas: feeData.maxPriorityFeePerGas * 80n / 100n, estimatedTime: '2-5 minutes' }, standard: { maxFeePerGas: feeData.maxFeePerGas, maxPriorityFeePerGas: feeData.maxPriorityFeePerGas, estimatedTime: '15-30 seconds' }, fast: { maxFeePerGas: feeData.maxFeePerGas * 120n / 100n, maxPriorityFeePerGas: feeData.maxPriorityFeePerGas * 150n / 100n, estimatedTime: '5-15 seconds' }, baseFee: block.baseFeePerGas }; } async estimateForTransaction(tx, speed = 'standard') { const prices = await this.getCurrentPrices(); const gasEstimate = await this.provider.estimateGas(tx); const settings = prices[speed]; return { gasLimit: gasEstimate, ...settings, estimatedCost: ethers.formatEther(gasEstimate * settings.maxFeePerGas), maxCost: ethers.formatEther(gasEstimate * settings.maxFeePerGas) }; } } ``` ### 3. Batch Operation Optimization ```javascript // Optimize gas for batch operations async function optimizeBatchTransactions(transactions) { const estimates = []; let totalGas = 0n; // Estimate individually for (const tx of transactions) { const estimate = await provider.estimateGas(tx); estimates.push(estimate); totalGas += estimate; } // Check if multicall is more efficient const multicallEstimate = await estimateMulticall(transactions); if (multicallEstimate < totalGas * 90n / 100n) { return { method: 'multicall', gasLimit: multicallEstimate, savings: ethers.formatUnits(totalGas - multicallEstimate, 'gwei') }; } return { method: 'individual', gasLimits: estimates, totalGas: totalGas }; } ``` ## Error Handling | Error Type | Description | Solution | |------------|-------------|----------| | Execution reverted | Transaction would fail | Check contract requirements | | Gas required exceeds limit | Block gas limit exceeded | Split into smaller transactions | | Insufficient funds | Not enough ETH for gas | Add funds or reduce gas price | ```javascript async function safeEstimate(transaction) { try { const estimate = await provider.estimateGas(transaction); return { success: true, gasLimit: estimate }; } catch (error) { // Parse error for useful information const errorString = error.toString(); if (errorString.includes('execution reverted')) { // Try to get revert reason try { await provider.call(transaction); } catch (callError) { return { success: false, error: 'Transaction would revert', reason: callError.reason || 'Unknown reason' }; } } if (errorString.includes('gas required exceeds')) { return { success: false, error: 'Gas limit exceeded', suggestion: 'Try splitting into smaller operations' }; } return { success: false, error: error.message }; } } ``` *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_feeHistory - Get historical gas prices # eth_feeHistory Returns historical gas information for the Centrifuge network. This method is useful for gas price estimation and understanding network congestion patterns over time. ## Parameters 1. `QUANTITY` - Number of blocks to retrieve. Must be between 1 and 1024. 2. `QUANTITY|TAG` - Highest block number to retrieve from (or "latest", "earliest", "pending"). 3. `Array` - Array of percentile values (0-100) to retrieve priority fees for. ## Returns `Object` containing: - `oldestBlock`: `QUANTITY` - Lowest block number returned - `baseFeePerGas`: `Array` - Array of base fees per gas for each block - `gasUsedRatio`: `Array` - Array of gas used ratios for each block (0.0 to 1.0) - `reward`: `Array` - Array of arrays containing priority fees at requested percentiles ## Implementation Example ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x4", "latest", [25, 50, 75]], "id": 1 }' ``` ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_feeHistory', params: ['0x4', 'latest', [25, 50, 75]], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": { "oldestBlock": "0x1a2b3c4", "baseFeePerGas": [ "0x3b9aca00", "0x3b9aca00", "0x3b9aca00", "0x3b9aca00" ], "gasUsedRatio": [0.5, 0.6, 0.4, 0.7], "reward": [ ["0x77359400", "0x77359400", "0x77359400"], ["0x77359400", "0x77359400", "0x77359400"], ["0x77359400", "0x77359400", "0x77359400"] ] } } ``` This example shows fee history for 4 blocks with priority fee percentiles at 25%, 50%, and 75%. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_gasPrice - Get Current Gas Price # eth_gasPrice Returns the current gas price in wei. This represents the median gas price from recent blocks on Centrifuge Mainnet. ## When to Use This Method `eth_gasPrice` is essential for: - **Transaction Pricing** - Set appropriate gas prices for transactions - **Fee Estimation** - Calculate transaction costs for users - **Gas Strategy** - Optimize transaction speed vs cost - **Market Monitoring** - Track network congestion levels ## Parameters None - This method takes no parameters. ```json { "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 } ``` ## Returns `QUANTITY` - Current gas price in wei (hexadecimal). ## Implementation Examples ```javascript const provider = new JsonRpcProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); // Gas price monitoring and optimization class GasPriceManager { constructor(provider) { this.provider = provider; this.priceHistory = []; this.updateInterval = null; } async getCurrentGasPrice() { const gasPrice = await this.provider.getGasPrice(); return { wei: gasPrice.toString(), gwei: formatGwei(gasPrice), eth: formatEther(gasPrice), hex: gasPrice.toHexString(), timestamp: Date.now() }; } async getGasPriceWithContext() { // Get multiple data points for context const [gasPrice, feeData, block] = await Promise.all([ this.provider.getGasPrice(), this.provider.getFeeData(), this.provider.getBlock('latest') ]); // Calculate percentiles for better pricing const baseFee = block.baseFeePerGas || 0n; const priorityFee = feeData.maxPriorityFeePerGas || 0n; return { current: { gasPrice: formatGwei(gasPrice), unit: 'gwei' }, eip1559: { baseFee: formatGwei(baseFee), priorityFee: formatGwei(priorityFee), maxFeePerGas: formatGwei(feeData.maxFeePerGas), recommended: formatGwei(baseFee + priorityFee) }, speeds: { slow: formatGwei(gasPrice * 90n / 100n), standard: formatGwei(gasPrice), fast: formatGwei(gasPrice * 120n / 100n), instant: formatGwei(gasPrice * 150n / 100n) }, networkCongestion: this.assessCongestion(baseFee) }; } assessCongestion(baseFee) { const baseGwei = Number(formatGwei(baseFee)); if (baseGwei < 0.1) return 'very low'; if (baseGwei < 0.5) return 'low'; if (baseGwei < 1) return 'moderate'; if (baseGwei < 5) return 'high'; return 'very high'; } async calculateTransactionCost(gasLimit, gasPriceMultiplier = 1) { const gasPrice = await this.provider.getGasPrice(); const adjustedPrice = gasPrice * BigInt(Math.floor(gasPriceMultiplier * 100)) / 100n; const cost = adjustedPrice * BigInt(gasLimit); return { gasLimit: gasLimit.toString(), gasPrice: formatGwei(adjustedPrice), totalCostWei: cost.toString(), totalCostGwei: formatGwei(cost), totalCostETH: formatEther(cost), dollarValue: await this.estimateUSDValue(cost) }; } async estimateUSDValue(costWei) { // This would typically fetch ETH price from an oracle // For demonstration, using a static value const ethPrice = 3000; // USD const costETH = Number(formatEther(costWei)); return (costETH * ethPrice).toFixed(4); } startMonitoring(intervalMs = 5000, callback) { this.stopMonitoring(); this.updateInterval = setInterval(async () => { const price = await this.getCurrentGasPrice(); this.priceHistory.push(price); // Keep only last 100 entries if (this.priceHistory.length > 100) { this.priceHistory.shift(); } if (callback) { callback(price, this.getStatistics()); } }, intervalMs); } stopMonitoring() { if (this.updateInterval) { clearInterval(this.updateInterval); this.updateInterval = null; } } getStatistics() { if (this.priceHistory.length === 0) return null; const prices = this.priceHistory.map(p => BigInt(p.wei)); const sum = prices.reduce((a, b) => a + b, 0n); const avg = sum / BigInt(prices.length); const min = prices.reduce((a, b) => a < b ? a : b); const max = prices.reduce((a, b) => a > b ? a : b); return { samples: prices.length, average: formatGwei(avg), minimum: formatGwei(min), maximum: formatGwei(max), current: formatGwei(prices[prices.length - 1]), trend: this.calculateTrend() }; } calculateTrend() { if (this.priceHistory.length < 2) return 'stable'; const recent = this.priceHistory.slice(-10); const older = this.priceHistory.slice(-20, -10); if (older.length === 0) return 'stable'; const recentAvg = recent.reduce((sum, p) => sum + BigInt(p.wei), 0n) / BigInt(recent.length); const olderAvg = older.reduce((sum, p) => sum + BigInt(p.wei), 0n) / BigInt(older.length); const change = Number(recentAvg - olderAvg) / Number(olderAvg) * 100; if (change > 10) return 'increasing'; if (change < -10) return 'decreasing'; return 'stable'; } async waitForLowerGas(targetGwei, timeoutMs = 60000) { const startTime = Date.now(); while (Date.now() - startTime < timeoutMs) { const current = await this.getCurrentGasPrice(); if (parseFloat(current.gwei) <= targetGwei) { return { success: true, gasPrice: current, waitTime: Date.now() - startTime }; } await new Promise(resolve => setTimeout(resolve, 2000)); } return { success: false, reason: 'timeout', currentPrice: await this.getCurrentGasPrice() }; } } // Usage examples const gasPriceManager = new GasPriceManager(provider); // Get current gas price const currentPrice = await gasPriceManager.getCurrentGasPrice(); console.log(`Current gas price: ${currentPrice.gwei} gwei`); // Get comprehensive gas data const gasData = await gasPriceManager.getGasPriceWithContext(); console.log('Network congestion:', gasData.networkCongestion); console.log('Recommended speeds:', gasData.speeds); // Calculate transaction cost const txCost = await gasPriceManager.calculateTransactionCost(21000); // ETH transfer console.log(`Transaction cost: ${txCost.totalCostETH} ETH (~$${txCost.dollarValue})`); // Monitor gas prices gasPriceManager.startMonitoring(5000, (price, stats) => { console.log(`Gas: ${price.gwei} gwei | Trend: ${stats?.trend}`); }); // Wait for lower gas const result = await gasPriceManager.waitForLowerGas(0.5, 30000); if (result.success) { console.log('Gas price dropped to target!'); } ``` ```python from web3 import Web3 from eth_utils import from_wei from typing import Dict, List, Optional, Callable from datetime import datetime, timedelta w3 = Web3(Web3.HTTPProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY')) class GasPriceAnalyzer: """Analyze and optimize gas prices on Centrifuge Mainnet""" def __init__(self, w3_instance): self.w3 = w3_instance self.price_history = [] self.monitoring = False def get_current_gas_price(self) -> Dict[str, any]: """Get current gas price in multiple units""" gas_price = self.w3.eth.gas_price return { 'wei': gas_price, 'gwei': from_wei(gas_price, 'gwei'), 'eth': from_wei(gas_price, 'ether'), 'hex': hex(gas_price), 'timestamp': datetime.now().isoformat() } def get_comprehensive_gas_data(self) -> Dict[str, any]: """Get comprehensive gas pricing data""" # Current gas price gas_price = self.w3.eth.gas_price # Latest block for base fee latest_block = self.w3.eth.get_block('latest') base_fee = latest_block.get('baseFeePerGas', 0) # Priority fee estimate try: priority_fee = self.w3.eth.max_priority_fee except: priority_fee = gas_price // 10 # Fallback estimate # Calculate different speed options speeds = { 'slow': { 'gas_price_gwei': from_wei(int(gas_price * 0.9), 'gwei'), 'max_fee_gwei': from_wei(int((base_fee * 2 + priority_fee) * 0.9), 'gwei'), 'priority_fee_gwei': from_wei(int(priority_fee * 0.8), 'gwei'), 'estimated_time': '2-5 minutes' }, 'standard': { 'gas_price_gwei': from_wei(gas_price, 'gwei'), 'max_fee_gwei': from_wei(base_fee * 2 + priority_fee, 'gwei'), 'priority_fee_gwei': from_wei(priority_fee, 'gwei'), 'estimated_time': '15-30 seconds' }, 'fast': { 'gas_price_gwei': from_wei(int(gas_price * 1.2), 'gwei'), 'max_fee_gwei': from_wei(int((base_fee * 2 + priority_fee) * 1.2), 'gwei'), 'priority_fee_gwei': from_wei(int(priority_fee * 1.5), 'gwei'), 'estimated_time': '5-15 seconds' }, 'instant': { 'gas_price_gwei': from_wei(int(gas_price * 1.5), 'gwei'), 'max_fee_gwei': from_wei(int((base_fee * 2 + priority_fee) * 1.5), 'gwei'), 'priority_fee_gwei': from_wei(int(priority_fee * 2), 'gwei'), 'estimated_time': '< 5 seconds' } } return { 'current_gas_price_gwei': from_wei(gas_price, 'gwei'), 'base_fee_gwei': from_wei(base_fee, 'gwei'), 'priority_fee_gwei': from_wei(priority_fee, 'gwei'), 'speeds': speeds, 'network_congestion': self._assess_congestion(base_fee), 'block_number': latest_block['number'], 'timestamp': datetime.now().isoformat() } def _assess_congestion(self, base_fee: int) -> str: """Assess network congestion based on base fee""" base_gwei = from_wei(base_fee, 'gwei') if base_gwei < 0.1: return 'very low' elif base_gwei < 0.5: return 'low' elif base_gwei < 1: return 'moderate' elif base_gwei < 5: return 'high' else: return 'very high' def calculate_transaction_cost( self, gas_limit: int, speed: str = 'standard' ) -> Dict[str, any]: """Calculate transaction cost at different speeds""" gas_data = self.get_comprehensive_gas_data() speed_data = gas_data['speeds'].get(speed, gas_data['speeds']['standard']) gas_price_wei = self.w3.to_wei(speed_data['gas_price_gwei'], 'gwei') total_cost_wei = gas_price_wei * gas_limit # Estimate USD value (would need oracle in production) eth_price_usd = 3000 # Example static price total_cost_eth = from_wei(total_cost_wei, 'ether') total_cost_usd = total_cost_eth * eth_price_usd return { 'gas_limit': gas_limit, 'gas_price_gwei': speed_data['gas_price_gwei'], 'speed': speed, 'total_cost_wei': total_cost_wei, 'total_cost_gwei': from_wei(total_cost_wei, 'gwei'), 'total_cost_eth': total_cost_eth, 'total_cost_usd': round(total_cost_usd, 4), 'estimated_time': speed_data['estimated_time'] } def analyze_historical_prices( self, duration_minutes: int = 60 ) -> Dict[str, any]: """Analyze historical gas prices""" if not self.price_history: return {'error': 'No historical data available'} # Filter data for requested duration cutoff_time = datetime.now() - timedelta(minutes=duration_minutes) recent_prices = [ p for p in self.price_history if datetime.fromisoformat(p['timestamp']) > cutoff_time ] if not recent_prices: return {'error': 'No data for requested period'} prices_gwei = [p['gwei'] for p in recent_prices] return { 'period_minutes': duration_minutes, 'samples': len(prices_gwei), 'average_gwei': round(statistics.mean(prices_gwei), 4), 'median_gwei': round(statistics.median(prices_gwei), 4), 'min_gwei': min(prices_gwei), 'max_gwei': max(prices_gwei), 'std_dev_gwei': round(statistics.stdev(prices_gwei), 4) if len(prices_gwei) > 1 else 0, 'volatility': self._calculate_volatility(prices_gwei), 'trend': self._calculate_trend(prices_gwei) } def _calculate_volatility(self, prices: List[float]) -> str: """Calculate price volatility""" if len(prices) < 2: return 'unknown' std_dev = statistics.stdev(prices) mean = statistics.mean(prices) cv = (std_dev / mean) * 100 if mean > 0 else 0 if cv < 10: return 'low' elif cv < 25: return 'moderate' elif cv < 50: return 'high' else: return 'very high' def _calculate_trend(self, prices: List[float]) -> str: """Calculate price trend""" if len(prices) < 3: return 'stable' first_third = prices[:len(prices)//3] last_third = prices[-len(prices)//3:] avg_first = statistics.mean(first_third) avg_last = statistics.mean(last_third) change_percent = ((avg_last - avg_first) / avg_first) * 100 if avg_first > 0 else 0 if change_percent > 10: return 'increasing' elif change_percent < -10: return 'decreasing' else: return 'stable' async def monitor_prices( self, interval_seconds: int = 5, duration_minutes: int = 60, callback: Optional[Callable] = None ): """Monitor gas prices over time""" self.monitoring = True end_time = datetime.now() + timedelta(minutes=duration_minutes) while self.monitoring and datetime.now() < end_time: price_data = self.get_current_gas_price() self.price_history.append(price_data) # Keep only recent history (last 1000 entries) if len(self.price_history) > 1000: self.price_history = self.price_history[-1000:] if callback: stats = self.analyze_historical_prices(5) # Last 5 minutes callback(price_data, stats) await asyncio.sleep(interval_seconds) def stop_monitoring(self): """Stop price monitoring""" self.monitoring = False def get_optimal_send_time( self, target_gwei: float, lookback_minutes: int = 60 ) -> Dict[str, any]: """Predict optimal time to send transaction""" analysis = self.analyze_historical_prices(lookback_minutes) if 'error' in analysis: return analysis current_price = self.get_current_gas_price()['gwei'] # Simple prediction based on trend if analysis['trend'] == 'decreasing': suggestion = 'Wait - prices are falling' estimated_wait = '5-10 minutes' elif analysis['trend'] == 'increasing': suggestion = 'Send now - prices are rising' estimated_wait = '0 minutes' else: if current_price <= target_gwei: suggestion = 'Send now - target price reached' estimated_wait = '0 minutes' elif current_price < analysis['average_gwei']: suggestion = 'Good time - below average' estimated_wait = '0 minutes' else: suggestion = 'Consider waiting' estimated_wait = '10-15 minutes' return { 'current_gwei': current_price, 'target_gwei': target_gwei, 'average_gwei': analysis['average_gwei'], 'trend': analysis['trend'], 'suggestion': suggestion, 'estimated_wait': estimated_wait } # Usage examples analyzer = GasPriceAnalyzer(w3) # Get current gas price current = analyzer.get_current_gas_price() print(f"Current gas price: {current['gwei']} gwei") # Get comprehensive data gas_data = analyzer.get_comprehensive_gas_data() print(f"Network congestion: {gas_data['network_congestion']}") print(f"Recommended for fast tx: {gas_data['speeds']['fast']['gas_price_gwei']} gwei") # Calculate costs eth_transfer_cost = analyzer.calculate_transaction_cost(21000, 'standard') print(f"ETH transfer cost: ${eth_transfer_cost['total_cost_usd']}") contract_cost = analyzer.calculate_transaction_cost(100000, 'fast') print(f"Contract call cost: {contract_cost['total_cost_eth']} ETH") # Get optimal send time optimal = analyzer.get_optimal_send_time(0.5, 30) print(f"Optimal send strategy: {optimal['suggestion']}") ``` ## Common Use Cases ### 1. Dynamic Fee Adjustment ```javascript // Dynamically adjust fees based on network conditions async function getOptimalGasPrice(urgency = 'standard') { const gasPrice = await provider.getGasPrice(); const block = await provider.getBlock('latest'); const baseFee = block.baseFeePerGas; const multipliers = { low: 0.9, standard: 1.0, high: 1.2, urgent: 1.5 }; const multiplier = multipliers[urgency] || 1.0; const adjustedPrice = gasPrice * BigInt(Math.floor(multiplier * 100)) / 100n; // For EIP-1559 transactions const maxPriorityFee = adjustedPrice - baseFee; const maxFeePerGas = baseFee * 2n + maxPriorityFee; return { legacy: { gasPrice: adjustedPrice, formatted: formatGwei(adjustedPrice) + ' gwei' }, eip1559: { maxFeePerGas: maxFeePerGas, maxPriorityFeePerGas: maxPriorityFee, formatted: { maxFee: formatGwei(maxFeePerGas) + ' gwei', priorityFee: formatGwei(maxPriorityFee) + ' gwei' } }, estimatedConfirmationBlocks: urgency === 'urgent' ? 1 : urgency === 'high' ? 2 : 3 }; } ``` ### 2. Gas Price Oracle ```javascript // Create a gas price oracle with caching class GasPriceOracle { constructor(provider, cacheTime = 5000) { this.provider = provider; this.cacheTime = cacheTime; this.cache = null; this.lastFetch = 0; } async getPrice() { const now = Date.now(); if (this.cache && (now - this.lastFetch) < this.cacheTime) { return this.cache; } const gasPrice = await this.provider.getGasPrice(); this.cache = { wei: gasPrice, gwei: formatGwei(gasPrice), timestamp: now }; this.lastFetch = now; return this.cache; } async getPriceWithRecommendations() { const price = await this.getPrice(); const gweiPrice = parseFloat(price.gwei); return { ...price, recommendations: { sendNow: gweiPrice < 1, waitSuggested: gweiPrice > 5, congestionLevel: gweiPrice < 0.5 ? 'low' : gweiPrice < 2 ? 'normal' : 'high' } }; } } ``` ### 3. Transaction Cost Calculator ```javascript // Calculate and display transaction costs async function calculateDetailedCosts(gasLimit) { const gasPrice = await provider.getGasPrice(); const ethPrice = 3000; // Would fetch from price feed const costs = { slow: gasPrice * 90n / 100n, standard: gasPrice, fast: gasPrice * 120n / 100n }; const results = {}; for (const [speed, price] of Object.entries(costs)) { const totalWei = price * BigInt(gasLimit); const totalETH = Number(formatEther(totalWei)); results[speed] = { gasPrice: formatGwei(price) + ' gwei', totalETH: totalETH.toFixed(6) + ' ETH', totalUSD: '$' + (totalETH * ethPrice).toFixed(2), percentOfTransfer: gasLimit === 21000 ? 'N/A' : ((Number(totalWei) / Number(parseEther('1'))) * 100).toFixed(3) + '%' }; } return results; } ``` ## Error Handling | Error Scenario | Description | Solution | |----------------|-------------|----------| | Network timeout | RPC connection issues | Retry with exponential backoff | | Invalid response | Malformed data from node | Validate response format | | Stale data | Cached price too old | Force refresh | ```javascript async function getRobustGasPrice(maxRetries = 3) { let lastError; for (let i = 0; i < maxRetries; i++) { try { const gasPrice = await provider.getGasPrice(); // Validate response if (!gasPrice || gasPrice === 0n) { throw new Error('Invalid gas price returned'); } // Sanity check - Centrifuge Mainnet shouldn't have extremely high gas const gweiPrice = Number(formatGwei(gasPrice)); if (gweiPrice > 1000) { console.warn('Unusually high gas price detected:', gweiPrice); } return gasPrice; } catch (error) { lastError = error; // Exponential backoff if (i < maxRetries - 1) { await new Promise(resolve => setTimeout(resolve, Math.pow(2, i) * 1000) ); } } } throw new Error(`Failed to get gas price after ${maxRetries} attempts: ${lastError.message}`); } ``` *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_getBalance - Query Account Balance # eth_getBalance Returns the ETH balance of a given address on Centrifuge Mainnet. ## When to Use This Method `eth_getBalance` is essential for: - **Wallet Applications** - Display user balances - **Transaction Validation** - Check if account has sufficient funds - **DeFi Applications** - Monitor collateral and liquidity - **Account Monitoring** - Track balance changes over time ## Parameters 1. **Address** - `DATA`, 20 bytes - The address to check balance for - Format: `0x` prefixed, 40 hex characters 2. **Block Parameter** - `QUANTITY|TAG` - `"latest"` - Most recent block (default) - `"earliest"` - Genesis block - `"pending"` - Pending state - `"safe"` - Latest safe block - `"finalized"` - Latest finalized block - Block number in hex format ```json { "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "latest" ], "id": 1 } ``` ## Returns `QUANTITY` - Integer of the current balance in wei. - **Type**: Hexadecimal string - **Unit**: Wei (1 ETH = 10^18 wei) - **Format**: `0x` prefixed ## Implementation Examples ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "latest" ], "id": 1 }' ``` ```javascript // Using ethers.js const provider = new JsonRpcProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); async function getBalance(address) { // Get balance in wei const balanceWei = await provider.getBalance(address); // Convert to ETH const balanceEth = formatEther(balanceWei); console.log(`Balance: ${balanceEth} ETH`); return balanceEth; } // Check multiple balances async function getMultipleBalances(addresses) { const balances = await Promise.all( addresses.map(async (addr) => { const balance = await provider.getBalance(addr); return { address: addr, balance: formatEther(balance) }; }) ); return balances; } ``` ```python from web3 import Web3 # Connect to Ethereum w3 = Web3(Web3.HTTPProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY')) def get_balance(address): # Get balance in wei balance_wei = w3.eth.get_balance(address) # Convert to ETH balance_eth = w3.from_wei(balance_wei, 'ether') print(f"Balance: {balance_eth} ETH") return balance_eth # Get balance at specific block def get_historical_balance(address, block_number): balance_wei = w3.eth.get_balance(address, block_identifier=block_number) return w3.from_wei(balance_wei, 'ether') # Monitor balance changes def monitor_balance(address, interval=2): last_balance = 0 while True: current_balance = w3.eth.get_balance(address) if current_balance != last_balance: change = current_balance - last_balance print(f"Balance changed: {w3.from_wei(change, 'ether')} ETH") last_balance = current_balance time.sleep(interval) ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-centrifuge.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045") // Get balance at latest block balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } // Convert wei to ETH ethValue := new(big.Float).Quo( new(big.Float).SetInt(balance), big.NewFloat(1e18), ) fmt.Printf("Balance: %f ETH\n", ethValue) } ``` ## Response Example ### Successful Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1a055690d9db80000" } ``` This represents `0x1a055690d9db80000` wei = 1.85 ETH ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32602, "message": "Invalid params: invalid address" } } ``` ## Common Use Cases ### 1. Wallet Balance Display Display formatted balance with USD value: ```javascript async function displayWalletBalance(address) { const provider = new JsonRpcProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); // Get ETH balance const balance = await provider.getBalance(address); const ethBalance = formatEther(balance); // Get ETH price (from your price oracle) const ethPrice = await getEthPrice(); // Implement this const usdValue = parseFloat(ethBalance) * ethPrice; return { eth: ethBalance, usd: usdValue.toFixed(2), formatted: `${ethBalance} ETH ($${usdValue.toFixed(2)})` }; } ``` ### 2. Transaction Pre-validation Check if account has enough balance for transaction: ```javascript async function canAffordTransaction(from, to, value, gasLimit, maxFeePerGas) { const balance = await provider.getBalance(from); // Calculate total cost const valueBigInt = BigInt(value); const gasCost = BigInt(gasLimit) * BigInt(maxFeePerGas); const totalCost = valueBigInt + gasCost; if (balance < totalCost) { const shortage = formatEther(totalCost - balance); throw new Error(`Insufficient balance. Need ${shortage} more ETH`); } return true; } ``` ### 3. Balance Change Detection Monitor account for balance changes: ```javascript class BalanceMonitor { constructor(provider, address) { this.provider = provider; this.address = address; this.lastBalance = null; } async start(callback, interval = 2000) { setInterval(async () => { const currentBalance = await this.provider.getBalance(this.address); if (this.lastBalance && currentBalance !== this.lastBalance) { const change = currentBalance - this.lastBalance; callback({ address: this.address, previousBalance: this.lastBalance, currentBalance, change, changeFormatted: formatEther(change) }); } this.lastBalance = currentBalance; }, interval); } } // Usage const monitor = new BalanceMonitor(provider, "0x..."); monitor.start((data) => { console.log(`Balance changed by ${data.changeFormatted} ETH`); }); ``` ### 4. Historical Balance Query Get balance at specific block: ```javascript async function getBalanceHistory(address, blocks) { const history = []; for (const blockNumber of blocks) { const balance = await provider.getBalance(address, blockNumber); const block = await provider.getBlock(blockNumber); history.push({ block: blockNumber, timestamp: block.timestamp, balance: formatEther(balance) }); } return history; } // Get balance every 1000 blocks async function getBalanceSnapshots(address, count = 10) { const currentBlock = await provider.getBlockNumber(); const blocks = []; for (let i = 0; i < count; i++) { blocks.push(currentBlock - (i * 1000)); } return getBalanceHistory(address, blocks); } ``` ## Performance Optimization ### Batch Balance Queries Query multiple balances efficiently: ```javascript async function batchGetBalances(addresses) { const batch = addresses.map((addr, i) => ({ jsonrpc: '2.0', method: 'eth_getBalance', params: [addr, 'latest'], id: i })); const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await response.json(); return results.map((r, i) => ({ address: addresses[i], balance: formatEther(BigInt(r.result)) })); } ``` ### Caching Strategy Implement smart caching for balance queries: ```javascript class BalanceCache { constructor(ttl = 5000) { this.cache = new Map(); this.ttl = ttl; } getCacheKey(address, block) { return `${address}-${block}`; } async getBalance(provider, address, block = 'latest') { const key = this.getCacheKey(address, block); const cached = this.cache.get(key); // Return cached if block is not 'latest' (immutable) if (cached && block !== 'latest') { return cached.balance; } // Check TTL for 'latest' block if (cached && block === 'latest') { if (Date.now() - cached.timestamp < this.ttl) { return cached.balance; } } // Fetch fresh balance const balance = await provider.getBalance(address, block); this.cache.set(key, { balance, timestamp: Date.now() }); return balance; } } ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32602 | Invalid address format | Ensure address is 40 hex chars with 0x prefix | | -32602 | Invalid block parameter | Use valid block tag or hex number | | -32000 | Account not found | Address may not exist on chain | ```javascript async function safeGetBalance(address) { try { // Validate address format if (!/^0x[a-fA-F0-9]{40}$/.test(address)) { throw new Error('Invalid address format'); } const balance = await provider.getBalance(address); return { success: true, balance: formatEther(balance) }; } catch (error) { console.error('Failed to get balance:', error); // Return zero for non-existent accounts if (error.code === -32000) { return { success: true, balance: '0' }; } return { success: false, error: error.message }; } } ``` *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_getBlockByHash - Get block Info by ha... # eth_getBlockByHash Retrieves comprehensive information about a block on Centrifuge Mainnet by its hash identifier, including header data, transaction lists, and execution metrics. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | string | Yes | The 32-byte block hash (66 characters with 0x prefix) | | `fullTransactionObjects` | boolean | Yes | When `true`, returns complete transaction objects. When `false`, returns only transaction hashes | ## Returns Returns a block object with the following fields: | Field | Type | Description | |-------|------|-------------| | `number` | string | Block number in hexadecimal | | `hash` | string | 32-byte block hash | | `parentHash` | string | Hash of the parent block | | `nonce` | string | Proof-of-work nonce (always 0x0000000000000000 on Centrifuge Mainnet) | | `sha3Uncles` | string | SHA3 hash of uncles data | | `logsBloom` | string | 256-byte bloom filter for block logs | | `transactionsRoot` | string | Root hash of the transaction trie | | `stateRoot` | string | Root hash of the final state trie | | `receiptsRoot` | string | Root hash of the receipts trie | | `miner` | string | Address receiving block rewards | | `difficulty` | string | Block difficulty (always 0x0 on Centrifuge Mainnet) | | `totalDifficulty` | string | Total chain difficulty up to this block | | `extraData` | string | Additional block-specific data | | `size` | string | Block size in bytes (hexadecimal) | | `gasLimit` | string | Maximum gas allowed in block | | `gasUsed` | string | Total gas consumed by all transactions | | `timestamp` | string | Unix timestamp of block creation | | `transactions` | array | Array of transaction hashes or full transaction objects | | `uncles` | array | Array of uncle block hashes (always empty on Centrifuge Mainnet) | | `baseFeePerGas` | string | Base fee per gas unit (EIP-1559) | | `withdrawals` | array | Validator withdrawals (if applicable) | | `withdrawalsRoot` | string | Root hash of withdrawals trie | ## Implementation Example ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0xba6064a55ed3dc3f34185d57dc000a63639302bf17f6eaf61c2f211d25f73a67", false ], "id": 1 }' ``` ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_getBlockByHash', params: [ '0xba6064a55ed3dc3f34185d57dc000a63639302bf17f6eaf61c2f211d25f73a67', false // Set to true for full transaction objects ], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ```python url = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY' headers = {'Content-Type': 'application/json'} payload = { "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0xba6064a55ed3dc3f34185d57dc000a63639302bf17f6eaf61c2f211d25f73a67", False # Set to True for full transaction objects ], "id": 1 } response = requests.post(url, headers=headers, data=json.dumps(payload)) print(response.json()['result']) ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": { "baseFeePerGas": "0x2da282a8", "difficulty": "0x0", "extraData": "0x", "gasLimit": "0x1c9c380", "gasUsed": "0x3b9aca", "hash": "0xba6064a55ed3dc3f34185d57dc000a63639302bf17f6eaf61c2f211d25f73a67", "logsBloom": "0x00000000000000000000000000000000...", "miner": "0x0000000000000000000000000000000000000000", "nonce": "0x0000000000000000", "number": "0x5bad55", "parentHash": "0xb4fbadf8ea452b139718e2700dc1135cfc81145031c84b7ab27cd99f43ec28ca", "receiptsRoot": "0x9b0816dba2e4c1c7b2d38d0c3da6e6bb93c1713a7e986e38f856b6fb725234cf", "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", "size": "0x21d", "stateRoot": "0xddc8b0234248b014296fed29c5c0e9d6e5a6e4a0576ce66970a36c064e3cd96b", "timestamp": "0x5e0be0ff", "totalDifficulty": "0x0", "transactions": [ "0x5d2dd8b32dc30f347120c5877975c93ccf3e5a5c9ad0c595b0a73c3e00c9e9bb", "0x8a91b1b37e0e463c27cb340dc0e2cbc5636cba8d9b3e9a66c2a9e6c3f8c65e82" ], "transactionsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", "uncles": [] } } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_getBlockByNumber - Get Block Details # eth_getBlockByNumber Returns information about a block by block number on Centrifuge Mainnet. ## When to Use This Method `eth_getBlockByNumber` is crucial for: - **Block Explorers** - Display block information and transactions - **Chain Analytics** - Analyze block patterns and metrics - **Transaction Verification** - Confirm transaction inclusion - **DApp Synchronization** - Process blocks sequentially ## Parameters 1. **Block Parameter** - `QUANTITY|TAG` - `"latest"` - Most recent mined block - `"earliest"` - Genesis block - `"pending"` - Pending block - `"safe"` - Latest safe block - `"finalized"` - Latest finalized block - Hex string block number (e.g., `"0x86c4dd"`) 2. **Transaction Details** - `Boolean` - `true` - Returns full transaction objects - `false` - Returns only transaction hashes ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": [ "0x86c4dd", true ], "id": 1 } ``` ## Returns Block object with the following fields: | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number, null if pending | | `hash` | `DATA`, 32 bytes | Block hash, null if pending | | `parentHash` | `DATA`, 32 bytes | Parent block hash | | `nonce` | `DATA`, 8 bytes | Proof-of-work nonce (always 0 on Ethereum) | | `sha3Uncles` | `DATA`, 32 bytes | SHA3 of uncles (always empty on Ethereum) | | `logsBloom` | `DATA`, 256 bytes | Bloom filter for logs | | `transactionsRoot` | `DATA`, 32 bytes | Root of transaction trie | | `stateRoot` | `DATA`, 32 bytes | Root of final state trie | | `receiptsRoot` | `DATA`, 32 bytes | Root of receipts trie | | `miner` | `DATA`, 20 bytes | Beneficiary address (sequencer on Ethereum) | | `difficulty` | `QUANTITY` | Difficulty (always 0 on Ethereum) | | `totalDifficulty` | `QUANTITY` | Total difficulty | | `extraData` | `DATA` | Extra data field | | `size` | `QUANTITY` | Block size in bytes | | `gasLimit` | `QUANTITY` | Maximum gas allowed | | `gasUsed` | `QUANTITY` | Total gas used by transactions | | `timestamp` | `QUANTITY` | Unix timestamp | | `transactions` | `Array` | Transaction objects or hashes | | `uncles` | `Array` | Uncle hashes (always empty on Ethereum) | | `baseFeePerGas` | `QUANTITY` | Base fee per gas (EIP-1559) | | `l1BlockNumber` | `QUANTITY` | Corresponding L1 block (Centrifuge specific) | ## Implementation Examples ```bash # Get block with transaction hashes only curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 }' # Get block with full transaction details curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["0x86c4dd", true], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); // Get latest block with transactions async function getLatestBlock() { const block = await provider.getBlock('latest', true); console.log('Block Number:', block.number); console.log('Block Hash:', block.hash); console.log('Timestamp:', new Date(block.timestamp * 1000)); console.log('Transactions:', block.transactions.length); console.log('Gas Used:', block.gasUsed.toString()); console.log('Centrifuge Fee:', block.baseFeePerGas?.toString()); return block; } // Get block range async function getBlockRange(start, end) { const blocks = []; for (let i = start; i <= end; i++) { const block = await provider.getBlock(i); blocks.push({ number: block.number, timestamp: block.timestamp, transactions: block.transactions.length, gasUsed: block.gasUsed.toString() }); } return blocks; } // Analyze block statistics async function analyzeBlock(blockNumber) { const block = await provider.getBlock(blockNumber, true); const analysis = { number: block.number, timestamp: new Date(block.timestamp * 1000), transactionCount: block.transactions.length, gasUsed: block.gasUsed, gasLimit: block.gasLimit, utilization: (Number(block.gasUsed) / Number(block.gasLimit) * 100).toFixed(2) + '%', baseFee: block.baseFeePerGas, totalValue: block.transactions.reduce((sum, tx) => sum + BigInt(tx.value || 0), 0n) }; return analysis; } ``` ```python from web3 import Web3 from datetime import datetime w3 = Web3(Web3.HTTPProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY')) def get_block_details(block_identifier='latest', full_transactions=False): """Get block with optional full transaction details""" block = w3.eth.get_block(block_identifier, full_transactions) return { 'number': block['number'], 'hash': block['hash'].hex(), 'timestamp': datetime.fromtimestamp(block['timestamp']), 'transactions': len(block['transactions']), 'gas_used': block['gasUsed'], 'gas_limit': block['gasLimit'], 'base_fee': block.get('baseFeePerGas', 0) } def analyze_blocks(start_block, num_blocks=10): """Analyze multiple blocks for patterns""" blocks_data = [] for i in range(num_blocks): block_num = start_block + i block = w3.eth.get_block(block_num) blocks_data.append({ 'number': block_num, 'timestamp': block['timestamp'], 'tx_count': len(block['transactions']), 'gas_used': block['gasUsed'], 'block_time': block['timestamp'] - blocks_data[-1]['timestamp'] if blocks_data else 0 }) # Calculate averages avg_tx = sum(b['tx_count'] for b in blocks_data) / len(blocks_data) avg_gas = sum(b['gas_used'] for b in blocks_data) / len(blocks_data) avg_time = sum(b['block_time'] for b in blocks_data[1:]) / (len(blocks_data) - 1) return { 'blocks': blocks_data, 'averages': { 'transactions_per_block': avg_tx, 'gas_per_block': avg_gas, 'block_time': avg_time } } ``` ```go package main "context" "fmt" "log" "math/big" "time" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-centrifuge.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } // Get latest block block, err := client.BlockByNumber(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Block Number: %s\n", block.Number().String()) fmt.Printf("Block Hash: %s\n", block.Hash().Hex()) fmt.Printf("Block Time: %s\n", time.Unix(int64(block.Time()), 0)) fmt.Printf("Transactions: %d\n", len(block.Transactions())) fmt.Printf("Gas Used: %d\n", block.GasUsed()) // Get specific block blockNumber := big.NewInt(1000000) historicalBlock, err := client.BlockByNumber(context.Background(), blockNumber) if err != nil { log.Fatal(err) } fmt.Printf("Historical Block: %s\n", historicalBlock.Number().String()) } ``` ## Response Example ### Block with Transaction Hashes ```json { "jsonrpc": "2.0", "id": 1, "result": { "baseFeePerGas": "0x3e", "difficulty": "0x0", "extraData": "0x", "gasLimit": "0x1c9c380", "gasUsed": "0x4f916", "hash": "0x1234567890abcdef...", "logsBloom": "0x00000000...", "miner": "0x0000000000000000000000000000000000000000", "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000", "nonce": "0x0000000000000000", "number": "0x86c4dd", "parentHash": "0xabcdef1234567890...", "receiptsRoot": "0x...", "sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", "size": "0x4d6", "stateRoot": "0x...", "timestamp": "0x64f1b438", "totalDifficulty": "0x0", "transactions": [ "0xhash1...", "0xhash2...", "0xhash3..." ], "transactionsRoot": "0x...", "uncles": [] } } ``` ## Common Use Cases ### 1. Block Explorer Display ```javascript async function formatBlockForExplorer(blockNumber) { const block = await provider.getBlock(blockNumber, true); return { number: block.number, hash: block.hash, timestamp: new Date(block.timestamp * 1000).toISOString(), miner: block.miner, transactionCount: block.transactions.length, gasUsed: `${(Number(block.gasUsed) / 1e6).toFixed(2)}M`, gasLimit: `${(Number(block.gasLimit) / 1e6).toFixed(2)}M`, utilization: `${(Number(block.gasUsed) / Number(block.gasLimit) * 100).toFixed(2)}%`, baseFee: `${Number(block.baseFeePerGas) / 1e9} Gwei`, burnt: formatEther(block.gasUsed * block.baseFeePerGas) }; } ``` ### 2. Transaction Confirmation ```javascript async function confirmTransaction(txHash, confirmations = 6) { const tx = await provider.getTransaction(txHash); if (!tx) throw new Error('Transaction not found'); const receipt = await provider.getTransactionReceipt(txHash); if (!receipt) { console.log('Transaction pending...'); return false; } const currentBlock = await provider.getBlockNumber(); const confirmCount = currentBlock - receipt.blockNumber + 1; if (confirmCount >= confirmations) { const block = await provider.getBlock(receipt.blockNumber, true); const txInBlock = block.transactions.find(t => t.hash === txHash); return { confirmed: true, confirmations: confirmCount, block: receipt.blockNumber, timestamp: block.timestamp, position: txInBlock ? block.transactions.indexOf(txInBlock) : -1 }; } return { confirmed: false, confirmations: confirmCount, needed: confirmations - confirmCount }; } ``` ### 3. Block Time Analysis ```javascript async function analyzeBlockTimes(count = 100) { const latest = await provider.getBlockNumber(); const blocks = []; for (let i = 0; i < count; i++) { const block = await provider.getBlock(latest - i); blocks.push({ number: block.number, timestamp: block.timestamp }); } const blockTimes = []; for (let i = 1; i < blocks.length; i++) { blockTimes.push(blocks[i-1].timestamp - blocks[i].timestamp); } return { average: blockTimes.reduce((a, b) => a + b, 0) / blockTimes.length, min: Math.min(...blockTimes), max: Math.max(...blockTimes), blocks: blockTimes }; } ``` ### 4. Gas Price Tracking ```javascript async function trackGasPrices(blocks = 10) { const latest = await provider.getBlockNumber(); const gasPrices = []; for (let i = 0; i < blocks; i++) { const block = await provider.getBlock(latest - i, true); // Calculate effective gas prices from transactions const prices = block.transactions .filter(tx => tx.gasPrice || tx.maxFeePerGas) .map(tx => { if (tx.type === 2) { // EIP-1559 return BigInt(tx.maxFeePerGas) < BigInt(block.baseFeePerGas) + BigInt(tx.maxPriorityFeePerGas) ? BigInt(tx.maxFeePerGas) : BigInt(block.baseFeePerGas) + BigInt(tx.maxPriorityFeePerGas); } return BigInt(tx.gasPrice); }); if (prices.length > 0) { const avgPrice = prices.reduce((a, b) => a + b, 0n) / BigInt(prices.length); gasPrices.push({ block: block.number, baseFee: Number(block.baseFeePerGas) / 1e9, avgPrice: Number(avgPrice) / 1e9, txCount: block.transactions.length }); } } return gasPrices; } ``` ## Performance Optimization ### Parallel Block Fetching ```javascript async function getBlocksParallel(startBlock, count) { const promises = []; for (let i = 0; i < count; i++) { promises.push(provider.getBlock(startBlock + i)); } const blocks = await Promise.all(promises); return blocks; } ``` ### Block Caching ```javascript class BlockCache { constructor(maxSize = 100) { this.cache = new Map(); this.maxSize = maxSize; } async getBlock(provider, blockNumber, fullTx = false) { const key = `${blockNumber}-${fullTx}`; if (this.cache.has(key)) { return this.cache.get(key); } const block = await provider.getBlock(blockNumber, fullTx); // LRU eviction if (this.cache.size >= this.maxSize) { const firstKey = this.cache.keys().next().value; this.cache.delete(firstKey); } this.cache.set(key, block); return block; } } ``` ## Error Handling | Error Code | Description | Solution | |------------|-------------|----------| | -32602 | Invalid block number | Check block exists and format | | -32000 | Block not found | Block may not be mined yet | | -32005 | Rate limit exceeded | Implement backoff strategy | ```javascript async function safeGetBlock(blockNumber, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { const block = await provider.getBlock(blockNumber); if (!block) { throw new Error(`Block ${blockNumber} not found`); } return block; } catch (error) { if (i === maxRetries - 1) throw error; // Exponential backoff for rate limits if (error.code === -32005) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } } } } ``` *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_getCode - Get Centrifuge Contract Byt... # eth_getCode Retrieves the compiled bytecode of a smart contract deployed on the Centrifuge network. This method is essential for contract verification, security analysis, and understanding deployed contract functionality on Ethereum's Layer 2 infrastructure. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `string` | Yes | The 20-byte address of the contract (0x-prefixed hex string) | | `blockNumber/blockTag` | `string` | Yes | Block number in hex (e.g., "0x1b4") or block tag: "latest", "earliest", "pending", "safe", "finalized" | ### Block Tags - `latest` - Most recent block in the canonical chain - `earliest` - Genesis block - `pending` - Pending state/transactions - `safe` - Latest safe head block (Ethereum) - `finalized` - Latest finalized block (Ethereum) ## Returns Returns the bytecode as a hex-encoded string. For Externally Owned Accounts (EOAs), returns "0x". | Type | Description | |------|-------------| | `string` | Hex-encoded bytecode starting with "0x". Returns "0x" for EOA addresses | ## Code Examples ```bash # Get bytecode for USDC contract on Ethereum curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "latest" ], "id": 1 }' ``` ```javascript // Get bytecode for Ethereum's official bridge contract const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_getCode', params: [ '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', 'latest' ], id: 1 }) }); const data = await response.json(); console.log('Contract bytecode:', data.result); // Check if address is a contract or EOA if (data.result === '0x') { console.log('Address is an EOA (no contract code)'); } else { console.log('Address contains contract code'); } ``` ```python # Get bytecode for Coinbase's cbETH contract on Ethereum url = "https://api-centrifuge.n.dwellir.com/YOUR_API_KEY" payload = { "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", # cbETH on Ethereum "latest" ], "id": 1 } response = requests.post(url, json=payload) result = response.json() if result['result'] == '0x': print("Address is an EOA") else: print(f"Contract bytecode: {result['result'][:100]}...") # First 100 chars print(f"Bytecode length: {len(result['result'])} characters") ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x608060405234801561001057600080fd5b50600436106101735760003560e01c80638da5cb5b116100de578063c87b56dd11610097578063e985e9c511610071578063e985e9c5146104a2578063f2fde38b146104de578063f46a04eb146104fa578063f5298aca1461051657610173565b8063c87b56dd1461044a578063d547741f14610466578063e8a3d4851461048257610173565b80638da5cb5b146103a657806391d14854146103c457806395d89b41146103e0578063a217fddf146103fe578063a22cb4651461041c578063bd85b0391461043857610173565b80632f2ff15d1161013057806336568abe1161010a57806336568abe146103285780634e1273f414610344578063715018a6146103745780638456cb591461037e57610173565b80632f2ff15d146102cc5780633659cfe6146102e85780633f4ba83a1461030457610173565b8062fdd58e1461017857806301ffc9a71461019857806306fdde03146101c85780630e89341c146101e6578063248a9ca3146102065780632eb2c2d614610236575b600080fd5b610182600480360381019061017d9190611c3a565b610532565b60405161018f9190611c89565b60405180910390f35b6101b260048036038101906101ad9190611cfc565b6105fa565b60405161..." } ``` ## Important Notes ### EOA vs Contract Addresses - **Contract addresses**: Return the actual bytecode of the deployed smart contract - **EOA addresses**: Return "0x" as they contain no contract code - Use this method to programmatically distinguish between EOAs and contracts ### Use Cases - **Contract verification**: Compare deployed bytecode with source code - **Security analysis**: Analyze contract functionality and potential vulnerabilities - **Proxy detection**: Identify proxy contracts and their implementation patterns - **Contract interaction**: Understand contract capabilities before interaction ### Ethereum-Specific Considerations - Centrifuge is the main Layer 1 blockchain using Proof of Stake consensus - Bytecode format is identical to Centrifuge mainnet - Gas costs for contract deployment and execution are significantly lower - Full compatibility with Centrifuge smart contracts and tooling --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_getFilterChanges - Poll filter for ch... # eth_getFilterChanges Polling method for a filter, which returns an array of events that have occurred since the last poll on the Centrifuge network. ## Parameters - `id` (string, required): The filter ID returned from eth_newFilter, eth_newBlockFilter, or eth_newPendingTransactionFilter ## Returns An array containing different data types depending on the filter type: ### For log filters (eth_newFilter): Array of log objects with: - `address` (string): Address from which this log originated - `topics` (array of strings): Array of 0 to 4 32-byte DATA topics - `data` (string): Contains non-indexed arguments of the log - `blockNumber` (string): Block number where this log was included - `blockHash` (string): Hash of the block where this log was included - `transactionHash` (string): Hash of the transaction that created this log - `transactionIndex` (string): Transaction index position in the block - `logIndex` (string): Integer of the log index position in the block - `removed` (boolean): true when the log was removed due to a chain reorganization ### For block filters (eth_newBlockFilter): Array of 32-byte block hashes for blocks that were newly created ### For pending transaction filters (eth_newPendingTransactionFilter): Array of 32-byte transaction hashes for transactions that entered the pending state ## Implementation Example ```bash # Create a log filter scoped to the latest block (requires jq) FILTER_ID=$(curl -s -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": null, "topics": [] }], "id": 1 }' | jq -r '.result') # Poll for changes on that filter curl -s -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d "$(jq -n --arg id \"$FILTER_ID\" '{jsonrpc:\"2.0\", method:\"eth_getFilterChanges\", params:[$id], id:1}')" ``` ```javascript const endpoint = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY'; const createFilter = async () => { const filterResponse = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_newFilter', params: [{ fromBlock: 'latest', toBlock: 'latest', address: null, topics: [] }], id: 1 }) }); const { result } = await filterResponse.json(); return result; }; const filterId = await createFilter(); const response = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_getFilterChanges', params: [filterId], id: 2 }) }); const data = await response.json(); console.log(data.result); ``` ```python url = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY' headers = {'Content-Type': 'application/json'} filter_payload = { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": None, "topics": [] }], "id": 1 } filter_id = requests.post(url, headers=headers, json=filter_payload, timeout=10).json()['result'] changes_payload = { "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": [filter_id], "id": 2 } response = requests.post(url, headers=headers, json=changes_payload, timeout=10) print(response.json()['result']) ``` ## Response Example ### For log filters: ```json { "jsonrpc": "2.0", "id": 1, "result": [ { "address": "0x1234567890abcdef1234567890abcdef12345678", "topics": [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef" ], "data": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000", "blockNumber": "0x1b4", "blockHash": "0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890", "transactionHash": "0xfedcba0987654321fedcba0987654321fedcba0987654321fedcba0987654321", "transactionIndex": "0x1", "logIndex": "0x0", "removed": false } ] } ``` ### For block filters: ```json { "jsonrpc": "2.0", "id": 1, "result": [ "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", "0xfedcba0987654321fedcba0987654321fedcba0987654321fedcba0987654321" ] } ``` ## Notes - This method only returns changes that occurred since the last poll - Filters timeout if not accessed within a certain time period (typically 5 minutes) - The first call to eth_getFilterChanges returns all events since filter creation - Subsequent calls return only new events since the previous call - Use eth_getFilterLogs to retrieve all accumulated logs regardless of polling --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_getFilterLogs - Get Filter Logs # eth_getFilterLogs Returns an array of all logs matching filter with given id on the Centrifuge network. This method retrieves all accumulated logs that match the criteria of a previously created filter. ## Parameters - `id` (string, required): The filter ID to retrieve logs for (obtained from eth_newFilter, eth_newBlockFilter, or eth_newPendingTransactionFilter) ## Returns An array of log objects, or an empty array if no logs match the filter. Each log object contains: - `address` (string): Address from which this log originated - `topics` (array of strings): Array of 0 to 4 32-byte DATA topics. The first topic is the hash of the signature of the event - `data` (string): Contains non-indexed arguments of the log - `blockNumber` (string): Block number where this log was included (null when pending) - `blockHash` (string): Hash of the block where this log was included (null when pending) - `transactionHash` (string): Hash of the transaction that created this log (null when pending) - `transactionIndex` (string): Transaction index position in the block (null when pending) - `logIndex` (string): Integer of the log index position in the block (null when pending) - `removed` (boolean): true when the log was removed due to a chain reorganization, false if it's a valid log ## Implementation Example ```bash # Create a filter for block 0x86d9c9 that includes Centrifuge liquidity pool events (requires jq) FILTER_ID=$(curl -s -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "0x86d9c9", "toBlock": "0x86d9c9", "address": "0x2d5d7d31f671f86c782533cc367f14109a082712", "topics": [] }], "id": 1 }' | jq -r '.result') # Retrieve the logs captured by that filter curl -s -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d "$(jq -n --arg id \"$FILTER_ID\" '{jsonrpc:\"2.0\", method:\"eth_getFilterLogs\", params:[$id], id:1}')" ``` ```javascript const endpoint = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY'; const createLogsFilter = async () => { const payload = { jsonrpc: '2.0', method: 'eth_newFilter', params: [{ fromBlock: '0x86d9c9', toBlock: '0x86d9c9', address: '0x2d5d7d31f671f86c782533cc367f14109a082712', topics: [] }], id: 1 }; const response = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); const { result } = await response.json(); return result; }; const filterId = await createLogsFilter(); const response = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_getFilterLogs', params: [filterId], id: 2 }) }); const data = await response.json(); console.log(data.result); ``` ```python url = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY' headers = {'Content-Type': 'application/json'} filter_payload = { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "0x86d9c9", "toBlock": "0x86d9c9", "address": "0x2d5d7d31f671f86c782533cc367f14109a082712", "topics": [] }], "id": 1 } filter_id = requests.post(url, headers=headers, json=filter_payload, timeout=10).json()['result'] logs_payload = { "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": [filter_id], "id": 2 } response = requests.post(url, headers=headers, json=logs_payload, timeout=10) print(response.json()['result']) ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": [ { "address": "0x1234567890abcdef1234567890abcdef12345678", "topics": [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x0000000000000000000000009876543210fedcba9876543210fedcba98765432" ], "data": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000", "blockNumber": "0x1b4", "blockHash": "0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890", "transactionHash": "0xfedcba0987654321fedcba0987654321fedcba0987654321fedcba0987654321", "transactionIndex": "0x1", "logIndex": "0x0", "removed": false } ] } ``` ## Notes - The filter must be created first using `eth_newFilter`, `eth_newBlockFilter`, or `eth_newPendingTransactionFilter` - This method returns all logs accumulated since the filter was created - Filters timeout if not accessed within a certain time period (typically 5 minutes) - Use `eth_getFilterChanges` to get only new logs since the last poll - The `removed` field helps handle chain reorganizations --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_getLogs - Query Event Logs # eth_getLogs Returns an array of all logs matching a given filter object. Essential for querying historical events and monitoring smart contract activity. ## When to Use This Method `eth_getLogs` is crucial for: - **Event Monitoring** - Track smart contract events and state changes - **Historical Queries** - Search past events within a block range - **DeFi Analytics** - Monitor trades, liquidity events, and protocol activity - **Indexing** - Build databases of on-chain events ## Parameters 1. **Filter Object** - `fromBlock` - (optional) Starting block number or tag - `toBlock` - (optional) Ending block number or tag - `address` - (optional) Contract address or array of addresses - `topics` - (optional) Array of topic filters (event signatures and indexed parameters) - `blockHash` - (optional) Restrict to single block (incompatible with fromBlock/toBlock) ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "0x1", "toBlock": "latest", "address": "0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0", "topics": [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", null, "0x000000000000000000000000a7d8d9ef8d8ce8992df33d8b8cf4aebabd5bd270" ] }], "id": 1 } ``` ## Returns Array of log objects with: - `removed` - `true` if log was removed due to reorg - `logIndex` - Position in the block - `transactionIndex` - Transaction position in block - `transactionHash` - Hash of transaction - `blockHash` - Hash of block - `blockNumber` - Block number - `address` - Contract address - `data` - Non-indexed log parameters - `topics` - Array of indexed log parameters ## Implementation Examples ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "0x86d9c9", "toBlock": "0x86d9c9", "address": "0x2d5d7d31f671f86c782533cc367f14109a082712", "topics": [ "0xd5df103822011013c8c940930e5180419111c65abadd6525ca7e740d56b4703f" ] }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); // Advanced event monitoring system class EventMonitor { constructor(provider) { this.provider = provider; this.filters = new Map(); } async getTransferEvents(tokenAddress, fromBlock, toBlock) { // ERC20 Transfer event signature const transferTopic = id('Transfer(address,address,uint256)'); const filter = { fromBlock: toBeHex(fromBlock), toBlock: toBlock === 'latest' ? 'latest' : toBeHex(toBlock), address: tokenAddress, topics: [transferTopic] }; const logs = await this.provider.getLogs(filter); // Decode logs const iface = new Interface([ 'event Transfer(address indexed from, address indexed to, uint256 value)' ]); return logs.map(log => { const decoded = iface.parseLog({ topics: log.topics, data: log.data }); return { from: decoded.args.from, to: decoded.args.to, value: decoded.args.value.toString(), blockNumber: log.blockNumber, transactionHash: log.transactionHash, logIndex: log.logIndex }; }); } async getEventsBySignature(signature, address, fromBlock, toBlock) { const eventTopic = id(signature); const filter = { fromBlock: toBeHex(fromBlock), toBlock: toBlock === 'latest' ? 'latest' : toBeHex(toBlock), address: address, topics: [eventTopic] }; return await this.provider.getLogs(filter); } async queryWithMultipleAddresses(addresses, eventSignature, fromBlock, toBlock) { const eventTopic = id(eventSignature); const filter = { fromBlock: toBeHex(fromBlock), toBlock: toBlock === 'latest' ? 'latest' : toBeHex(toBlock), address: addresses, // Array of addresses topics: [eventTopic] }; const logs = await this.provider.getLogs(filter); // Group by address const grouped = {}; for (const log of logs) { if (!grouped[log.address]) { grouped[log.address] = []; } grouped[log.address].push(log); } return grouped; } async getFilteredTransfers(tokenAddress, specificAddress, direction, fromBlock, toBlock) { const transferTopic = id('Transfer(address,address,uint256)'); let topics; if (direction === 'from') { // Transfers FROM specific address topics = [ transferTopic, zeroPadValue(specificAddress, 32), null ]; } else if (direction === 'to') { // Transfers TO specific address topics = [ transferTopic, null, zeroPadValue(specificAddress, 32) ]; } else { // All transfers involving address const [fromLogs, toLogs] = await Promise.all([ this.getFilteredTransfers(tokenAddress, specificAddress, 'from', fromBlock, toBlock), this.getFilteredTransfers(tokenAddress, specificAddress, 'to', fromBlock, toBlock) ]); return [...fromLogs, ...toLogs].sort((a, b) => a.blockNumber - b.blockNumber); } const filter = { fromBlock: toBeHex(fromBlock), toBlock: toBlock === 'latest' ? 'latest' : toBeHex(toBlock), address: tokenAddress, topics: topics }; return await this.provider.getLogs(filter); } async searchDeFiEvents(protocolAddress, fromBlock, toBlock) { // Common DeFi event signatures const eventSignatures = { swap: 'Swap(address,uint256,uint256,uint256,uint256,address)', addLiquidity: 'Mint(address,uint256,uint256)', removeLiquidity: 'Burn(address,uint256,uint256,address)', deposit: 'Deposit(address,uint256,uint256)', withdraw: 'Withdrawal(address,uint256,uint256)', borrow: 'Borrow(address,address,uint256,uint256,uint256)', repay: 'Repay(address,address,uint256,uint256)' }; const events = {}; for (const [name, signature] of Object.entries(eventSignatures)) { try { const logs = await this.getEventsBySignature( signature, protocolAddress, fromBlock, toBlock ); if (logs.length > 0) { events[name] = logs; } } catch (error) { // Event might not exist in this contract continue; } } return events; } async getPaginatedLogs(filter, pageSize = 1000) { const results = []; let currentBlock = parseInt(filter.fromBlock); const endBlock = filter.toBlock === 'latest' ? await this.provider.getBlockNumber() : parseInt(filter.toBlock); while (currentBlock <= endBlock) { const chunkEnd = Math.min(currentBlock + pageSize - 1, endBlock); const chunkFilter = { ...filter, fromBlock: toBeHex(currentBlock), toBlock: toBeHex(chunkEnd) }; try { const logs = await this.provider.getLogs(chunkFilter); results.push(...logs); console.log(`Fetched blocks ${currentBlock} to ${chunkEnd}: ${logs.length} logs`); } catch (error) { if (error.message.includes('query returned more than')) { // Reduce page size and retry return this.getPaginatedLogs(filter, Math.floor(pageSize / 2)); } throw error; } currentBlock = chunkEnd + 1; } return results; } createLiveEventStream(filter, callback) { const processNewBlock = async (blockNumber) => { const logs = await this.provider.getLogs({ ...filter, fromBlock: toBeHex(blockNumber), toBlock: toBeHex(blockNumber) }); if (logs.length > 0) { callback(logs); } }; // Listen for new blocks this.provider.on('block', processNewBlock); // Return unsubscribe function return () => { this.provider.off('block', processNewBlock); }; } } // NFT event monitoring class NFTEventTracker { constructor(provider) { this.provider = provider; } async getERC721Transfers(contractAddress, fromBlock, toBlock) { const transferTopic = id('Transfer(address,address,uint256)'); const logs = await this.provider.getLogs({ fromBlock: toBeHex(fromBlock), toBlock: toBlock === 'latest' ? 'latest' : toBeHex(toBlock), address: contractAddress, topics: [transferTopic] }); const iface = new Interface([ 'event Transfer(address indexed from, address indexed to, uint256 indexed tokenId)' ]); return logs.map(log => { const decoded = iface.parseLog({ topics: log.topics, data: log.data }); return { from: decoded.args.from, to: decoded.args.to, tokenId: decoded.args.tokenId.toString(), blockNumber: log.blockNumber, transactionHash: log.transactionHash, isMint: decoded.args.from === '0x0000000000000000000000000000000000000000', isBurn: decoded.args.to === '0x0000000000000000000000000000000000000000' }; }); } async getERC1155Transfers(contractAddress, fromBlock, toBlock) { const singleTransferTopic = id('TransferSingle(address,address,address,uint256,uint256)'); const batchTransferTopic = id('TransferBatch(address,address,address,uint256[],uint256[])'); const [singleLogs, batchLogs] = await Promise.all([ this.provider.getLogs({ fromBlock: toBeHex(fromBlock), toBlock: toBlock === 'latest' ? 'latest' : toBeHex(toBlock), address: contractAddress, topics: [singleTransferTopic] }), this.provider.getLogs({ fromBlock: toBeHex(fromBlock), toBlock: toBlock === 'latest' ? 'latest' : toBeHex(toBlock), address: contractAddress, topics: [batchTransferTopic] }) ]); return { single: singleLogs, batch: batchLogs, total: singleLogs.length + batchLogs.length }; } } // Usage examples const monitor = new EventMonitor(provider); // Get transfer events for a token const transfers = await monitor.getTransferEvents( '0xTokenAddress', 12345678, 'latest' ); // Monitor specific address activity const userTransfers = await monitor.getFilteredTransfers( '0xTokenAddress', '0xUserAddress', 'both', // 'from', 'to', or 'both' 12345678, 'latest' ); // Search DeFi protocol events const defiEvents = await monitor.searchDeFiEvents( '0xProtocolAddress', 12345678, 12345778 ); // Create live event stream const unsubscribe = monitor.createLiveEventStream( { address: '0xTokenAddress', topics: [id('Transfer(address,address,uint256)')] }, (logs) => { console.log('New events:', logs); } ); ``` ```python from web3 import Web3 from eth_utils import event_signature_to_log_topic, to_hex from typing import Dict, List, Any, Optional from datetime import datetime, timedelta w3 = Web3(Web3.HTTPProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY')) class LogAnalyzer: """Analyze and query event logs on Centrifuge Mainnet""" def __init__(self, w3_instance): self.w3 = w3_instance def get_transfer_events( self, token_address: str, from_block: int, to_block: str = 'latest', from_address: Optional[str] = None, to_address: Optional[str] = None ) -> List[Dict[str, Any]]: """Get ERC20 transfer events with optional filtering""" # Transfer event signature transfer_topic = self.w3.keccak(text='Transfer(address,address,uint256)').hex() # Build topics array topics = [transfer_topic] if from_address: topics.append(self._address_to_topic(from_address)) else: topics.append(None) if to_address: topics.append(self._address_to_topic(to_address)) # Create filter filter_params = { 'fromBlock': from_block, 'toBlock': to_block, 'address': token_address, 'topics': topics } # Get logs logs = self.w3.eth.get_logs(filter_params) # Decode logs transfers = [] for log in logs: transfers.append({ 'from': self._topic_to_address(log['topics'][1]), 'to': self._topic_to_address(log['topics'][2]), 'value': int(log['data'], 16) if log['data'] != '0x' else 0, 'block_number': log['blockNumber'], 'transaction_hash': log['transactionHash'].hex(), 'log_index': log['logIndex'], 'address': log['address'] }) return transfers def _address_to_topic(self, address: str) -> str: """Convert address to topic format""" return '0x' + address[2:].lower().zfill(64) def _topic_to_address(self, topic: str) -> str: """Convert topic to address format""" return '0x' + topic.hex()[-40:] def get_events_by_signature( self, event_signature: str, contract_address: Optional[str] = None, from_block: int = 0, to_block: str = 'latest' ) -> List[Dict[str, Any]]: """Get events by signature""" event_topic = self.w3.keccak(text=event_signature).hex() filter_params = { 'fromBlock': from_block, 'toBlock': to_block, 'topics': [event_topic] } if contract_address: filter_params['address'] = contract_address logs = self.w3.eth.get_logs(filter_params) return [{ 'address': log['address'], 'topics': [t.hex() for t in log['topics']], 'data': log['data'], 'block_number': log['blockNumber'], 'transaction_hash': log['transactionHash'].hex(), 'log_index': log['logIndex'] } for log in logs] def search_defi_activity( self, protocol_address: str, from_block: int, to_block: str = 'latest' ) -> Dict[str, List[Dict]]: """Search for common DeFi events""" event_signatures = { 'swaps': 'Swap(address,uint256,uint256,uint256,uint256,address)', 'liquidity_added': 'Mint(address,uint256,uint256)', 'liquidity_removed': 'Burn(address,uint256,uint256,address)', 'deposits': 'Deposit(address,uint256)', 'withdrawals': 'Withdrawal(address,uint256)', 'borrows': 'Borrow(address,address,uint256,uint256,uint256)', 'repayments': 'Repay(address,address,uint256,uint256)' } results = {} for event_type, signature in event_signatures.items(): try: logs = self.get_events_by_signature( signature, protocol_address, from_block, to_block ) if logs: results[event_type] = logs except Exception as e: # Event might not exist in this contract continue return results def get_nft_transfers( self, nft_address: str, from_block: int, to_block: str = 'latest', token_id: Optional[int] = None ) -> List[Dict[str, Any]]: """Get NFT transfer events (ERC721)""" # Transfer event with tokenId as indexed parameter transfer_topic = self.w3.keccak(text='Transfer(address,address,uint256)').hex() topics = [transfer_topic, None, None] if token_id is not None: topics.append(to_hex(token_id).zfill(66)) filter_params = { 'fromBlock': from_block, 'toBlock': to_block, 'address': nft_address, 'topics': topics } logs = self.w3.eth.get_logs(filter_params) transfers = [] for log in logs: from_addr = self._topic_to_address(log['topics'][1]) to_addr = self._topic_to_address(log['topics'][2]) transfers.append({ 'from': from_addr, 'to': to_addr, 'token_id': int(log['topics'][3].hex(), 16) if len(log['topics']) > 3 else int(log['data'], 16), 'is_mint': from_addr == '0x0000000000000000000000000000000000000000', 'is_burn': to_addr == '0x0000000000000000000000000000000000000000', 'block_number': log['blockNumber'], 'transaction_hash': log['transactionHash'].hex(), 'log_index': log['logIndex'] }) return transfers def get_logs_paginated( self, filter_params: Dict, page_size: int = 1000 ) -> List[Dict[str, Any]]: """Get logs with pagination to avoid query limits""" all_logs = [] from_block = filter_params['fromBlock'] to_block = filter_params['toBlock'] if to_block == 'latest': to_block = self.w3.eth.block_number current_block = from_block while current_block <= to_block: chunk_end = min(current_block + page_size - 1, to_block) chunk_filter = { **filter_params, 'fromBlock': current_block, 'toBlock': chunk_end } try: logs = self.w3.eth.get_logs(chunk_filter) all_logs.extend(logs) print(f"Fetched blocks {current_block} to {chunk_end}: {len(logs)} logs") except Exception as e: if 'query returned more than' in str(e): # Reduce page size and retry if page_size > 10: return self.get_logs_paginated(filter_params, page_size // 2) else: raise Exception("Block range too large even with minimum page size") else: raise e current_block = chunk_end + 1 return all_logs def analyze_event_patterns( self, logs: List[Dict] ) -> Dict[str, Any]: """Analyze patterns in event logs""" if not logs: return {'error': 'No logs to analyze'} # Group by block blocks = {} for log in logs: block = log['blockNumber'] if block not in blocks: blocks[block] = [] blocks[block].append(log) # Group by transaction transactions = {} for log in logs: tx = log['transactionHash'].hex() if hasattr(log['transactionHash'], 'hex') else log['transactionHash'] if tx not in transactions: transactions[tx] = [] transactions[tx].append(log) # Find most active addresses addresses = {} for log in logs: addr = log['address'] if addr not in addresses: addresses[addr] = 0 addresses[addr] += 1 sorted_addresses = sorted(addresses.items(), key=lambda x: x[1], reverse=True) return { 'total_logs': len(logs), 'unique_blocks': len(blocks), 'unique_transactions': len(transactions), 'unique_addresses': len(addresses), 'most_active_addresses': sorted_addresses[:10], 'logs_per_block': { 'average': len(logs) / len(blocks) if blocks else 0, 'max': max(len(b) for b in blocks.values()) if blocks else 0, 'min': min(len(b) for b in blocks.values()) if blocks else 0 }, 'logs_per_transaction': { 'average': len(logs) / len(transactions) if transactions else 0, 'max': max(len(t) for t in transactions.values()) if transactions else 0, 'min': min(len(t) for t in transactions.values()) if transactions else 0 } } def export_logs_to_csv( self, logs: List[Dict], filename: str ): """Export logs to CSV file""" if not logs: return # Get all unique keys keys = set() for log in logs: keys.update(log.keys()) with open(filename, 'w', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=sorted(keys)) writer.writeheader() for log in logs: # Convert bytes to hex strings row = {} for key, value in log.items(): if isinstance(value, bytes): row[key] = value.hex() else: row[key] = value writer.writerow(row) print(f"Exported {len(logs)} logs to {filename}") # Usage examples analyzer = LogAnalyzer(w3) # Get token transfers transfers = analyzer.get_transfer_events( token_address='0xTokenAddress', from_block=12345678, to_block='latest', from_address='0xUserAddress' # Optional filter ) print(f"Found {len(transfers)} transfers") for transfer in transfers[:5]: print(f"From: {transfer['from'][:10]}... To: {transfer['to'][:10]}... Value: {transfer['value']}") # Search DeFi activity defi_events = analyzer.search_defi_activity( protocol_address='0xProtocolAddress', from_block=12345678 ) for event_type, events in defi_events.items(): print(f"{event_type}: {len(events)} events") # Get NFT transfers nft_transfers = analyzer.get_nft_transfers( nft_address='0xNFTAddress', from_block=12345678 ) mints = [t for t in nft_transfers if t['is_mint']] print(f"Found {len(mints)} NFT mints") # Analyze event patterns pattern_analysis = analyzer.analyze_event_patterns(transfers) print(f"Analysis: {json.dumps(pattern_analysis, indent=2)}") ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": [ { "address": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", "topics": [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x000000000000000000000000a7d8d9ef8d8ce8992df33d8b8cf4aebabd5bd270", "0x0000000000000000000000004e6b5f1abfb9aa3cc5b3d8f4a7b8c2d9e3f0a1b2" ], "data": "0x000000000000000000000000000000000000000000000000016345785d8a0000", "blockNumber": "0x123abc", "blockHash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", "transactionHash": "0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890", "transactionIndex": "0x0", "logIndex": "0x0", "removed": false } ] } ``` ## Advanced Usage ### Multiple Address Filtering ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "0x1", "toBlock": "latest", "address": [ "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913", "0x4200000000000000000000000000000000000006" ], "topics": [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef" ] }], "id": 1 } ``` ### Topic Filtering with OR Logic ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "0x1", "toBlock": "latest", "topics": [ [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925" ] ] }], "id": 1 } ``` ## Notes - Centrifuge supports **historical log queries** back to genesis block - **Query limits**: Maximum 10,000 results per request - **Block range limits**: Maximum 2,000 blocks per query for optimal performance - **Topic arrays**: Support up to 4 topics with OR logic within each position - **Performance tip**: Use specific address filters to improve query speed - **Event signatures**: First topic is always the keccak256 hash of the event signature ## Common Use Cases ### 1. Token Balance History ```javascript // Track historical token balance changes async function getBalanceHistory(tokenAddress, userAddress, fromBlock) { const monitor = new EventMonitor(provider); // Get all transfers involving the user const logs = await monitor.getFilteredTransfers( tokenAddress, userAddress, 'both', fromBlock, 'latest' ); // Calculate balance changes const balanceChanges = []; let currentBalance = 0n; for (const log of logs) { const iface = new Interface([ 'event Transfer(address indexed from, address indexed to, uint256 value)' ]); const decoded = iface.parseLog({ topics: log.topics, data: log.data }); const change = decoded.args.from.toLowerCase() === userAddress.toLowerCase() ? -decoded.args.value : decoded.args.value; currentBalance += change; balanceChanges.push({ blockNumber: log.blockNumber, transactionHash: log.transactionHash, change: change.toString(), balance: currentBalance.toString(), type: change < 0 ? 'outgoing' : 'incoming' }); } return balanceChanges; } ``` ### 2. DEX Trade Monitoring ```javascript // Monitor DEX trading activity async function monitorDEXTrades(dexAddress, fromBlock) { const swapTopic = id('Swap(address,address,int256,int256,uint160,uint128,int24)'); const logs = await provider.getLogs({ fromBlock: toBeHex(fromBlock), toBlock: 'latest', address: dexAddress, topics: [swapTopic] }); const trades = logs.map(log => { // Decode Uniswap V3 swap event const iface = new Interface([ 'event Swap(address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick)' ]); const decoded = iface.parseLog({ topics: log.topics, data: log.data }); return { sender: decoded.args.sender, recipient: decoded.args.recipient, amount0: decoded.args.amount0.toString(), amount1: decoded.args.amount1.toString(), price: Number(decoded.args.sqrtPriceX96) ** 2 / (2 ** 192), blockNumber: log.blockNumber, transactionHash: log.transactionHash }; }); return trades; } ``` ### 3. Contract Event Indexer ```javascript // Build an event index for a contract class EventIndexer { constructor(provider, contractAddress, abi) { this.provider = provider; this.contractAddress = contractAddress; this.iface = new Interface(abi); this.eventIndex = new Map(); } async indexEvents(fromBlock, toBlock) { // Get all events for the contract const logs = await this.provider.getLogs({ fromBlock: toBeHex(fromBlock), toBlock: toBlock === 'latest' ? 'latest' : toBeHex(toBlock), address: this.contractAddress }); for (const log of logs) { try { const parsed = this.iface.parseLog({ topics: log.topics, data: log.data }); if (!this.eventIndex.has(parsed.name)) { this.eventIndex.set(parsed.name, []); } this.eventIndex.get(parsed.name).push({ args: Object.fromEntries( Object.entries(parsed.args).filter(([key]) => isNaN(key)) ), blockNumber: log.blockNumber, transactionHash: log.transactionHash, logIndex: log.logIndex }); } catch { // Unknown event } } return this.getStatistics(); } getStatistics() { const stats = {}; for (const [eventName, events] of this.eventIndex) { stats[eventName] = { count: events.length, firstBlock: Math.min(...events.map(e => e.blockNumber)), lastBlock: Math.max(...events.map(e => e.blockNumber)) }; } return stats; } } ``` ## Error Handling | Error Type | Description | Solution | |------------|-------------|----------| | Query limit exceeded | Too many logs in range | Use pagination or reduce block range | | Invalid block range | fromBlock > toBlock | Validate block parameters | | Node timeout | Large query timeout | Break into smaller queries | ```javascript async function robustGetLogs(filter, maxRetries = 3) { // Validate filter if (filter.fromBlock > filter.toBlock && filter.toBlock !== 'latest') { throw new Error('Invalid block range: fromBlock must be <= toBlock'); } for (let attempt = 0; attempt < maxRetries; attempt++) { try { const logs = await provider.getLogs(filter); return logs; } catch (error) { if (error.message.includes('query returned more than')) { // Too many results, need pagination const monitor = new EventMonitor(provider); return await monitor.getPaginatedLogs(filter, 500); } if (error.message.includes('timeout') && attempt < maxRetries - 1) { // Retry with exponential backoff await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000) ); continue; } throw error; } } } ``` *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_getStorageAt - Get Contract Storage V... # eth_getStorageAt Retrieves the value from a storage position at a given address on the Centrifuge network. This method allows direct access to contract storage slots, enabling you to read contract state variables, proxy implementation addresses, and other stored data. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | string | Yes | The 20-byte address of the contract whose storage you want to read | | `position` | string | Yes | The hex-encoded storage position/slot number (32 bytes) | | `blockNumber` | string | Yes | Block number in hex, or block tag ("latest", "earliest", "pending") | ### Storage Position Calculation - **Simple variables**: Use slot number directly (e.g., `0x0`, `0x1`, `0x2`) - **Mappings**: `keccak256(key + slot)` where key is padded to 32 bytes - **Arrays**: Length at slot, elements at `keccak256(slot) + index` - **Structs**: Each field occupies consecutive slots ## Returns Returns a 32-byte hex string representing the storage value. Values are left-padded with zeros if smaller than 32 bytes. ## Code Examples ```bash # Read storage slot 0 from USDC contract on Ethereum curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "0x0", "latest" ], "id": 1 }' ``` ```javascript // Read storage from Centrifuge USDC contract const getStorage = async () => { const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_getStorageAt', params: [ '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // Centrifuge USDC '0x0', // Storage slot 0 'latest' ], id: 1 }) }); const data = await response.json(); return data.result; }; // Calculate mapping storage position const getMappingSlot = (key, slot) => { const keyPadded = key.padStart(64, '0'); const slotPadded = slot.toString(16).padStart(64, '0'); return web3.utils.keccak256('0x' + keyPadded + slotPadded); }; ``` ```python from web3 import Web3 # Read storage from contract def get_storage_at(address, position, block='latest'): payload = { "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [address, position, block], "id": 1 } response = requests.post( 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', json=payload, headers={'Content-Type': 'application/json'} ) return response.json()['result'] # Example: Read from Centrifuge USDC contract usdc_address = '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' storage_value = get_storage_at(usdc_address, '0x0') # Calculate mapping storage position def get_mapping_slot(key, slot): key_padded = key.zfill(64) slot_padded = hex(slot)[2:].zfill(64) return Web3.keccak(bytes.fromhex(key_padded + slot_padded)).hex() # Example: Get balance mapping for an address balance_slot = get_mapping_slot('000000000000000000000000YourAddress', 9) balance = get_storage_at(usdc_address, balance_slot) ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0000000000000000000000000000000000000000000000000000000000000001" } ``` ## Use Cases - **Contract State Inspection**: Read private or internal variables - **Proxy Implementation**: Get implementation address from proxy contracts - **Token Balances**: Access balance mappings directly - **Access Control**: Check role assignments and permissions - **Debugging**: Investigate contract state during development ## Important Notes - Storage values are always 32 bytes (64 hex characters plus 0x prefix) - Unused storage slots return `0x0000000000000000000000000000000000000000000000000000000000000000` - Storage layout depends on Solidity version and compiler optimizations - For dynamic arrays, slot contains length; actual data starts at `keccak256(slot)` - Packed structs may share storage slots for gas optimization --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_getTransactionByHash - Get Transactio... # eth_getTransactionByHash Returns information about a transaction requested by transaction hash. Essential for tracking transaction status and details. ## When to Use This Method `eth_getTransactionByHash` is crucial for: - **Transaction Tracking** - Monitor transaction status after submission - **Payment Verification** - Confirm payment details and recipients - **Transaction Explorers** - Build transaction detail pages - **Debugging** - Investigate failed or stuck transactions ## Parameters 1. **Transaction Hash** - `DATA`, 32 Bytes - Hash of the transaction to retrieve - Format: `0x` followed by 64 hexadecimal characters ```json { "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": [ "0xba6064a55ed3dc3f34185d57dc000a63639302bf17f6eaf61c2f211d25f73a67" ], "id": 1 } ``` ## Returns `Object` - Transaction object, or `null` when no transaction was found: - `blockHash` - Hash of the block containing this transaction - `blockNumber` - Block number containing this transaction - `from` - Address of the sender - `gas` - Gas provided by the sender - `gasPrice` - Gas price in wei - `maxFeePerGas` - Maximum fee per gas (EIP-1559) - `maxPriorityFeePerGas` - Maximum priority fee per gas (EIP-1559) - `hash` - Transaction hash - `input` - Input data sent with transaction - `nonce` - Number of transactions from sender - `to` - Receiver address (null for contract creation) - `transactionIndex` - Position in the block - `value` - Value transferred in wei - `type` - Transaction type (0x0, 0x1, 0x2) - `v`, `r`, `s` - Signature values ## Implementation Examples ```javascript const provider = new JsonRpcProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); // Transaction tracking system class TransactionTracker { constructor(provider) { this.provider = provider; this.cache = new Map(); } async getTransaction(txHash) { // Check cache first if (this.cache.has(txHash)) { const cached = this.cache.get(txHash); if (Date.now() - cached.timestamp < 5000) { return cached.data; } } // Fetch transaction const tx = await this.provider.getTransaction(txHash); if (!tx) { return { status: 'not_found' }; } // Cache the result const result = { hash: tx.hash, from: tx.from, to: tx.to, value: tx.value.toString(), gasPrice: tx.gasPrice?.toString(), gasLimit: tx.gasLimit.toString(), nonce: tx.nonce, data: tx.data, blockNumber: tx.blockNumber, blockHash: tx.blockHash, confirmations: tx.confirmations, status: tx.blockNumber ? 'confirmed' : 'pending', type: tx.type, maxFeePerGas: tx.maxFeePerGas?.toString(), maxPriorityFeePerGas: tx.maxPriorityFeePerGas?.toString() }; this.cache.set(txHash, { data: result, timestamp: Date.now() }); return result; } async waitForConfirmation(txHash, confirmations = 1, timeout = 60000) { const startTime = Date.now(); while (Date.now() - startTime < timeout) { const tx = await this.getTransaction(txHash); if (tx.status === 'not_found') { await new Promise(resolve => setTimeout(resolve, 2000)); continue; } if (tx.confirmations >= confirmations) { return tx; } await new Promise(resolve => setTimeout(resolve, 2000)); } throw new Error('Transaction confirmation timeout'); } async getTransactionWithReceipt(txHash) { const [tx, receipt] = await Promise.all([ this.getTransaction(txHash), this.provider.getTransactionReceipt(txHash) ]); if (tx.status === 'not_found') { return tx; } return { ...tx, receipt: receipt ? { status: receipt.status, gasUsed: receipt.gasUsed.toString(), effectiveGasPrice: receipt.effectiveGasPrice?.toString(), logs: receipt.logs.length, contractAddress: receipt.contractAddress } : null }; } } // Usage example async function trackPayment(txHash) { const tracker = new TransactionTracker(provider); console.log('Tracking transaction:', txHash); // Get initial status const tx = await tracker.getTransaction(txHash); console.log('Status:', tx.status); if (tx.status === 'pending') { console.log('Waiting for confirmation...'); const confirmed = await tracker.waitForConfirmation(txHash, 2); console.log('Confirmed in block:', confirmed.blockNumber); } // Get full details with receipt const fullDetails = await tracker.getTransactionWithReceipt(txHash); console.log('Transaction details:', fullDetails); return fullDetails; } ``` ```python from web3 import Web3 from typing import Optional, Dict, Any w3 = Web3(Web3.HTTPProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY')) class TransactionMonitor: """Monitor and analyze transactions on Ethereum""" def __init__(self, w3_instance): self.w3 = w3_instance self.tx_cache = {} def get_transaction_details(self, tx_hash: str) -> Dict[str, Any]: """Get comprehensive transaction details""" # Convert to hex if needed if not tx_hash.startswith('0x'): tx_hash = '0x' + tx_hash # Check cache if tx_hash in self.tx_cache: cached = self.tx_cache[tx_hash] if time.time() - cached['timestamp'] < 5: return cached['data'] try: # Fetch transaction tx = self.w3.eth.get_transaction(tx_hash) if not tx: return {'status': 'not_found', 'hash': tx_hash} # Parse transaction details result = { 'hash': tx.hash.hex(), 'from': tx['from'], 'to': tx.get('to'), 'value': str(tx.value), 'value_eth': self.w3.from_wei(tx.value, 'ether'), 'gas': tx.gas, 'gas_price': str(tx.gasPrice) if tx.get('gasPrice') else None, 'max_fee_per_gas': str(tx.get('maxFeePerGas', 0)), 'max_priority_fee': str(tx.get('maxPriorityFeePerGas', 0)), 'nonce': tx.nonce, 'block_number': tx.blockNumber, 'block_hash': tx.blockHash.hex() if tx.blockHash else None, 'transaction_index': tx.transactionIndex, 'type': tx.type, 'input': tx.input.hex(), 'status': 'confirmed' if tx.blockNumber else 'pending' } # Calculate confirmations if tx.blockNumber: current_block = self.w3.eth.block_number result['confirmations'] = current_block - tx.blockNumber else: result['confirmations'] = 0 # Cache result self.tx_cache[tx_hash] = { 'data': result, 'timestamp': time.time() } return result except Exception as e: return {'status': 'error', 'error': str(e), 'hash': tx_hash} def decode_input_data(self, input_data: str) -> Dict[str, Any]: """Decode transaction input data""" if not input_data or input_data == '0x': return {'type': 'transfer', 'data': None} # Check for common function signatures signatures = { '0xa9059cbb': 'transfer(address,uint256)', '0x095ea7b3': 'approve(address,uint256)', '0x23b872dd': 'transferFrom(address,address,uint256)', '0x70a08231': 'balanceOf(address)', '0x18160ddd': 'totalSupply()', '0x3ccfd60b': 'withdraw()', '0xd0e30db0': 'deposit()' } if len(input_data) >= 10: method_id = input_data[:10] if method_id in signatures: return { 'type': 'contract_call', 'method': signatures[method_id], 'data': input_data[10:] } return {'type': 'unknown', 'data': input_data} async def wait_for_transaction( self, tx_hash: str, confirmations: int = 1, timeout: int = 60 ) -> Dict[str, Any]: """Wait for transaction confirmation""" start_time = time.time() while time.time() - start_time < timeout: tx = self.get_transaction_details(tx_hash) if tx['status'] == 'not_found': await asyncio.sleep(2) continue if tx['status'] == 'confirmed' and tx['confirmations'] >= confirmations: return tx await asyncio.sleep(2) raise TimeoutError(f"Transaction {tx_hash} not confirmed within {timeout} seconds") def analyze_transaction(self, tx_hash: str) -> Dict[str, Any]: """Analyze transaction for insights""" tx = self.get_transaction_details(tx_hash) if tx['status'] in ['not_found', 'error']: return tx analysis = { 'basic_info': tx, 'decoded_input': self.decode_input_data(tx['input']), 'is_contract_creation': tx['to'] is None, 'is_token_transfer': len(tx['input']) > 2, 'gas_efficiency': None } # Calculate gas efficiency for confirmed transactions if tx['status'] == 'confirmed': try: receipt = self.w3.eth.get_transaction_receipt(tx_hash) gas_used = receipt.gasUsed gas_limit = tx['gas'] analysis['gas_efficiency'] = { 'used': gas_used, 'limit': gas_limit, 'efficiency': f"{(gas_used / gas_limit * 100):.2f}%" } except: pass return analysis # Usage examples monitor = TransactionMonitor(w3) # Get transaction details tx_details = monitor.get_transaction_details( "0xba6064a55ed3dc3f34185d57dc000a63639302bf17f6eaf61c2f211d25f73a67" ) # Analyze transaction analysis = monitor.analyze_transaction( "0xba6064a55ed3dc3f34185d57dc000a63639302bf17f6eaf61c2f211d25f73a67" ) print(f"Transaction from: {tx_details['from']}") print(f"Value: {tx_details['value_eth']} ETH") print(f"Status: {tx_details['status']}") print(f"Confirmations: {tx_details['confirmations']}") ``` ## Common Use Cases ### 1. Payment Verification System ```javascript // Verify payment received async function verifyPayment(txHash, expectedAmount, expectedRecipient) { const tx = await provider.getTransaction(txHash); if (!tx) { return { valid: false, reason: 'Transaction not found' }; } // Check recipient if (tx.to?.toLowerCase() !== expectedRecipient.toLowerCase()) { return { valid: false, reason: 'Wrong recipient' }; } // Check amount if (tx.value.toString() !== expectedAmount) { return { valid: false, reason: 'Wrong amount' }; } // Check confirmations if (!tx.blockNumber) { return { valid: false, reason: 'Transaction pending' }; } const receipt = await provider.getTransactionReceipt(txHash); if (receipt.status === 0) { return { valid: false, reason: 'Transaction failed' }; } return { valid: true, confirmations: tx.confirmations, blockNumber: tx.blockNumber }; } ``` ### 2. Transaction History Builder ```javascript // Build transaction history for address async function getAddressTransactions(address, txHashes) { const transactions = []; for (const hash of txHashes) { const tx = await provider.getTransaction(hash); if (!tx) continue; const isIncoming = tx.to?.toLowerCase() === address.toLowerCase(); const isOutgoing = tx.from.toLowerCase() === address.toLowerCase(); transactions.push({ hash: tx.hash, type: isIncoming ? 'incoming' : 'outgoing', from: tx.from, to: tx.to, value: ethers.formatEther(tx.value), timestamp: tx.blockNumber ? (await provider.getBlock(tx.blockNumber)).timestamp : null, status: tx.blockNumber ? 'confirmed' : 'pending', gasPrice: tx.gasPrice ? ethers.formatGwei(tx.gasPrice) : null, confirmations: tx.confirmations }); } return transactions.sort((a, b) => b.timestamp - a.timestamp); } ``` ### 3. Gas Price Analysis ```javascript // Analyze gas usage patterns async function analyzeGasUsage(txHash) { const tx = await provider.getTransaction(txHash); if (!tx) { throw new Error('Transaction not found'); } const receipt = await provider.getTransactionReceipt(txHash); const block = await provider.getBlock(tx.blockNumber); return { txHash: tx.hash, gasLimit: tx.gasLimit.toString(), gasUsed: receipt ? receipt.gasUsed.toString() : null, gasPrice: tx.gasPrice ? ethers.formatGwei(tx.gasPrice) : null, maxFeePerGas: tx.maxFeePerGas ? ethers.formatGwei(tx.maxFeePerGas) : null, maxPriorityFee: tx.maxPriorityFeePerGas ? ethers.formatGwei(tx.maxPriorityFeePerGas) : null, baseFee: block.baseFeePerGas ? ethers.formatGwei(block.baseFeePerGas) : null, efficiency: receipt ? ((Number(receipt.gasUsed) / Number(tx.gasLimit)) * 100).toFixed(2) + '%' : null, totalCost: receipt && tx.gasPrice ? ethers.formatEther(receipt.gasUsed * tx.gasPrice) : null }; } ``` ## Error Handling | Error Scenario | Description | Solution | |----------------|-------------|----------| | `null` response | Transaction not found | Check hash validity, wait for propagation | | Network timeout | RPC connection issues | Retry with exponential backoff | | Invalid hash | Malformed transaction hash | Validate hash format (66 characters) | ```javascript async function safeGetTransaction(txHash, retries = 3) { // Validate hash format if (!/^0x[a-fA-F0-9]{64}$/.test(txHash)) { throw new Error('Invalid transaction hash format'); } for (let i = 0; i < retries; i++) { try { const tx = await provider.getTransaction(txHash); if (tx) { return tx; } // Wait before retry if not found if (i < retries - 1) { await new Promise(resolve => setTimeout(resolve, 2000 * (i + 1))); } } catch (error) { if (i === retries - 1) { throw error; } await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1))); } } return null; } ``` *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_getTransactionCount - Get Centrifuge... # eth_getTransactionCount Retrieves the number of transactions sent from an account on the Centrifuge network. This method returns the account's nonce, which is essential for transaction ordering and preventing replay attacks. The nonce represents the count of confirmed transactions from the specified address. ## Description The `eth_getTransactionCount` method is crucial for Centrifuge blockchain interaction as it provides the current transaction count (nonce) for any account. This value must be included in every transaction to ensure proper ordering and prevent duplicate transactions on the Centrifuge Mainnet network. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | string | Yes | The Centrifuge address (20-byte hex string with 0x prefix) to get transaction count for | | `blockNumber` | string | Yes | Block number as hex string, or block tag: "latest", "earliest", "pending", "safe", "finalized" | ### Block Parameter Options - `"latest"` - Most recent confirmed block (recommended for confirmed count) - `"pending"` - Include pending transactions in mempool (use for next nonce) - `"earliest"` - Genesis block - `"safe"` - Latest safe head block - `"finalized"` - Latest finalized block - `"0x..."` - Specific block number in hex ## Returns **Type:** `string` Returns the transaction count as a hexadecimal string (e.g., "0x1c" = 28 transactions). This value represents: - For EOA (Externally Owned Accounts): Number of transactions sent - For Contract Accounts: Number of contracts created by this account ## Use Cases - **Transaction Building**: Get next nonce for new transactions - **Wallet Management**: Track account activity and transaction history - **Nonce Management**: Prevent transaction conflicts in DApps - **Account Analysis**: Determine if address is active or new - **Batch Transactions**: Sequence multiple transactions correctly ## Code Examples ```bash # Get latest confirmed transaction count curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x82B58A073faA247C7f68DBd9B4101B26B2D177bF", "latest" ], "id": 1 }' # Get pending transaction count (includes mempool) curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x82B58A073faA247C7f68DBd9B4101B26B2D177bF", "pending" ], "id": 2 }' ``` ```javascript // Get confirmed transaction count for wallet async function getAccountNonce(address) { const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_getTransactionCount', params: [address, 'latest'], id: 1 }) }); const data = await response.json(); return parseInt(data.result, 16); // Convert hex to decimal } // Get pending nonce for transaction building async function getPendingNonce(address) { const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_getTransactionCount', params: [address, 'pending'], id: 1 }) }); const data = await response.json(); return data.result; // Keep as hex for transaction } // Usage examples const vitalikAddress = '0x82B58A073faA247C7f68DBd9B4101B26B2D177bF'; getAccountNonce(vitalikAddress).then(count => { console.log(`Account has sent ${count} transactions`); }); getPendingNonce(vitalikAddress).then(nonce => { console.log(`Next transaction nonce: ${nonce}`); }); ``` ```python def get_transaction_count(address, block_tag="latest"): """Get transaction count for an address on Ethereum""" url = "https://api-centrifuge.n.dwellir.com/YOUR_API_KEY" payload = { "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [address, block_tag], "id": 1 } response = requests.post(url, json=payload) result = response.json() if 'error' in result: raise Exception(f"RPC Error: {result['error']}") return result['result'] def compare_nonces(address): """Compare confirmed vs pending transaction counts""" confirmed = get_transaction_count(address, "latest") pending = get_transaction_count(address, "pending") confirmed_int = int(confirmed, 16) pending_int = int(pending, 16) return { 'confirmed_count': confirmed_int, 'pending_count': pending_int, 'pending_transactions': pending_int - confirmed_int, 'next_nonce': pending } # Example usage vitalik_address = "0x82B58A073faA247C7f68DBd9B4101B26B2D177bF" # Get basic transaction count count = get_transaction_count(vitalik_address) print(f"Transaction count: {int(count, 16)}") # Analyze account activity nonce_info = compare_nonces(vitalik_address) print(f"Confirmed transactions: {nonce_info['confirmed_count']}") print(f"Pending transactions: {nonce_info['pending_transactions']}") print(f"Next nonce to use: {nonce_info['next_nonce']}") ``` ## Response Examples ### Latest Block Transaction Count ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1c" } ``` ### Pending Transaction Count ```json { "jsonrpc": "2.0", "id": 2, "result": "0x1e" } ``` ## Important Notes ### Nonce Management - **Transaction Ordering**: Each transaction must use the next sequential nonce - **Pending vs Confirmed**: Use "pending" to include mempool transactions when building new transactions - **Failed Transactions**: Failed transactions still consume the nonce and increment the count - **Nonce Gaps**: Transactions with gaps in nonce sequence will be held until earlier nonces are filled ### Best Practices - Always use "pending" when preparing new transactions to avoid nonce conflicts - Cache nonce values briefly but refresh for each new transaction batch - Handle nonce collisions by incrementing and retrying - Monitor both confirmed and pending counts for wallet applications ### Centrifuge Network Specifics - Centrifuge uses a sequential nonce system for transaction ordering - Transaction finality depends on network confirmation requirements - Nonce management is crucial for Centrifuge DApp development - Consider batch transaction sequencing for gas optimization ### Common Use Cases 1. **Wallet Integration**: Track user transaction history 2. **DApp Development**: Sequence contract interactions 3. **Transaction Builders**: Generate properly ordered transactions 4. **Account Analysis**: Determine account activity levels 5. **Automated Systems**: Manage nonce for bot transactions --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_getTransactionReceipt - Get Receipt # eth_getTransactionReceipt Returns the receipt of a transaction by transaction hash. Provides execution status, gas consumption, and emitted logs. ## When to Use This Method `eth_getTransactionReceipt` is essential for: - **Transaction Confirmation** - Verify successful execution - **Event Monitoring** - Access emitted logs and events - **Gas Analysis** - Track actual gas consumption - **Contract Deployment** - Get deployed contract addresses ## Parameters 1. **Transaction Hash** - `DATA`, 32 Bytes - Hash of the executed transaction - Format: `0x` followed by 64 hexadecimal characters ```json { "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": [ "0xf1f24140121b76826eb408d0683baed8f3a189c7974cfbd47ef71818e8e4fcd9" ], "id": 1 } ``` ## Returns `Object` - Receipt object, or `null` when no receipt was found: - `transactionHash` - Hash of the transaction - `transactionIndex` - Position in the block - `blockHash` - Hash of the block - `blockNumber` - Block number - `from` - Sender address - `to` - Receiver address (null for contract creation) - `cumulativeGasUsed` - Total gas used in block up to this transaction - `gasUsed` - Gas used by this specific transaction - `effectiveGasPrice` - Actual gas price paid - `contractAddress` - Created contract address (if contract creation) - `logs` - Array of log objects from events - `logsBloom` - Bloom filter for logs - `status` - `0x1` (success) or `0x0` (failure) - `type` - Transaction type - `l1Fee` - L1 data posting fee (Centrifuge specific) - `l1GasPrice` - L1 gas price used (Centrifuge specific) - `l1GasUsed` - L1 gas consumed (Centrifuge specific) ## Implementation Examples ```javascript const provider = new JsonRpcProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); // Enhanced receipt processor class ReceiptProcessor { constructor(provider) { this.provider = provider; } async getReceipt(txHash) { const receipt = await this.provider.getTransactionReceipt(txHash); if (!receipt) { return null; } return { hash: receipt.hash, status: receipt.status === 1 ? 'success' : 'failed', blockNumber: receipt.blockNumber, blockHash: receipt.blockHash, from: receipt.from, to: receipt.to, contractAddress: receipt.contractAddress, gasUsed: receipt.gasUsed.toString(), effectiveGasPrice: receipt.effectiveGasPrice.toString(), cumulativeGasUsed: receipt.cumulativeGasUsed.toString(), logs: receipt.logs.length, type: receipt.type, // Centrifuge Mainnet specific fields l1Fee: receipt.l1Fee?.toString(), l1GasPrice: receipt.l1GasPrice?.toString(), l1GasUsed: receipt.l1GasUsed?.toString() }; } async parseEvents(txHash, abi) { const receipt = await this.provider.getTransactionReceipt(txHash); if (!receipt) { throw new Error('Receipt not found'); } const iface = new ethers.Interface(abi); const events = []; for (const log of receipt.logs) { try { const parsed = iface.parseLog({ topics: log.topics, data: log.data }); events.push({ name: parsed.name, signature: parsed.signature, args: Object.fromEntries( Object.entries(parsed.args).filter(([key]) => isNaN(key)) ), address: log.address, blockNumber: log.blockNumber, transactionIndex: log.transactionIndex, logIndex: log.logIndex }); } catch { // Not an event from this ABI events.push({ name: 'Unknown', topics: log.topics, data: log.data, address: log.address }); } } return events; } async calculateTotalCost(txHash) { const [receipt, tx] = await Promise.all([ this.provider.getTransactionReceipt(txHash), this.provider.getTransaction(txHash) ]); if (!receipt || !tx) { throw new Error('Transaction or receipt not found'); } const l2GasCost = receipt.gasUsed * receipt.effectiveGasPrice; const l1GasCost = receipt.l1Fee || 0n; const totalCost = l2GasCost + l1GasCost; return { l2Cost: ethers.formatEther(l2GasCost), l1Cost: ethers.formatEther(l1GasCost), totalCost: ethers.formatEther(totalCost), gasUsed: receipt.gasUsed.toString(), effectiveGasPrice: ethers.formatGwei(receipt.effectiveGasPrice), status: receipt.status === 1 ? 'success' : 'failed' }; } async waitForReceipt(txHash, confirmations = 1, timeout = 60000) { const startTime = Date.now(); while (Date.now() - startTime < timeout) { const receipt = await this.provider.getTransactionReceipt(txHash); if (receipt) { const currentBlock = await this.provider.getBlockNumber(); const confirmationCount = currentBlock - receipt.blockNumber; if (confirmationCount >= confirmations) { return receipt; } } await new Promise(resolve => setTimeout(resolve, 2000)); } throw new Error(`Receipt not found within ${timeout}ms`); } } // ERC20 Transfer event monitoring async function monitorTokenTransfers(txHash) { const processor = new ReceiptProcessor(provider); const ERC20_ABI = [ "event Transfer(address indexed from, address indexed to, uint256 value)", "event Approval(address indexed owner, address indexed spender, uint256 value)" ]; const events = await processor.parseEvents(txHash, ERC20_ABI); const transfers = events.filter(e => e.name === 'Transfer'); for (const transfer of transfers) { console.log(`Transfer detected:`); console.log(` From: ${transfer.args.from}`); console.log(` To: ${transfer.args.to}`); console.log(` Amount: ${ethers.formatUnits(transfer.args.value, 18)}`); console.log(` Token: ${transfer.address}`); } return transfers; } // Contract deployment tracking async function trackDeployment(txHash) { const processor = new ReceiptProcessor(provider); const receipt = await processor.waitForReceipt(txHash); if (receipt.contractAddress) { console.log('Contract deployed at:', receipt.contractAddress); // Verify deployment const code = await provider.getCode(receipt.contractAddress); const isDeployed = code !== '0x'; return { success: receipt.status === 1, address: receipt.contractAddress, deploymentCost: await processor.calculateTotalCost(txHash), verified: isDeployed, blockNumber: receipt.blockNumber }; } else { throw new Error('Not a contract deployment transaction'); } } ``` ```python from web3 import Web3 from eth_utils import event_signature_to_log_topic from typing import Dict, List, Any, Optional w3 = Web3(Web3.HTTPProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY')) class ReceiptAnalyzer: """Analyze and process transaction receipts on Ethereum""" def __init__(self, w3_instance): self.w3 = w3_instance def get_receipt_details(self, tx_hash: str) -> Optional[Dict[str, Any]]: """Get comprehensive receipt details""" try: receipt = self.w3.eth.get_transaction_receipt(tx_hash) if not receipt: return None return { 'transaction_hash': receipt['transactionHash'].hex(), 'status': 'success' if receipt['status'] == 1 else 'failed', 'block_number': receipt['blockNumber'], 'block_hash': receipt['blockHash'].hex(), 'from': receipt['from'], 'to': receipt.get('to'), 'contract_address': receipt.get('contractAddress'), 'gas_used': receipt['gasUsed'], 'effective_gas_price': receipt.get('effectiveGasPrice', 0), 'cumulative_gas_used': receipt['cumulativeGasUsed'], 'logs_count': len(receipt['logs']), 'transaction_index': receipt['transactionIndex'], 'type': receipt.get('type', 0), # Centrifuge Mainnet specific 'l1_fee': receipt.get('l1Fee'), 'l1_gas_price': receipt.get('l1GasPrice'), 'l1_gas_used': receipt.get('l1GasUsed') } except Exception as e: return {'error': str(e), 'tx_hash': tx_hash} def decode_logs(self, tx_hash: str, abi: List[Dict]) -> List[Dict[str, Any]]: """Decode event logs from receipt""" receipt = self.w3.eth.get_transaction_receipt(tx_hash) if not receipt: return [] # Create contract instance for decoding contract = self.w3.eth.contract(abi=abi) decoded_logs = [] for log in receipt['logs']: try: # Try to decode the log decoded = contract.events[log['topics'][0]].process_log(log) decoded_logs.append({ 'event': decoded['event'], 'args': dict(decoded['args']), 'address': log['address'], 'block_number': log['blockNumber'], 'transaction_index': log['transactionIndex'], 'log_index': log['logIndex'] }) except: # Could not decode this log with provided ABI decoded_logs.append({ 'event': 'Unknown', 'topics': [t.hex() for t in log['topics']], 'data': log['data'], 'address': log['address'] }) return decoded_logs def monitor_erc20_events(self, tx_hash: str) -> Dict[str, Any]: """Monitor ERC20 token events in transaction""" # Standard ERC20 events transfer_topic = self.w3.keccak(text="Transfer(address,address,uint256)").hex() approval_topic = self.w3.keccak(text="Approval(address,address,uint256)").hex() receipt = self.w3.eth.get_transaction_receipt(tx_hash) if not receipt: return {'status': 'no_receipt'} transfers = [] approvals = [] for log in receipt['logs']: if len(log['topics']) > 0: topic0 = log['topics'][0].hex() if topic0 == transfer_topic and len(log['topics']) == 3: # Decode Transfer event transfers.append({ 'token': log['address'], 'from': '0x' + log['topics'][1].hex()[26:], 'to': '0x' + log['topics'][2].hex()[26:], 'value': int(log['data'], 16) if log['data'] != '0x' else 0, 'block': log['blockNumber'], 'log_index': log['logIndex'] }) elif topic0 == approval_topic and len(log['topics']) == 3: # Decode Approval event approvals.append({ 'token': log['address'], 'owner': '0x' + log['topics'][1].hex()[26:], 'spender': '0x' + log['topics'][2].hex()[26:], 'value': int(log['data'], 16) if log['data'] != '0x' else 0, 'block': log['blockNumber'], 'log_index': log['logIndex'] }) return { 'transaction_hash': tx_hash, 'status': 'success' if receipt['status'] == 1 else 'failed', 'transfers': transfers, 'approvals': approvals, 'total_events': len(transfers) + len(approvals) } def calculate_transaction_costs(self, tx_hash: str) -> Dict[str, Any]: """Calculate detailed transaction costs including L1 fees""" receipt = self.w3.eth.get_transaction_receipt(tx_hash) tx = self.w3.eth.get_transaction(tx_hash) if not receipt or not tx: return {'error': 'Transaction or receipt not found'} # L2 gas costs gas_used = receipt['gasUsed'] effective_gas_price = receipt.get('effectiveGasPrice', tx.get('gasPrice', 0)) l2_cost = gas_used * effective_gas_price # L1 costs (Centrifuge specific) l1_fee = receipt.get('l1Fee', 0) # Total cost total_cost = l2_cost + l1_fee return { 'transaction_hash': tx_hash, 'gas_used': gas_used, 'gas_limit': tx['gas'], 'gas_efficiency': f"{(gas_used / tx['gas'] * 100):.2f}%", 'effective_gas_price_gwei': self.w3.from_wei(effective_gas_price, 'gwei'), 'l2_cost_eth': self.w3.from_wei(l2_cost, 'ether'), 'l1_cost_eth': self.w3.from_wei(l1_fee, 'ether'), 'total_cost_eth': self.w3.from_wei(total_cost, 'ether'), 'status': 'success' if receipt['status'] == 1 else 'failed' } def wait_for_receipt( self, tx_hash: str, timeout: int = 60, poll_interval: int = 2 ) -> Optional[Dict[str, Any]]: """Wait for transaction receipt with timeout""" start_time = time.time() while time.time() - start_time < timeout: try: receipt = self.w3.eth.get_transaction_receipt(tx_hash) if receipt: return self.get_receipt_details(tx_hash) except: pass time.sleep(poll_interval) return None # Usage examples analyzer = ReceiptAnalyzer(w3) # Get receipt details receipt = analyzer.get_receipt_details( "0xf1f24140121b76826eb408d0683baed8f3a189c7974cfbd47ef71818e8e4fcd9" ) if receipt: print(f"Status: {receipt['status']}") print(f"Gas Used: {receipt['gas_used']}") print(f"Block: {receipt['block_number']}") # Calculate costs costs = analyzer.calculate_transaction_costs( "0xf1f24140121b76826eb408d0683baed8f3a189c7974cfbd47ef71818e8e4fcd9" ) print(f"Total Cost: {costs['total_cost_eth']} ETH") print(f"L1 Cost: {costs['l1_cost_eth']} ETH") # Monitor token events events = analyzer.monitor_erc20_events( "0xf1f24140121b76826eb408d0683baed8f3a189c7974cfbd47ef71818e8e4fcd9" ) print(f"Token Transfers: {len(events['transfers'])}") ``` ## Common Use Cases ### 1. Smart Contract Event Monitoring ```javascript // Monitor DeFi protocol events async function monitorDeFiEvents(txHash) { const DEFI_ABI = [ "event Deposit(address indexed user, uint256 amount, uint256 shares)", "event Withdraw(address indexed user, uint256 amount, uint256 shares)", "event Swap(address indexed user, address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut)" ]; const processor = new ReceiptProcessor(provider); const events = await processor.parseEvents(txHash, DEFI_ABI); for (const event of events) { switch(event.name) { case 'Deposit': console.log(`User ${event.args.user} deposited ${event.args.amount}`); break; case 'Withdraw': console.log(`User ${event.args.user} withdrew ${event.args.amount}`); break; case 'Swap': console.log(`Swap: ${event.args.amountIn} ${event.args.tokenIn} -> ${event.args.amountOut} ${event.args.tokenOut}`); break; } } return events; } ``` ### 2. Failed Transaction Debugging ```javascript // Debug failed transactions async function debugFailedTransaction(txHash) { const receipt = await provider.getTransactionReceipt(txHash); if (!receipt) { return { error: 'Receipt not found' }; } if (receipt.status === 1) { return { status: 'success' }; } // Get transaction details for more context const tx = await provider.getTransaction(txHash); // Try to decode revert reason try { const result = await provider.call({ to: tx.to, from: tx.from, data: tx.data, value: tx.value, gasLimit: tx.gasLimit }, tx.blockNumber - 1); } catch (error) { return { status: 'failed', gasUsed: receipt.gasUsed.toString(), gasLimit: tx.gasLimit.toString(), revertReason: error.reason || error.message, block: receipt.blockNumber }; } } ``` ### 3. Multi-Transaction Batch Analysis ```javascript // Analyze batch of transactions async function analyzeBatch(txHashes) { const processor = new ReceiptProcessor(provider); const results = []; for (const hash of txHashes) { const receipt = await processor.getReceipt(hash); const cost = await processor.calculateTotalCost(hash); results.push({ hash: hash, status: receipt?.status, gasUsed: receipt?.gasUsed, totalCost: cost?.totalCost, l1Cost: cost?.l1Cost, blockNumber: receipt?.blockNumber }); } // Calculate statistics const successful = results.filter(r => r.status === 'success').length; const totalGas = results.reduce((sum, r) => sum + BigInt(r.gasUsed || 0), 0n); return { transactions: results, statistics: { total: txHashes.length, successful: successful, failed: txHashes.length - successful, totalGasUsed: totalGas.toString() } }; } ``` ## Error Handling | Error Scenario | Description | Solution | |----------------|-------------|----------| | `null` receipt | Transaction not mined yet | Wait and retry | | Status `0x0` | Transaction failed | Check revert reason | | Missing L1 fee data | Old transaction format | Handle gracefully | ```javascript async function robustGetReceipt(txHash, maxRetries = 10) { for (let i = 0; i < maxRetries; i++) { try { const receipt = await provider.getTransactionReceipt(txHash); if (receipt) { // Ensure all fields are present return { ...receipt, l1Fee: receipt.l1Fee || 0n, l1GasPrice: receipt.l1GasPrice || 0n, l1GasUsed: receipt.l1GasUsed || 0n, effectiveGasPrice: receipt.effectiveGasPrice || receipt.gasPrice }; } // Exponential backoff await new Promise(resolve => setTimeout(resolve, Math.min(1000 * Math.pow(2, i), 30000)) ); } catch (error) { if (i === maxRetries - 1) throw error; } } return null; } ``` *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_hashrate - Get node hashrate(Centrifuge) # eth_hashrate Get node hashrate on the Centrifuge network. ## Parameters Varies by method. Please refer to the official [Centrifuge JSON-RPC: eth_hashrate](https://ethereum.org/developers/docs/apis/json-rpc/#eth_hashrate) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_hashrate", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_hashrate', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_maxPriorityFeePerGas - Get priority f... # eth_maxPriorityFeePerGas Returns the priority fee needed for inclusion in the next block on the Centrifuge network. This method is essential for EIP-1559 transactions, helping you determine the appropriate tip to incentivize miners. ## Parameters None required - this method takes no parameters. ## Returns `QUANTITY` - The hex-encoded priority fee per gas in wei needed for inclusion in the next block. ## Implementation Example ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_maxPriorityFeePerGas', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x77359400" } ``` The result `0x77359400` represents 2,000,000,000 wei (2 gwei) as the suggested priority fee. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_mining - Check if node is mining(Centrifuge) # eth_mining Check if node is mining on the Centrifuge network. ## Parameters Varies by method. Please refer to the official [Centrifuge JSON-RPC: eth_mining](https://ethereum.org/developers/docs/apis/json-rpc/#eth_mining) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_mining', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_newBlockFilter - Subscribe to new blocks # eth_newBlockFilter Subscribe to new blocks on the Centrifuge network. ## Parameters Varies by method. Please refer to the official [Centrifuge JSON-RPC: eth_newBlockFilter](https://ethereum.org/developers/docs/apis/json-rpc/#eth_newblockfilter) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_newBlockFilter', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_newFilter - Create event filter # eth_newFilter Creates a filter object, based on filter options, to notify when the state changes (logs) on the Centrifuge network. This method is essential for tracking smart contract events and state changes. ## Parameters - `filter` (object, required): The filter object with the following properties: - `fromBlock` (string, optional): Block number (hex) or tag ("earliest", "latest", "pending", "safe", "finalized") to start filtering from. Default: "latest" - `toBlock` (string, optional): Block number (hex) or tag to stop filtering at. Default: "latest" - `address` (string or array, optional): Contract address or array of addresses to monitor for logs - `topics` (array, optional): Array of 32-byte DATA topics. Topics are order-dependent: - First topic is typically the event signature hash - Use `null` to match any value at a specific position - Can provide arrays for "OR" conditions at each position ## Returns - `filterID` (string): A hexadecimal filter identifier to be used with: - `eth_getFilterChanges` - Get new logs since last poll - `eth_getFilterLogs` - Get all accumulated logs - `eth_uninstallFilter` - Remove the filter when no longer needed ## Implementation Example ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "0x1", "toBlock": "0x2", "address": "0x8888f1f195afa192cfee860698584c030f4c9db1", "topics": [ "0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b" ] }], "id": 1 }' ``` ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_newFilter', params: [{ fromBlock: '0x1', toBlock: '0x2', address: '0x8888f1f195afa192cfee860698584c030f4c9db1', topics: [ '0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b' ] }], id: 1 }) }); const data = await response.json(); const filterID = data.result; console.log('Filter ID:', filterID); ``` ```python url = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY' headers = {'Content-Type': 'application/json'} payload = { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "0x1", "toBlock": "0x2", "address": "0x8888f1f195afa192cfee860698584c030f4c9db1", "topics": [ "0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b" ] }], "id": 1 } response = requests.post(url, headers=headers, data=json.dumps(payload)) data = response.json() filter_id = data['result'] print(f'Filter ID: {filter_id}') ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x990a0ab959f87cc519ae825a7e6e7a46" } ``` ## Advanced Usage ### Monitor Multiple Contracts ```json { "params": [{ "fromBlock": "latest", "address": [ "0x1234567890abcdef1234567890abcdef12345678", "0xabcdef1234567890abcdef1234567890abcdef12" ] }] } ``` ### Complex Topic Filtering ```json { "params": [{ "topics": [ "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", // Transfer event null, // Any sender [ // Specific recipients "0x0000000000000000000000001234567890abcdef1234567890abcdef12345678", "0x000000000000000000000000abcdef1234567890abcdef1234567890abcdef12" ] ] }] } ``` ### Monitor All Events from Latest Block ```json { "params": [{ "fromBlock": "latest", "toBlock": "latest" }] } ``` ## Workflow Example ```javascript // 1. Create filter const createFilter = await fetch(url, { method: 'POST', body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_newFilter', params: [{ fromBlock: 'latest' }], id: 1 }) }); const { result: filterID } = await createFilter.json(); // 2. Poll for changes const getChanges = await fetch(url, { method: 'POST', body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_getFilterChanges', params: [filterID], id: 2 }) }); const { result: logs } = await getChanges.json(); // 3. Clean up const uninstall = await fetch(url, { method: 'POST', body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_uninstallFilter', params: [filterID], id: 3 }) }); ``` ## Notes - **Block Range Limits**: Free plans typically limited to 5 blocks, paid plans up to 10,000 blocks - **Filter Timeout**: Filters expire after ~5 minutes of inactivity - poll regularly with `eth_getFilterChanges` - **Topics Order**: Topics are order-dependent; the first topic is usually the event signature hash - **Filter Management**: Always uninstall filters when done to free up resources - **Performance**: Create specific filters to reduce the amount of data processed --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_newPendingTransactionFilter - Monitor... # eth_newPendingTransactionFilter Monitor pending transactions on the Centrifuge network. ## Parameters Varies by method. Please refer to the official [Centrifuge JSON-RPC: eth_newPendingTransactionFilter](https://ethereum.org/developers/docs/apis/json-rpc/#eth_newpendingtransactionfilter) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_newPendingTransactionFilter', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_protocolVersion - Get protocol version(Centrifuge) # eth_protocolVersion Get protocol version on the Centrifuge network. ## Parameters Varies by method. Please refer to the official [Centrifuge JSON-RPC: eth_protocolVersion](https://ethereum.org/developers/docs/apis/json-rpc/#eth_protocolversion) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_protocolVersion", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_protocolVersion', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_sendRawTransaction - Broadcast Signed... # eth_sendRawTransaction Submits a pre-signed transaction to the network for broadcast and execution. Returns the transaction hash if successful. ## When to Use This Method `eth_sendRawTransaction` is required for: - **Sending ETH** - Transfer value between accounts - **Token Transfers** - Execute ERC20/NFT transfers - **Contract Interactions** - Call state-changing functions - **Contract Deployment** - Deploy new smart contracts ## Parameters 1. **Signed Transaction Data** - `DATA` - The signed transaction data in RLP-encoded format - Must be prefixed with `0x` ```json { "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": [ "0xf86c0185046110...signed_transaction_data...90a0cf5e" ], "id": 1 } ``` ## Returns `DATA` - 32 Bytes - The transaction hash, or error if transaction invalid. ## Implementation Examples ```javascript const provider = new JsonRpcProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); // Transaction builder and sender class TransactionManager { constructor(provider, privateKey) { this.provider = provider; this.wallet = new Wallet(privateKey, provider); } async sendETH(to, amount) { try { // Build transaction const tx = { to: to, value: parseEther(amount), // Centrifuge uses EIP-1559 transactions type: 2, chainId: 1, // Centrifuge mainnet }; // Estimate gas and get fee data const [gasLimit, feeData] = await Promise.all([ this.provider.estimateGas({...tx, from: this.wallet.address}), this.provider.getFeeData() ]); tx.gasLimit = gasLimit; tx.maxFeePerGas = feeData.maxFeePerGas; tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; // Sign and send const signedTx = await this.wallet.signTransaction(tx); const txHash = await this.provider.send('eth_sendRawTransaction', [signedTx]); console.log('Transaction sent:', txHash); // Wait for confirmation const receipt = await this.provider.waitForTransaction(txHash); return { hash: txHash, status: receipt.status === 1 ? 'success' : 'failed', blockNumber: receipt.blockNumber, gasUsed: receipt.gasUsed.toString(), effectiveGasPrice: receipt.effectiveGasPrice.toString() }; } catch (error) { console.error('Transaction failed:', error); throw error; } } async sendToken(tokenAddress, to, amount, decimals = 18) { const ERC20_ABI = [ "function transfer(address to, uint256 amount) returns (bool)" ]; const token = new Contract(tokenAddress, ERC20_ABI, this.wallet); // Build transaction const amountWei = parseUnits(amount, decimals); const tx = await token.transfer.populateTransaction(to, amountWei); // Add gas settings const [gasLimit, feeData] = await Promise.all([ this.provider.estimateGas({...tx, from: this.wallet.address}), this.provider.getFeeData() ]); tx.gasLimit = gasLimit * 110n / 100n; // Add 10% buffer tx.maxFeePerGas = feeData.maxFeePerGas; tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; tx.type = 2; tx.chainId = 1; // Sign and send const signedTx = await this.wallet.signTransaction(tx); const txHash = await this.provider.send('eth_sendRawTransaction', [signedTx]); return txHash; } async deployContract(bytecode, abi, constructorArgs = []) { const factory = new ContractFactory(abi, bytecode, this.wallet); // Estimate deployment cost const deployTx = factory.getDeployTransaction(...constructorArgs); const gasLimit = await this.provider.estimateGas({ ...deployTx, from: this.wallet.address }); // Deploy with proper gas settings const contract = await factory.deploy(...constructorArgs, { gasLimit: gasLimit * 120n / 100n, // 20% buffer for deployment maxFeePerGas: (await this.provider.getFeeData()).maxFeePerGas, maxPriorityFeePerGas: (await this.provider.getFeeData()).maxPriorityFeePerGas }); await contract.waitForDeployment(); return { address: await contract.getAddress(), deploymentHash: contract.deploymentTransaction().hash, gasUsed: (await contract.deploymentTransaction().wait()).gasUsed.toString() }; } async batchSend(transactions) { const results = []; const nonce = await this.provider.getTransactionCount(this.wallet.address); for (let i = 0; i < transactions.length; i++) { const tx = { ...transactions[i], nonce: nonce + i, type: 2, chainId: 1, gasLimit: await this.provider.estimateGas({ ...transactions[i], from: this.wallet.address }) }; // Add fee data const feeData = await this.provider.getFeeData(); tx.maxFeePerGas = feeData.maxFeePerGas; tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; // Sign and send const signedTx = await this.wallet.signTransaction(tx); const txHash = await this.provider.send('eth_sendRawTransaction', [signedTx]); results.push({ index: i, hash: txHash, nonce: tx.nonce }); } return results; } } // Advanced transaction with retry logic async function sendWithRetry(provider, signedTx, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { const txHash = await provider.send('eth_sendRawTransaction', [signedTx]); return txHash; } catch (error) { if (error.message.includes('already known')) { // Transaction already in mempool const tx = ethers.Transaction.from(signedTx); return tx.hash; } if (error.message.includes('replacement transaction underpriced')) { // Need to increase gas price throw new Error('Gas price too low, please rebuild transaction with higher fees'); } if (i === maxRetries - 1) throw error; // Wait before retry await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1))); } } } // Monitor mempool for transaction async function monitorTransaction(provider, txHash) { const startTime = Date.now(); const timeout = 60000; // 1 minute timeout while (Date.now() - startTime < timeout) { // Check if transaction is mined const receipt = await provider.getTransactionReceipt(txHash); if (receipt) { return { status: 'confirmed', blockNumber: receipt.blockNumber, gasUsed: receipt.gasUsed.toString() }; } // Check if still in mempool const tx = await provider.getTransaction(txHash); if (!tx) { return { status: 'dropped' }; } await new Promise(resolve => setTimeout(resolve, 2000)); } return { status: 'timeout' }; } ``` ```python from web3 import Web3 from eth_account import Account from eth_utils import to_wei, from_wei from typing import Dict, Any, Optional, List w3 = Web3(Web3.HTTPProvider('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY')) class TransactionSender: """Handle transaction signing and broadcasting on Ethereum""" def __init__(self, w3_instance, private_key): self.w3 = w3_instance self.account = Account.from_key(private_key) self.address = self.account.address self.chain_id = 1 # Centrifuge mainnet def send_eth(self, to_address: str, amount_eth: float) -> Dict[str, Any]: """Send ETH to an address""" try: # Build transaction nonce = self.w3.eth.get_transaction_count(self.address) # Get current gas prices (EIP-1559) base_fee = self.w3.eth.get_block('latest')['baseFeePerGas'] max_priority_fee = self.w3.eth.max_priority_fee max_fee = base_fee * 2 + max_priority_fee transaction = { 'type': '0x2', # EIP-1559 'chainId': self.chain_id, 'from': self.address, 'to': to_address, 'value': to_wei(amount_eth, 'ether'), 'nonce': nonce, 'maxFeePerGas': max_fee, 'maxPriorityFeePerGas': max_priority_fee, 'gas': 21000 # Standard transfer } # Sign transaction signed = self.account.sign_transaction(transaction) # Send transaction tx_hash = self.w3.eth.send_raw_transaction(signed.rawTransaction) # Wait for receipt receipt = self.w3.eth.wait_for_transaction_receipt(tx_hash, timeout=60) return { 'success': receipt['status'] == 1, 'hash': tx_hash.hex(), 'block': receipt['blockNumber'], 'gas_used': receipt['gasUsed'], 'effective_gas_price': receipt['effectiveGasPrice'], 'total_fee_eth': from_wei( receipt['gasUsed'] * receipt['effectiveGasPrice'], 'ether' ) } except Exception as e: return {'success': False, 'error': str(e)} def send_token( self, token_address: str, to_address: str, amount: int, gas_limit: int = 100000 ) -> Dict[str, Any]: """Send ERC20 tokens""" # ERC20 transfer function signature function_signature = self.w3.keccak(text="transfer(address,uint256)")[:4] # Encode parameters encoded_to = to_address[2:].lower().zfill(64) encoded_amount = hex(amount)[2:].zfill(64) data = function_signature.hex() + encoded_to + encoded_amount # Build transaction nonce = self.w3.eth.get_transaction_count(self.address) transaction = { 'type': '0x2', 'chainId': self.chain_id, 'from': self.address, 'to': token_address, 'value': 0, 'nonce': nonce, 'data': data, 'maxFeePerGas': self.w3.eth.gas_price * 2, 'maxPriorityFeePerGas': self.w3.eth.max_priority_fee, 'gas': gas_limit } # Estimate gas try: estimated_gas = self.w3.eth.estimate_gas(transaction) transaction['gas'] = int(estimated_gas * 1.1) # 10% buffer except: pass # Sign and send signed = self.account.sign_transaction(transaction) tx_hash = self.w3.eth.send_raw_transaction(signed.rawTransaction) return {'hash': tx_hash.hex(), 'nonce': nonce} def deploy_contract( self, bytecode: str, constructor_args: bytes = b'', gas_limit: int = 3000000 ) -> Dict[str, Any]: """Deploy a smart contract""" nonce = self.w3.eth.get_transaction_count(self.address) transaction = { 'type': '0x2', 'chainId': self.chain_id, 'from': self.address, 'nonce': nonce, 'data': bytecode + constructor_args, 'value': 0, 'maxFeePerGas': self.w3.eth.gas_price * 2, 'maxPriorityFeePerGas': self.w3.eth.max_priority_fee, 'gas': gas_limit } # Estimate gas for deployment try: estimated_gas = self.w3.eth.estimate_gas(transaction) transaction['gas'] = int(estimated_gas * 1.2) # 20% buffer except Exception as e: print(f"Gas estimation failed: {e}") # Sign and send signed = self.account.sign_transaction(transaction) tx_hash = self.w3.eth.send_raw_transaction(signed.rawTransaction) # Wait for deployment receipt = self.w3.eth.wait_for_transaction_receipt(tx_hash, timeout=120) return { 'success': receipt['status'] == 1, 'contract_address': receipt.get('contractAddress'), 'hash': tx_hash.hex(), 'gas_used': receipt['gasUsed'] } def send_batch( self, transactions: List[Dict[str, Any]], gas_price_multiplier: float = 1.1 ) -> List[Dict[str, Any]]: """Send multiple transactions in sequence""" results = [] base_nonce = self.w3.eth.get_transaction_count(self.address) for i, tx_data in enumerate(transactions): tx = { 'type': '0x2', 'chainId': self.chain_id, 'from': self.address, 'nonce': base_nonce + i, 'to': tx_data['to'], 'value': tx_data.get('value', 0), 'data': tx_data.get('data', '0x'), 'maxFeePerGas': int(self.w3.eth.gas_price * gas_price_multiplier), 'maxPriorityFeePerGas': self.w3.eth.max_priority_fee, 'gas': tx_data.get('gas', 21000) } try: # Sign and send signed = self.account.sign_transaction(tx) tx_hash = self.w3.eth.send_raw_transaction(signed.rawTransaction) results.append({ 'index': i, 'hash': tx_hash.hex(), 'nonce': tx['nonce'], 'status': 'sent' }) except Exception as e: results.append({ 'index': i, 'error': str(e), 'status': 'failed' }) return results def cancel_transaction(self, nonce: int) -> Optional[str]: """Cancel a pending transaction by sending 0 ETH to self with same nonce""" transaction = { 'type': '0x2', 'chainId': self.chain_id, 'from': self.address, 'to': self.address, 'value': 0, 'nonce': nonce, 'maxFeePerGas': self.w3.eth.gas_price * 3, # Much higher gas 'maxPriorityFeePerGas': self.w3.eth.max_priority_fee * 3, 'gas': 21000 } signed = self.account.sign_transaction(transaction) try: tx_hash = self.w3.eth.send_raw_transaction(signed.rawTransaction) return tx_hash.hex() except Exception as e: return None # Usage examples sender = TransactionSender(w3, 'YOUR_PRIVATE_KEY') # Send ETH result = sender.send_eth('0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5', 0.1) print(f"Transaction hash: {result['hash']}") print(f"Success: {result['success']}") # Send tokens token_result = sender.send_token( token_address='0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', to_address='0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5', amount=1000000 # 1 USDC (6 decimals) ) # Batch transactions batch = [ {'to': '0xAddress1', 'value': to_wei(0.01, 'ether')}, {'to': '0xAddress2', 'value': to_wei(0.02, 'ether')}, {'to': '0xAddress3', 'value': to_wei(0.03, 'ether')} ] batch_results = sender.send_batch(batch) ``` ## Common Use Cases ### 1. Safe Transaction Broadcasting ```javascript // Broadcast with safety checks async function safeBroadcast(wallet, transaction) { // Pre-flight checks const balance = await wallet.provider.getBalance(wallet.address); const estimatedCost = transaction.gasLimit * transaction.maxFeePerGas; if (balance < estimatedCost + transaction.value) { throw new Error('Insufficient balance for transaction'); } // Check nonce const expectedNonce = await wallet.provider.getTransactionCount(wallet.address); if (transaction.nonce && transaction.nonce !== expectedNonce) { console.warn(`Nonce mismatch: expected ${expectedNonce}, got ${transaction.nonce}`); } // Sign transaction const signedTx = await wallet.signTransaction(transaction); // Broadcast with retry let attempts = 0; while (attempts < 3) { try { const txHash = await wallet.provider.send('eth_sendRawTransaction', [signedTx]); return txHash; } catch (error) { if (error.message.includes('already known')) { // Transaction already sent return ethers.Transaction.from(signedTx).hash; } attempts++; if (attempts === 3) throw error; await new Promise(r => setTimeout(r, 1000 * attempts)); } } } ``` ### 2. Optimized Gas Strategy ```javascript // Dynamic gas price management async function optimizedSend(wallet, to, value) { const provider = wallet.provider; // Get network conditions const [block, feeData, gasPrice] = await Promise.all([ provider.getBlock('latest'), provider.getFeeData(), provider.getGasPrice() ]); // Calculate optimal fees const baseFee = block.baseFeePerGas; const priorityFee = feeData.maxPriorityFeePerGas; // Adjust based on network congestion const congestionFactor = Number(baseFee) / Number(parseUnits('10', 'gwei')); const adjustedPriorityFee = priorityFee * BigInt(Math.ceil(congestionFactor)); const transaction = { to: to, value: parseEther(value), type: 2, chainId: 1, maxFeePerGas: baseFee * 2n + adjustedPriorityFee, maxPriorityFeePerGas: adjustedPriorityFee, gasLimit: 21000n }; const signedTx = await wallet.signTransaction(transaction); return await provider.send('eth_sendRawTransaction', [signedTx]); } ``` ### 3. Transaction Queue Management ```javascript // Manage transaction queue class TransactionQueue { constructor(wallet) { this.wallet = wallet; this.queue = []; this.processing = false; } async add(transaction) { this.queue.push(transaction); if (!this.processing) { this.process(); } } async process() { this.processing = true; while (this.queue.length > 0) { const tx = this.queue.shift(); try { // Add nonce tx.nonce = await this.wallet.provider.getTransactionCount(this.wallet.address); // Sign and send const signedTx = await this.wallet.signTransaction(tx); const hash = await this.wallet.provider.send('eth_sendRawTransaction', [signedTx]); console.log(`Transaction sent: ${hash}`); // Wait for confirmation before next await this.wallet.provider.waitForTransaction(hash); } catch (error) { console.error('Transaction failed:', error); // Optionally re-queue or handle error } } this.processing = false; } } ``` ## Error Handling | Error Code | Description | Solution | |------------|-------------|----------| | -32000 | Invalid transaction | Check parameters and signature | | -32001 | Insufficient funds | Ensure account has enough ETH | | -32002 | Nonce too low | Transaction already processed | | -32003 | Transaction underpriced | Increase gas price | ```javascript async function handleSendError(error) { const message = error.message || error.toString(); if (message.includes('insufficient funds')) { return { error: 'Insufficient balance', recoverable: false }; } if (message.includes('nonce too low')) { return { error: 'Transaction already processed', recoverable: false }; } if (message.includes('replacement transaction underpriced')) { return { error: 'Gas price too low for replacement', recoverable: true }; } if (message.includes('transaction already known')) { return { error: 'Transaction already in mempool', recoverable: false }; } return { error: message, recoverable: false }; } ``` *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_sendTransaction - Send transaction (w... # eth_sendTransaction > **Important**: Dwellir's shared Centrifuge endpoints do not manage user private keys. JSON-RPC nodes cannot unlock your account, so `eth_sendTransaction` calls will fail. Sign transactions client-side and broadcast them with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Why this method is disabled on shared nodes - [`eth_sendTransaction` requires the node to hold and unlock the `from` account's private key](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction). - Managed infrastructure providers disable it for security reasons rather than storing customer keys on shared servers (for example, [Infura explicitly blocks the method on shared endpoints](https://docs.infura.io/api/networks/ethereum/json-rpc-methods/eth_sendtransaction)). ## Recommended workflow 1. Build the raw transaction locally with your wallet or SDK. 2. Sign the payload client-side (hardware wallet, custodial service, or library). 3. Submit the signed hex string with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Example response from the shared endpoint ```bash curl -s -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"0x0000000000000000000000000000000000000000"}],"id":1}' ``` ```json {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"unknown account"}} ``` Need help? Contact our [support team](mailto:support@dwellir.com) or use the dedicated [`eth_sendRawTransaction`](./eth_sendRawTransaction) guide. --- ## eth_signTransaction - Sign transaction (r... # eth_signTransaction Signs a transaction using an unlocked account on the node. **Important**: Most RPC providers don't support this method for security reasons, as it requires private keys to be stored on the server. ## Security Considerations - This method requires an unlocked account on the node - Private keys must be available to the RPC server - Most production RPC providers disable this method - Use client-side signing libraries instead for better security ## Parameters 1. `Object` - The transaction object: - `from`: `DATA`, 20 Bytes - The address the transaction is sent from - `to`: `DATA`, 20 Bytes - (optional) The address the transaction is directed to - `gas`: `QUANTITY` - (optional) Integer of the gas provided for the transaction execution - `gasPrice`: `QUANTITY` - (optional) Integer of the gasPrice used for each paid gas - `value`: `QUANTITY` - (optional) Integer of the value sent with this transaction - `data`: `DATA` - (optional) The compiled code of a contract OR the hash of the invoked method signature and encoded parameters ## Returns `DATA` - The signed transaction data, ready for transmission via `eth_sendRawTransaction`. ## Implementation Example :::note Heads up `eth_signTransaction` requires access to an unlocked account, which Dwellir's shared RPC endpoints do not provide. Sign the payload locally (wallet, HSM, or KMS) and then broadcast with `eth_sendRawTransaction`. ::: ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_signTransaction', params: [{ from: '0x9b2055d370f73ec7d8a03e965129118dc8f5bf83', to: '0xd46e8dd67c5d32be8058bb8eb970870f07244567', gas: '0x76c0', gasPrice: '0x9184e72a000', value: '0x9184e72a' }], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0xf86c808504a817c8008276c094d46e8dd67c5d32be8058bb8eb970870f072445675849184e72a8001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804" } ``` **Note**: This method is typically not available on hosted RPC providers for security reasons. The response shows a signed transaction ready for broadcast. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_syncing - Check node sync status # eth_syncing Check node sync status on the Centrifuge network. ## Parameters Varies by method. Please refer to the official [Centrifuge JSON-RPC: eth_syncing](https://ethereum.org/developers/docs/apis/json-rpc/#eth_syncing) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_syncing', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## eth_uninstallFilter - Uninstall Filter # eth_uninstallFilter Remove filter subscription on the Centrifuge network. ## Parameters Varies by method. Please refer to the official [Centrifuge JSON-RPC: eth_uninstallFilter](https://ethereum.org/developers/docs/apis/json-rpc/#eth_uninstallfilter) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash # Create a short-lived filter so we have an ID to remove (requires jq) FILTER_ID=$(curl -s -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": null, "topics": [] }], "id": 1 }' | jq -r '.result') # Uninstall the filter and confirm the response curl -s -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d "$(jq -n --arg id \"$FILTER_ID\" '{jsonrpc:\"2.0\", method:\"eth_uninstallFilter\", params:[$id], id:1}')" ``` ```javascript const endpoint = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY'; const createFilter = async () => { const payload = { jsonrpc: '2.0', method: 'eth_newFilter', params: [{ fromBlock: 'latest', toBlock: 'latest', address: null, topics: [] }], id: 1 }; const response = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); const { result } = await response.json(); return result; }; const filterId = await createFilter(); const response = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_uninstallFilter', params: [filterId], id: 2 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## grandpa_roundState - Centrifuge RPC Method # grandpa_roundState Returns the state of the current GRANDPA finality round on Centrifuge. GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) is the finality gadget used by Substrate chains. ## Use Cases - **Finality monitoring** - Track consensus progress for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Validator analysis** - Monitor prevote/precommit participation - **Chain health checks** - Detect finality delays or stalls ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `setId` | `u64` | Current authority set ID | | `best` | `RoundState` | Best round state | | `background` | `Vec` | Background rounds | ### RoundState Structure | Field | Type | Description | |-------|------|-------------| | `round` | `u64` | Round number | | `totalWeight` | `u64` | Total validator weight | | `thresholdWeight` | `u64` | Weight needed for supermajority | | `prevotes` | `Prevotes` | Prevote information | | `precommits` | `Precommits` | Precommit information | ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "grandpa_roundState", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const roundState = await api.rpc.grandpa.roundState(); console.log('Set ID:', roundState.setId.toString()); console.log('Best round:', roundState.best.round.toString()); console.log('Total weight:', roundState.best.totalWeight.toString()); console.log('Threshold:', roundState.best.thresholdWeight.toString()); await api.disconnect(); ``` ```python url = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'grandpa_roundState', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json()['result'] print(f"Set ID: {result['setId']}") print(f"Round: {result['best']['round']}") print(f"Total weight: {result['best']['totalWeight']}") ``` ## Understanding GRANDPA Rounds 1. **Prevote phase** - Validators vote on best block they've seen 2. **Precommit phase** - Validators commit to finalize if supermajority prevoted 3. **Finalization** - Block is finalized when 2/3+ weight precommits ## Related Methods - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get current finalized hash - [`beefy_getFinalizedHead`](./beefy_getFinalizedHead) - BEEFY finality (if enabled) --- ## Centrifuge RPC Documentation # Centrifuge RPC API Documentation ## Overview Centrifuge is the leading Real-World Asset (RWA) protocol and Polkadot parachain, providing infrastructure for tokenizing, managing, and investing in real-world financial assets. Built on the Substrate framework, Centrifuge bridges traditional finance with DeFi, enabling businesses to access instant, bankless liquidity through tokenized credit, real estate, treasuries, and other real-world assets. This documentation provides comprehensive coverage of Centrifuge's JSON-RPC API methods, enabling developers to interact with Centrifuge nodes for building applications, wallets, explorers, and other blockchain tools. ## Network Information ### Mainnet (Centrifuge) - **Parachain ID**: 2031 - **Native Token**: CFG - **Token Decimals**: 18 - **SS58 Prefix**: 36 - **Consensus**: Nominated Proof-of-Stake (NPoS) via Polkadot - **Framework**: Substrate - **Genesis Hash**: 0xb3db41421702df9a7fcac62b53ffeac85f7853cc4e689e0b93aeb3db18c09d82 ## Connection Endpoints ### HTTPS Endpoint ``` https://api-centrifuge.n.dwellir.com/{YOUR_API_KEY} ``` ### WebSocket Endpoint ``` wss://api-centrifuge.n.dwellir.com/{YOUR_API_KEY} ``` ## Authentication Authentication is done via the URL path. Replace `{YOUR_API_KEY}` with your actual API key obtained from [dwellir.com](https://www.dwellir.com). ## API Categories Centrifuge's RPC API is organized into the following method categories: ### Core APIs #### [Author Methods](/centrifuge#author-methods) Submit and manage extrinsics (transactions) on the network. #### [Chain Methods](/centrifuge#chain-methods) Query blockchain data including blocks, headers, and finalized state. #### [State Methods](/centrifuge#state-methods) Access runtime storage, metadata, and proof generation. #### [System Methods](/centrifuge#system-methods) Node information, health checks, and network properties. ### Specialized APIs #### [BEEFY Methods](/centrifuge#beefy-methods) Bridge Efficiency Enabling Finality Yielder protocol operations. #### [Grandpa Methods](/centrifuge#grandpa-methods) GRANDPA finality gadget operations and proofs. #### [Child State Methods](/centrifuge#child-state-methods) Manage child storage tries for contracts and parachains. #### [Sync State Methods](/centrifuge#sync-state-methods) Monitor and manage node synchronization state. ## Quick Start Examples ### Get Latest Block ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'chain_getBlock', params: [], id: 1 }) }); const data = await response.json(); console.log('Latest block:', data.result); ``` ### Submit Transaction ```python url = "https://api-centrifuge.n.dwellir.com/YOUR_API_KEY" headers = { "Content-Type": "application/json" } # Properly formatted and signed extrinsic extrinsic = "0x..." payload = { "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": [extrinsic], "id": 1 } response = requests.post(url, headers=headers, data=json.dumps(payload)) tx_hash = response.json()["result"] print(f"Transaction hash: {tx_hash}") ``` ### Subscribe to New Blocks (WebSocket) ```javascript const WebSocket = require('ws'); const ws = new WebSocket('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); ws.on('open', () => { ws.send(JSON.stringify({ jsonrpc: '2.0', method: 'chain_subscribeNewHeads', params: [], id: 1 })); }); ws.on('message', (data) => { const response = JSON.parse(data); if (response.params?.result) { console.log('New block:', response.params.result); } }); ``` ## Error Handling Centrifuge RPC errors follow the JSON-RPC 2.0 error format: ```json { "jsonrpc": "2.0", "error": { "code": -32602, "message": "Invalid params", "data": "Expected hex-encoded hash" }, "id": 1 } ``` ### Common Error Codes | Code | Message | Description | |------|---------|-------------| | -32700 | Parse error | Invalid JSON | | -32600 | Invalid request | Missing required fields | | -32601 | Method not found | Unknown RPC method | | -32602 | Invalid params | Invalid method parameters | | -32603 | Internal error | Node processing error | | -32000 | Server error | Custom server errors | ## Best Practices ### 1. Connection Management - Use WebSocket connections for subscriptions and real-time updates - Implement reconnection logic for WebSocket disconnections - Use HTTPS for single queries and transactions ### 2. Error Handling - Always check for error responses before processing results - Implement retry logic with exponential backoff - Log errors for debugging and monitoring ### 3. Performance Optimization - Batch multiple queries when possible - Cache frequently accessed data like metadata - Use specific block hashes for deterministic queries ### 4. Security - Never expose API keys in client-side code - Validate all input data before submission - Use secure storage for private keys ## SDK Support ### Official Libraries - **@polkadot/api** - JavaScript/TypeScript SDK (compatible with Centrifuge) - **py-substrate-interface** - Python SDK - **subxt** - Rust SDK - **go-substrate-rpc-client** - Go SDK ### Integration Example ```javascript // Using @polkadot/api const { ApiPromise, WsProvider } = require('@polkadot/api'); async function connect() { const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query chain data const chain = await api.rpc.system.chain(); console.log(`Connected to ${chain}`); // Get account balance const account = 'YOUR_ADDRESS'; const { data: balance } = await api.query.system.account(account); console.log(`Balance: ${balance.free.toString()}`); return api; } ``` ## Centrifuge Features ### Real-World Asset Tokenization Centrifuge is the leading protocol for tokenizing real-world assets, with $270 million in active loans and nearly $500 million in total financed assets. The platform enables: - **Private Credit** - Tokenization of private credit and lending markets - **Real Estate** - Property-backed tokenized assets - **Treasuries** - Government bond tokenization - **Invoice Financing** - SME invoice and receivables tokenization ### DeFi Integration Centrifuge bridges traditional finance with DeFi through: - **Multichain Support** - Integration across Polkadot, Ethereum, and other chains via Wormhole - **Liquidity Pools** - Tinlake protocol for asset-backed lending pools - **Institutional Grade** - Compliance-ready infrastructure for regulated assets ### CFG Token The CFG token serves multiple purposes: - **Governance** - Community-driven protocol upgrades and parameter changes - **Staking** - Network security through Polkadot's NPoS - **Utility** - Access to protocol features and services ### Polkadot Integration As a Polkadot parachain, Centrifuge benefits from: - **Shared Security** - Protected by Polkadot's validator network - **Cross-Chain Interoperability** - Seamless communication with other parachains - **Scalability** - Leveraging Polkadot's multi-chain architecture ## Additional Resources - [Centrifuge Website](https://centrifuge.io/) - [Centrifuge Documentation](https://docs.centrifuge.io/) - [Centrifuge GitHub](https://github.com/centrifuge) - [Centrifuge Explorer](https://centrifuge.subscan.io/) - [Polkadot Parachains Info](https://parachains.info/details/centrifuge) - [Substrate Documentation](https://docs.substrate.io/) ## Support For additional support or questions: - Email: support@dwellir.com - Documentation: [dwellir.com/docs](https://www.dwellir.com/docs) --- ## Method Categories Select a category below to explore detailed method documentation: --- ## net_listening - Check if node is listening # net_listening Check if node is listening on the Centrifuge network. ## Parameters Varies by method. Please refer to the official [Centrifuge JSON-RPC: net_listening](https://ethereum.org/developers/docs/apis/json-rpc/#net_listening) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'net_listening', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## net_peerCount - Get connected peer count # net_peerCount Get connected peer count on the Centrifuge network. ## Parameters Varies by method. Please refer to the official [Centrifuge JSON-RPC: net_peerCount](https://ethereum.org/developers/docs/apis/json-rpc/#net_peercount) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'net_peerCount', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## net_version - Get network ID # net_version Get network ID on the Centrifuge network. ## Parameters Varies by method. Please refer to the official [Centrifuge JSON-RPC: net_version](https://ethereum.org/developers/docs/apis/json-rpc/#net_version) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'net_version', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## payment_queryFeeDetails - Centrifuge RPC Method # payment_queryFeeDetails Returns a detailed breakdown of fees for a given extrinsic on Centrifuge. Unlike `payment_queryInfo` which returns the total fee, this method separates the fee into its component parts. ## Use Cases - **Fee analysis** - Understand fee composition for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Optimization** - Identify which fee component dominates costs - **Debugging** - Diagnose unexpected fee amounts ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `Bytes` | Yes | SCALE-encoded extrinsic (signed or unsigned) | | `blockHash` | `Hash` | No | Block hash for fee calculation context | ## Returns | Field | Type | Description | |-------|------|-------------| | `inclusionFee` | `Option` | Fee details (null for unsigned extrinsics) | ### InclusionFee Structure | Field | Type | Description | |-------|------|-------------| | `baseFee` | `Balance` | Fixed base fee per extrinsic | | `lenFee` | `Balance` | Fee based on encoded extrinsic length | | `adjustedWeightFee` | `Balance` | Fee based on execution weight | ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "payment_queryFeeDetails", "params": ["0x...encodedExtrinsic"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Create a sample transfer const tx = api.tx.balances.transferKeepAlive( '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 1000000000000n ); // Get fee details const feeDetails = await api.rpc.payment.queryFeeDetails(tx.toHex()); if (feeDetails.inclusionFee.isSome) { const fee = feeDetails.inclusionFee.unwrap(); console.log('Base fee:', fee.baseFee.toString()); console.log('Length fee:', fee.lenFee.toString()); console.log('Weight fee:', fee.adjustedWeightFee.toString()); } await api.disconnect(); ``` ```python url = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY' # Replace with actual encoded extrinsic encoded_extrinsic = '0x...' payload = { 'jsonrpc': '2.0', 'method': 'payment_queryFeeDetails', 'params': [encoded_extrinsic], 'id': 1 } response = requests.post(url, json=payload) result = response.json()['result'] if result['inclusionFee']: fee = result['inclusionFee'] print(f"Base fee: {fee['baseFee']}") print(f"Length fee: {fee['lenFee']}") print(f"Weight fee: {fee['adjustedWeightFee']}") ``` ## Fee Components Explained | Component | Calculation | Optimization | |-----------|-------------|--------------| | **Base fee** | Fixed per extrinsic | Batch calls to share base fee | | **Length fee** | `length * lengthToFee` | Minimize call data size | | **Weight fee** | `weight * weightToFee` | Choose efficient operations | ## Related Methods - [`payment_queryInfo`](./payment_queryInfo) - Get total fee estimate - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction - [`state_call`](./state_call) - Call TransactionPaymentApi directly --- ## payment_queryInfo - Centrifuge RPC Method # payment_queryInfo Estimates the fee for an extrinsic on Centrifuge. ## Use Cases - **Fee estimation** - Calculate transaction costs before sending - **UI display** - Show fees to users for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Transaction planning** - Ensure sufficient funds ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `String` | Yes | Hex-encoded unsigned extrinsic | | `blockHash` | `String` | No | Block hash for fee calculation | ## Request ```json { "jsonrpc": "2.0", "method": "payment_queryInfo", "params": ["0x..."], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `weight` | `Object` | Transaction weight | | `class` | `String` | Dispatch class | | `partialFee` | `String` | Estimated fee | ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "payment_queryInfo", "params": ["0x..."], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Create transfer (unsigned for estimation) const transfer = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000); const info = await transfer.paymentInfo('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'); console.log('Partial fee:', info.partialFee.toHuman()); await api.disconnect(); ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction --- ## rpc_methods - Centrifuge RPC Method # rpc_methods Returns a list of all RPC methods available on Centrifuge. ## Use Cases - **API discovery** - List all available methods - **Compatibility checking** - Verify method availability for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Documentation** - Auto-generate method lists ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const methods = await api.rpc.rpc.methods(); console.log('Available methods:', methods.methods.length); await api.disconnect(); ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## state_call - Centrifuge RPC Method # state_call Calls a runtime API method on Centrifuge. ## Use Cases - **Runtime computations** - Execute runtime logic without transactions - **Account queries** - Use AccountNonceApi for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Fee estimation** - Use TransactionPaymentApi ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `method` | `String` | Yes | Runtime API method name | | `data` | `String` | Yes | SCALE-encoded call data | | `blockHash` | `String` | No | Block hash for historical call | ## Request ```json { "jsonrpc": "2.0", "method": "state_call", "params": ["AccountNonceApi_account_nonce", "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"], "id": 1 } ``` ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_call", "params": ["AccountNonceApi_account_nonce", "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get account nonce via runtime API const account = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const result = await api.call.accountNonceApi.accountNonce(account); console.log('Account nonce:', result.toNumber()); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Query storage - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## state_getKeys - JSON-RPC Method(Centrifuge) ## Description Returns storage keys that match a given prefix. This JSON-RPC method is useful for discovering all storage entries under a specific module or querying multiple related storage items. Be cautious with broad prefixes as they may return large result sets. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `prefix` | string | Yes | Hex-encoded storage key prefix to match | | `blockHash` | string | No | Block hash to query at. If omitted, uses the latest block | ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | array | Array of hex-encoded storage keys matching the prefix | ## Request Example ```json { "jsonrpc": "2.0", "method": "state_getKeys", "params": [ "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9" ], "id": 1 } ``` ## Response Example ```json { "jsonrpc": "2.0", "result": [ "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9de1e86a9a8c739864cf3cc5ec2bea59fd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d", "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da94f9aea1afa791265fae359272badc1cf8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48" ], "id": 1 } ``` ## Code Examples ```python from substrateinterface import SubstrateInterface def get_storage_keys(prefix, block_hash=None): url = "https://api-centrifuge.n.dwellir.com" headers = { "Content-Type": "application/json" } params = [prefix, block_hash] if block_hash else [prefix] payload = { "jsonrpc": "2.0", "method": "state_getKeys", "params": params, "id": 1 } response = requests.post(url, headers=headers, data=json.dumps(payload)) return response.json()["result"] # Example: Get all validator preferences keys def get_validator_keys(): # Staking.Validators storage prefix prefix = "0x5f3e4907f716ac89b6347d15ececedca9320c2dc4f5d7af5b320b04e2d1a3ff3" keys = get_storage_keys(prefix) print(f"Found {len(keys)} validator preference entries") for key in keys: # Extract validator account from key validator_account = key[-64:] print(f"Validator: 0x{validator_account}") return keys # Example: Query all keys under a module def get_module_keys(module_prefix): keys = get_storage_keys(module_prefix) # Group keys by storage item storage_items = {} for key in keys: # Storage keys typically have a fixed prefix per item item_prefix = key[:66] # First 33 bytes (66 hex chars) if item_prefix not in storage_items: storage_items[item_prefix] = [] storage_items[item_prefix].append(key) return storage_items ``` ```javascript const getStorageKeys = async (prefix, blockHash = null) => { const params = blockHash ? [prefix, blockHash] : [prefix]; const response = await fetch('https://api-centrifuge.n.dwellir.com', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'state_getKeys', params: params, id: 1 }) }); const data = await response.json(); return data.result; }; // Get all account keys (System.Account storage) const accountPrefix = '0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9'; const accountKeys = await getStorageKeys(accountPrefix); console.log(`Found ${accountKeys.length} accounts`); // Extract account addresses from keys accountKeys.forEach(key => { // The account address is the last 32 bytes of the key const addressHex = key.slice(-64); console.log('Account key:', key); console.log('Address portion:', addressHex); }); ``` ```typescript async function queryStorageKeys() { const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com'); const api = await ApiPromise.create({ provider }); // Method 1: Using high-level API to get keys const accountKeys = await api.query.system.account.keys(); console.log('Account addresses:', accountKeys.map(k => k.toHuman())); // Method 2: Using low-level RPC for custom prefixes const prefix = api.query.system.account.keyPrefix(); const keys = await api.rpc.state.getKeys(prefix); console.log(`Found ${keys.length} account storage keys`); // Method 3: Get keys for a specific map entry const validatorKeys = await api.query.staking.validators.keys(); console.log('Active validators:', validatorKeys.length); // Process keys to extract data for (const key of keys) { // Decode the storage key const keyHex = key.toHex(); console.log('Storage key:', keyHex); // Get the value for this key const value = await api.rpc.state.getStorage(key); console.log('Storage value:', value.toHex()); } await api.disconnect(); } // Advanced: Query keys with pagination async function getKeysPagedExample() { const api = await ApiPromise.create({ provider: new WsProvider('wss://api-centrifuge.n.dwellir.com') }); const prefix = api.query.system.account.keyPrefix(); const pageSize = 100; let startKey = prefix; let allKeys = []; while (true) { // Note: state_getKeysPaged is used for pagination const keys = await api.rpc.state.getKeysPaged(prefix, pageSize, startKey); if (keys.length === 0) break; allKeys = allKeys.concat(keys); startKey = keys[keys.length - 1]; console.log(`Fetched ${keys.length} keys, total: ${allKeys.length}`); if (keys.length < pageSize) break; } console.log(`Total keys found: ${allKeys.length}`); await api.disconnect(); } ``` ## Common Storage Prefixes | Module | Storage Item | Prefix (example) | |--------|--------------|------------------| | System | Account | `0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9` | | Balances | TotalIssuance | `0xc2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80` | | Staking | Validators | `0x5f3e4907f716ac89b6347d15ececedca9320c2dc4f5d7af5b320b04e2d1a3ff3` | | Session | NextKeys | `0xcec5070d609dd3497f72bde07fc96ba0e0cdd062e6eaf24295ad4ccfc41d4609` | ## Batch Query Example ```javascript // Efficiently query multiple storage values async function batchQueryStorage(api, keys) { // Get all values in a single call const values = await api.rpc.state.queryStorageAt(keys); const results = {}; keys.forEach((key, index) => { results[key.toString()] = values[index]; }); return results; } // Example usage const keys = await getStorageKeys(accountPrefix); const values = await batchQueryStorage(api, keys.slice(0, 10)); console.log('Batch query results:', values); ``` ## Use Cases 1. **Account Discovery**: Find all accounts with balances 2. **Validator Enumeration**: List all validators in the network 3. **Storage Analysis**: Analyze storage usage by module 4. **Migration Scripts**: Iterate over storage for upgrades 5. **Indexing**: Build indexes of on-chain data ## Notes - Large prefixes may return many keys - use pagination when available - Keys are returned in lexicographical order - The prefix must be hex-encoded - Consider using `state_getKeysPaged` for large datasets - Storage keys include both the storage prefix and the key data ## Related Methods - [`state_getKeysPaged`](./state_getKeysPaged) - Get keys with pagination - [`state_getStorage`](./state_getStorage) - Get storage value - [`state_getMetadata`](./state_getMetadata) - Get metadata to decode keys --- ## state_getKeysPaged - Centrifuge RPC Method # state_getKeysPaged Returns storage keys with pagination on Centrifuge. ## Use Cases - **Storage iteration** - Enumerate storage map entries - **Data export** - Bulk export chain data for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Account enumeration** - List all accounts ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `prefix` | `String` | Yes | Storage key prefix | | `count` | `Number` | Yes | Maximum keys to return | | `startKey` | `String` | No | Key to start after | | `blockHash` | `String` | No | Block hash for historical query | ## Request ```json { "jsonrpc": "2.0", "method": "state_getKeysPaged", "params": ["0x...", 100], "id": 1 } ``` ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getKeysPaged", "params": ["0x26aa394eea5630e07c48ae0c9558cef7", 100], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get all accounts (paginated) const keys = await api.rpc.state.getKeysPaged( api.query.system.account.keyPrefix(), 100 ); console.log('Found accounts:', keys.length); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Get storage value - [`state_queryStorageAt`](./state_queryStorageAt) - Batch storage query --- ## state_getMetadata - Centrifuge RPC Method # state_getMetadata Returns the runtime metadata on Centrifuge. ## Use Cases - **Runtime introspection** - Discover available pallets and calls - **Extrinsic building** - Get call and type information for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Storage key generation** - Build storage keys from metadata - **Client generation** - Auto-generate typed APIs ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash for historical metadata | ## Request ```json { "jsonrpc": "2.0", "method": "state_getMetadata", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getMetadata", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get runtime metadata const metadata = await api.rpc.state.getMetadata(); // List available pallets const pallets = metadata.asLatest.pallets.map(p => p.name.toString()); console.log('Available pallets:', pallets); // Get specific pallet info const systemPallet = metadata.asLatest.pallets.find(p => p.name.toString() === 'System'); console.log('System pallet calls:', systemPallet.calls.isSome ? 'Available' : 'None'); await api.disconnect(); ``` ```python def get_metadata(): url = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'state_getMetadata', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] metadata_hex = get_metadata() print(f'Metadata length: {len(metadata_hex)} bytes') ``` ## Related Methods - [`state_getRuntimeVersion`](./state_getRuntimeVersion) - Get runtime version - [`state_getStorage`](./state_getStorage) - Query storage --- ## state_getRuntimeVersion - Centrifuge RPC Method # state_getRuntimeVersion Returns the runtime version on Centrifuge. ## Use Cases - **Version checking** - Verify runtime compatibility - **Upgrade detection** - Monitor for runtime upgrades on tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Client compatibility** - Ensure API compatibility ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash for historical version | ## Request ```json { "jsonrpc": "2.0", "method": "state_getRuntimeVersion", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getRuntimeVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const version = await api.rpc.state.getRuntimeVersion(); console.log('Spec name:', version.specName.toString()); console.log('Spec version:', version.specVersion.toNumber()); console.log('Impl version:', version.implVersion.toNumber()); await api.disconnect(); ``` ```python def get_runtime_version(): url = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'state_getRuntimeVersion', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] version = get_runtime_version() print(f"Spec: {version['specName']} v{version['specVersion']}") ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata - [`system_version`](./system_version) - Get node version --- ## state_getStorage - Centrifuge RPC Method # state_getStorage Returns a storage entry at a specific key on Centrifuge. > **Why Centrifuge?** Build on the RWA tokenization platform bridging traditional finance with $1B+ Janus Henderson backing with ERC-7540 RWA standards, multichain via Wormhole, 97% securitization cost savings, and BlockTower $220M fund integration. ## Use Cases - **State queries** - Read on-chain storage values - **Account balances** - Query account data for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Pallet storage** - Access runtime storage items - **Historical state** - Query state at specific blocks ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `key` | `String` | Yes | Storage key (hex-encoded) | | `blockHash` | `String` | No | Block hash for historical query | ## Request ```json { "jsonrpc": "2.0", "method": "state_getStorage", "params": [""], "id": 1 } ``` ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getStorage", "params": [""], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query account balance const account = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const accountInfo = await api.query.system.account(account); console.log('Free balance:', accountInfo.data.free.toString()); // Query at specific block const blockHash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'; const historicalBalance = await api.query.system.account.at(blockHash, account); console.log('Historical balance:', historicalBalance.data.free.toString()); await api.disconnect(); ``` ```python def get_storage(key, block_hash=None): url = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY' params = [key] if block_hash is None else [key, block_hash] payload = { 'jsonrpc': '2.0', 'method': 'state_getStorage', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] # Query :code storage (runtime wasm) storage_key = '' value = get_storage(storage_key) print(f'Storage value: {value[:66]}...' if value else 'None') ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata - [`state_getKeysPaged`](./state_getKeysPaged) - Enumerate storage keys --- ## state_queryStorageAt - Centrifuge RPC Method # state_queryStorageAt Query multiple storage keys at a specific block on Centrifuge. ## Use Cases - **Batch queries** - Efficiently query multiple storage items - **Snapshot state** - Get consistent multi-key state for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Data analysis** - Compare storage across blocks ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `keys` | `Array` | Yes | Array of storage keys | | `blockHash` | `String` | No | Block hash for query | ## Request ```json { "jsonrpc": "2.0", "method": "state_queryStorageAt", "params": [[""]], "id": 1 } ``` ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_queryStorageAt", "params": [[""]], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query multiple accounts at once const accounts = ['5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY']; const entries = await api.query.system.account.multi(accounts); entries.forEach((info, idx) => { console.log(`Account ${idx}: ${info.data.free.toString()}`); }); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Single storage query - [`state_getKeysPaged`](./state_getKeysPaged) - Enumerate keys --- ## system_chain - Centrifuge RPC Method # system_chain Returns the chain name on Centrifuge. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const chain = await api.rpc.system.chain(); console.log('Chain:', chain.toString()); await api.disconnect(); ``` ## Related Methods - [`system_name`](./system_name) - Get node implementation name - [`system_version`](./system_version) - Get node version --- ## system_health - Centrifuge RPC Method # system_health Returns the health status of the Centrifuge node. ## Use Cases - **Health checks** - Monitor node availability - **Load balancing** - Route traffic based on health for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **Sync status** - Verify node is synced ## Parameters This method accepts no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `peers` | `Number` | Connected peer count | | `isSyncing` | `Boolean` | Whether node is syncing | | `shouldHavePeers` | `Boolean` | Whether node should have peers | ## Request ```json { "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const health = await api.rpc.system.health(); console.log('Peers:', health.peers.toNumber()); console.log('Is syncing:', health.isSyncing.isTrue); await api.disconnect(); ``` ```python def get_health(): url = 'https://api-centrifuge.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'system_health', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] health = get_health() print(f"Peers: {health['peers']}") print(f"Syncing: {health['isSyncing']}") ``` ## Related Methods - [`system_version`](./system_version) - Get node version - [`system_chain`](./system_chain) - Get chain name --- ## system_name - Centrifuge RPC Method # system_name Returns the node implementation name on Centrifuge. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_name", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_name", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const name = await api.rpc.system.name(); console.log('Node name:', name.toString()); await api.disconnect(); ``` ## Related Methods - [`system_version`](./system_version) - Get node version - [`system_chain`](./system_chain) - Get chain name --- ## system_properties - Centrifuge RPC Method # system_properties Returns chain properties including token symbol and decimals on Centrifuge. ## Use Cases - **Token formatting** - Get decimals and symbol for tokenized treasury funds, SME invoice financing, and institutional-grade RWA infrastructure - **UI configuration** - Configure wallets and dApps - **Address formatting** - Get SS58 prefix ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_properties", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_properties", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const props = await api.rpc.system.properties(); console.log('Token symbol:', props.tokenSymbol.toString()); console.log('Token decimals:', props.tokenDecimals.toString()); console.log('SS58 prefix:', props.ss58Format.toString()); await api.disconnect(); ``` ## Related Methods - [`system_chain`](./system_chain) - Get chain name - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## system_version - Centrifuge RPC Method # system_version Returns the node implementation version on Centrifuge. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_version", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_version", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-centrifuge.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const version = await api.rpc.system.version(); console.log('Version:', version.toString()); await api.disconnect(); ``` ## Related Methods - [`system_chain`](./system_chain) - Get chain name - [`state_getRuntimeVersion`](./state_getRuntimeVersion) - Get runtime version --- ## web3_clientVersion - Get client version # web3_clientVersion Get client version on the Centrifuge network. ## Parameters Varies by method. Please refer to the official [Centrifuge JSON-RPC: web3_clientVersion](https://ethereum.org/developers/docs/apis/json-rpc/#web3_clientversion) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'web3_clientVersion', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## web3_sha3 - Calculate Keccak-256 Hash on... # web3_sha3 Calculate Keccak-256 hash on the Centrifuge network. ## Parameters Varies by method. Please refer to the official [Centrifuge JSON-RPC: web3_sha3](https://ethereum.org/developers/docs/apis/json-rpc/#web3_sha3) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-centrifuge.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f20776f726c64"], "id": 1 }' ``` ```javascript const response = await fetch('https://api-centrifuge.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'web3_sha3', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Centrifuge documentation](/docs/centrifuge).* --- ## debug_traceBlock - Chiliz RPC Method # debug_traceBlock Traces all transactions in a block on Chiliz by block RLP. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Analyze transaction execution step-by-step - **Smart contract analysis** - Debug contract interactions - **Security auditing** - Trace internal calls for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockRlp` | `DATA` | Yes | RLP-encoded block data | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Use debug_traceBlockByNumber instead (more practical) const traces = await provider.send('debug_traceBlockByNumber', ['latest', {}]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by block number - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by block hash --- ## debug_traceBlockByHash - Chiliz RPC Method # debug_traceBlockByHash Traces all transactions in a block on Chiliz by block hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0xa9922ade53a153685d0ee94acdaf34dacc756b4a0170812abd7338daca98c178", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0xa9922ade53a153685d0ee94acdaf34dacc756b4a0170812abd7338daca98c178", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0xa9922ade53a153685d0ee94acdaf34dacc756b4a0170812abd7338daca98c178'; const traces = await provider.send('debug_traceBlockByHash', [blockHash, { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by number - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceBlockByNumber - Chiliz RPC Method # debug_traceBlockByNumber Traces all transactions in a block on Chiliz by block number. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('debug_traceBlockByNumber', ['latest', { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by hash - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceCall - Chiliz RPC Method # debug_traceCall Traces a call without creating a transaction on Chiliz. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction simulation** - Debug before sending - **Gas analysis** - Analyze gas usage per opcode - **Contract debugging** - Step through execution for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `call` | `Object` | Yes | Call object (same as eth_call) | | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ { "to": "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "data": "0x70a08231000000000000000000000000721EF6871f1c4Efe730dCE047d40D1743B886946" }, "latest", {} ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ {"to": "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "data": "0x70a08231000000000000000000000000721EF6871f1c4Efe730dCE047d40D1743B886946"}, "latest", {"tracer": "callTracer"} ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const trace = await provider.send('debug_traceCall', [ { to: '0x721EF6871f1c4Efe730dCE047d40D1743B886946', data: '0x70a08231000000000000000000000000721EF6871f1c4Efe730dCE047d40D1743B886946' }, 'latest', { tracer: 'callTracer' } ]); console.log('Trace:', trace); ``` ## Related Methods - [`eth_call`](./eth_call) - Execute call without trace - [`debug_traceTransaction`](./debug_traceTransaction) - Trace actual transaction --- ## debug_traceTransaction - Chiliz RPC Method # debug_traceTransaction Traces a transaction execution on Chiliz by transaction hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Understand exactly what happened - **Failure analysis** - Find where and why a transaction reverted - **Gas optimization** - Analyze gas usage for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Tracer Options - `{}` - Default opcode tracer (verbose) - `{ tracer: "callTracer" }` - Call tree tracer - `{ tracer: "prestateTracer" }` - Pre-state tracer ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x01038cb6fa5140b5068293ecaf6e2029eae653b9489388ff252e1c18b4606f39", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x01038cb6fa5140b5068293ecaf6e2029eae653b9489388ff252e1c18b4606f39", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x01038cb6fa5140b5068293ecaf6e2029eae653b9489388ff252e1c18b4606f39'; // Call tracer - shows internal calls const callTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'callTracer' } ]); console.log('Type:', callTrace.type); console.log('From:', callTrace.from); console.log('To:', callTrace.to); console.log('Gas used:', parseInt(callTrace.gasUsed, 16)); // Prestate tracer - shows state before execution const prestateTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'prestateTracer' } ]); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x01038cb6fa5140b5068293ecaf6e2029eae653b9489388ff252e1c18b4606f39' # Call tracer trace = w3.provider.make_request('debug_traceTransaction', [ tx_hash, {'tracer': 'callTracer'} ]) print(f'Trace type: {trace["result"]["type"]}') print(f'Gas used: {int(trace["result"]["gasUsed"], 16)}') ``` ## Related Methods - [`debug_traceCall`](./debug_traceCall) - Trace without executing - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace entire block --- ## eth_accounts - Chiliz RPC Method # eth_accounts Returns a list of addresses owned by the client on Chiliz. > **Why Chiliz?** Build on the sports-first blockchain powering 2M+ fan token wallets and dozens of licensed sports partnerships with licensed partnerships with major football clubs, MiCA-compliant in EU, OG Esports integration, and SportFi DeFi infrastructure. ## Important Note On public RPC endpoints like Dwellir, `eth_accounts` returns an empty array because the node does not hold any private keys. This method is primarily useful for: - Local development nodes (Ganache, Hardhat, Anvil) - Private nodes with managed accounts - Wallet provider connections (MetaMask injects accounts) ## When to Use This Method `eth_accounts` is relevant for sports organizations, entertainment brands, and fan engagement platform developers in specific scenarios: - **Development Testing** — Retrieve test accounts from local nodes - **Wallet Detection** — Check if a wallet provider has connected accounts - **Client Verification** — Confirm node account access capabilities ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `Array` | List of 20-byte account addresses owned by the client | **Return format**: Array of `0x` prefixed hexadecimal addresses (typically empty for public nodes) ## Request ```json { "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 } ``` ## Response ### Successful Response (Public Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [] } ``` ### Successful Response (Local Development Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [ "0x407d73d8a49eeb85d32cf465507dd71d507100c1", "0x85d32cf465507dd71d507100c1407d73d8a49eeb" ] } ``` ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_accounts', params: [], id: 1 }) }); const { result } = await response.json(); console.log('Accounts:', result); // Using ethers.js const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const accounts = await provider.listAccounts(); console.log('Accounts:', accounts); ``` ```python def get_accounts(): response = requests.post( 'https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_accounts', 'params': [], 'id': 1 } ) return response.json()['result'] accounts = get_accounts() print(f'Accounts: {accounts}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) print(f'Accounts: {w3.eth.accounts}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/rpc" ) func main() { client, err := rpc.Dial("https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } var accounts []string err = client.CallContext(context.Background(), &accounts, "eth_accounts") if err != nil { log.Fatal(err) } fmt.Printf("Accounts: %v\n", accounts) } ``` ## Common Use Cases ### 1. Development Environment Detection Check if running against a development node with test accounts: ```javascript async function isDevEnvironment(provider) { const accounts = await provider.listAccounts(); return accounts.length > 0; } const isDev = await isDevEnvironment(provider); if (isDev) { console.log('Development environment detected'); } ``` ### 2. Wallet Connection Check Verify wallet provider has connected accounts: ```javascript async function checkWalletConnection() { if (typeof window.ethereum === 'undefined') { return { connected: false, reason: 'No wallet detected' }; } const accounts = await window.ethereum.request({ method: 'eth_accounts' }); return { connected: accounts.length > 0, accounts: accounts }; } ``` ### 3. Fallback Account Selection Use first available account or request connection: ```javascript async function getActiveAccount() { // Check existing connections let accounts = await window.ethereum.request({ method: 'eth_accounts' }); // Request connection if no accounts if (accounts.length === 0) { accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); } return accounts[0] || null; } ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32601 | Method not found | Node may not support this method | | -32603 | Internal error | Retry with exponential backoff | ```javascript async function safeGetAccounts(provider) { try { const accounts = await provider.listAccounts(); return { success: true, accounts }; } catch (error) { if (error.code === -32601) { console.warn('eth_accounts not supported on this node'); return { success: false, accounts: [], reason: 'unsupported' }; } throw error; } } ``` ## Related Methods - [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102) — Request wallet connection (browser wallets) - [`eth_getBalance`](./eth_getBalance) — Get account balance - [`eth_getTransactionCount`](./eth_getTransactionCount) — Get account nonce --- ## eth_blockNumber - Chiliz RPC Method # eth_blockNumber Returns the number of the most recent block on Chiliz. > **Why Chiliz?** Build on the sports-first blockchain powering 2M+ fan token wallets and dozens of licensed sports partnerships with licensed partnerships with major football clubs, MiCA-compliant in EU, OG Esports integration, and SportFi DeFi infrastructure. ## When to Use This Method `eth_blockNumber` is fundamental for sports organizations, entertainment brands, and fan engagement platform developers: - **Syncing Applications** — Keep your dApp in sync with the latest Chiliz blockchain state - **Transaction Monitoring** — Verify confirmations by comparing block numbers - **Event Filtering** — Set the correct block range for querying logs on sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets - **Health Checks** — Monitor node connectivity and sync status ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `QUANTITY` | Hexadecimal string representing the current block number | **Return format**: `0x` prefixed hexadecimal (e.g., `0x5BAD55` = 6,008,149 in decimal) ## Request ```json { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } ``` ## Response ### Successful Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5BAD55" } ``` ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error" } } ``` ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }) }); const { result } = await response.json(); const blockNumber = parseInt(result, 16); console.log('Chiliz block:', blockNumber); // Using ethers.js const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockNumber = await provider.getBlockNumber(); console.log('Chiliz block:', blockNumber); ``` ```python def get_block_number(): response = requests.post( 'https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_blockNumber', 'params': [], 'id': 1 } ) result = response.json()['result'] return int(result, 16) block_number = get_block_number() print(f'Chiliz block: {block_number}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) print(f'Chiliz block: {w3.eth.block_number}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockNumber, err := client.BlockNumber(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Chiliz block: %d\n", blockNumber) } ``` ## Common Use Cases ### 1. Block Confirmation Counter Monitor transaction confirmations on Chiliz: ```javascript async function getConfirmations(provider, txHash) { const tx = await provider.getTransaction(txHash); if (!tx || !tx.blockNumber) return 0; const currentBlock = await provider.getBlockNumber(); return currentBlock - tx.blockNumber + 1; } // Wait for specific confirmations async function waitForConfirmations(provider, txHash, confirmations = 6) { let currentConfirmations = 0; while (currentConfirmations < confirmations) { currentConfirmations = await getConfirmations(provider, txHash); console.log(`Confirmations: ${currentConfirmations}/${confirmations}`); await new Promise(r => setTimeout(r, 2000)); } return true; } ``` ### 2. Event Log Filtering Query events from recent blocks on Chiliz: ```javascript async function getRecentEvents(provider, contract, eventName, blockRange = 100) { const currentBlock = await provider.getBlockNumber(); const fromBlock = currentBlock - blockRange; const filter = contract.filters[eventName](); const events = await contract.queryFilter(filter, fromBlock, currentBlock); return events; } ``` ### 3. Node Health Monitoring Check if your Chiliz node is synced: ```javascript async function checkNodeHealth(provider) { try { const blockNumber = await provider.getBlockNumber(); const block = await provider.getBlock(blockNumber); const now = Date.now() / 1000; const blockAge = now - block.timestamp; if (blockAge > 60) { console.warn(`Node may be behind. Last block was ${blockAge}s ago`); return false; } console.log(`Node healthy. Latest block: ${blockNumber}`); return true; } catch (error) { console.error('Node unreachable:', error); return false; } } ``` ## Performance Optimization ### Caching Strategy Cache block numbers to reduce API calls: ```javascript class BlockNumberCache { constructor(ttl = 2000) { this.cache = null; this.timestamp = 0; this.ttl = ttl; } async get(provider) { const now = Date.now(); if (this.cache && (now - this.timestamp) < this.ttl) { return this.cache; } this.cache = await provider.getBlockNumber(); this.timestamp = now; return this.cache; } invalidate() { this.cache = null; this.timestamp = 0; } } const blockCache = new BlockNumberCache(); ``` ### Batch Requests Combine with other calls for efficiency: ```javascript const batch = [ { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }, { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 }, { jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 } ]; const response = await fetch('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await response.json(); ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32603 | Internal error | Retry with exponential backoff | | -32005 | Rate limit exceeded | Implement rate limiting client-side | | -32000 | Execution reverted | Check node sync status | ```javascript async function safeGetBlockNumber(provider, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await provider.getBlockNumber(); } catch (error) { if (error.code === -32005) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } else if (i === maxRetries - 1) { throw error; } } } } ``` ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) — Get full block details by number - [`eth_getBlockByHash`](./eth_getBlockByHash) — Get block details by hash - [`eth_syncing`](./eth_syncing) — Check if node is still syncing --- ## eth_call - Chiliz RPC Method # eth_call Executes a new message call immediately without creating a transaction on Chiliz. Used for reading smart contract state. > **Why Chiliz?** Build on the sports-first blockchain powering 2M+ fan token wallets and dozens of licensed sports partnerships with licensed partnerships with major football clubs, MiCA-compliant in EU, OG Esports integration, and SportFi DeFi infrastructure. ## Use Cases The `eth_call` method is essential for: - **Reading contract state** - Query view/pure functions - **Simulating transactions** - Test execution without gas costs - **DeFi integrations** - Check prices, balances, allowances for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets - **Complex queries** - Execute multi-step contract logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | 20-byte address executing the call | | `to` | `DATA` | Yes | 20-byte contract address | | `gas` | `QUANTITY` | No | Gas limit for the call | | `gasPrice` | `QUANTITY` | No | Gas price in wei | | `value` | `QUANTITY` | No | Value to send in wei | | `data` | `DATA` | Yes | Encoded function call data | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_call", "params": [ { "to": "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "data": "0x70a08231000000000000000000000000721EF6871f1c4Efe730dCE047d40D1743B886946" }, "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | The return value of the executed contract function | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000" } ``` ## Code Examples ```bash # Call ERC20 balanceOf function curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{ "to": "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "data": "0x70a08231000000000000000000000000721EF6871f1c4Efe730dCE047d40D1743B886946" }, "latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // ERC20 ABI for common functions const ERC20_ABI = [ "function balanceOf(address owner) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function totalSupply() view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)" ]; // Read ERC20 token balance async function getTokenBalance(tokenAddress, walletAddress) { const contract = new Contract(tokenAddress, ERC20_ABI, provider); const balance = await contract.balanceOf(walletAddress); const decimals = await contract.decimals(); const symbol = await contract.symbol(); return { raw: balance.toString(), formatted: (Number(balance) / Math.pow(10, decimals)).toFixed(4), symbol: symbol }; } // Direct eth_call async function directCall(to, data) { const result = await provider.call({ to, data }); return result; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) def get_erc20_balance(token_address, wallet_address): # balanceOf(address) selector function_signature = "balanceOf(address)" function_selector = w3.keccak(text=function_signature)[:4].hex() # Encode address parameter encoded_address = wallet_address[2:].lower().zfill(64) data = function_selector + encoded_address # Make the call result = w3.eth.call({ 'to': token_address, 'data': data }) return int(result.hex(), 16) balance = get_erc20_balance( '0x721EF6871f1c4Efe730dCE047d40D1743B886946', '0x721EF6871f1c4Efe730dCE047d40D1743B886946' ) print(f'Balance: {balance}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0x721EF6871f1c4Efe730dCE047d40D1743B886946") data := common.FromHex("0x70a08231000000000000000000000000721EF6871f1c4Efe730dCE047d40D1743B886946") msg := ethereum.CallMsg{ To: &contractAddress, Data: data, } result, err := client.CallContract(context.Background(), msg, nil) if err != nil { log.Fatal(err) } fmt.Printf("Result: 0x%x\n", result) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Contract function reverted | | -32602 | Invalid parameters | Invalid data encoding | | -32015 | VM execution error | Contract logic error | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas for transaction - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send actual transaction --- ## eth_chainId - Chiliz RPC Method # eth_chainId Returns the chain ID used for transaction signing on Chiliz. > **Why Chiliz?** Build on the sports-first blockchain powering 2M+ fan token wallets and dozens of licensed sports partnerships with licensed partnerships with major football clubs, MiCA-compliant in EU, OG Esports integration, and SportFi DeFi infrastructure. ## Use Cases The `eth_chainId` method is essential for: - **Transaction signing** - Ensure transactions are signed for the correct network - **Network verification** - Confirm connection to the expected chain - **Multi-chain apps** - Handle different networks programmatically - **Wallet integration** - Validate network before transactions ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Chain ID in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1" } ``` ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const network = await provider.getNetwork(); console.log('Chain ID:', network.chainId); // Verify network before transaction async function verifyNetwork(expectedChainId) { const network = await provider.getNetwork(); if (network.chainId !== BigInt(expectedChainId)) { throw new Error(`Wrong network. Expected ${expectedChainId}, got ${network.chainId}`); } return true; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) chain_id = w3.eth.chain_id print(f'Chain ID: {chain_id}') # Verify network def verify_network(expected_chain_id): chain_id = w3.eth.chain_id if chain_id != expected_chain_id: raise ValueError(f'Wrong network. Expected {expected_chain_id}, got {chain_id}') return True ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } chainID, err := client.ChainID(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Chain ID: %d\n", chainID) } ``` ## Related Methods - [`net_version`](./net_version) - Get network version - [`eth_syncing`](./eth_syncing) - Check sync status --- ## eth_coinbase - Get Coinbase Address(Chiliz) # eth_coinbase Returns the client coinbase address. ## Parameters None. ## Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_coinbase", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider( 'https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); const coinbase = await provider.send('eth_coinbase', []); console.log('Coinbase address:', coinbase); ``` ```typescript const chiliz = defineChain({ id: 88888, name: 'Chiliz', nativeCurrency: { decimals: 18, name: 'CHZ', symbol: 'CHZ', }, rpcUrls: { default: { http: ['https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'], }, }, blockExplorers: { default: { name: 'ChilizScan', url: 'https://chiliscan.com' }, }, }); const client = createPublicClient({ chain: chiliz, transport: http('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'), }); const coinbase = await client.request({ method: 'eth_coinbase' }); console.log('Coinbase address:', coinbase); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider( 'https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY' )) coinbase = w3.eth.coinbase print('Coinbase address:', coinbase) ``` ## Response Returns the coinbase address as a hex string. Common error responses: - `{"code": -32700, "message": "Parse error"}` - Invalid JSON - `{"code": -32602, "message": "Invalid params"}` - Invalid parameters - `{"code": -32603, "message": "Internal error"}` - Server error --- ## eth_estimateGas - Chiliz RPC Method # eth_estimateGas Estimates the gas necessary to execute a transaction on Chiliz. > **Why Chiliz?** Build on the sports-first blockchain powering 2M+ fan token wallets and dozens of licensed sports partnerships with licensed partnerships with major football clubs, MiCA-compliant in EU, OG Esports integration, and SportFi DeFi infrastructure. ## Use Cases The `eth_estimateGas` method is essential for: - **Transaction preparation** - Set appropriate gas limits - **Cost estimation** - Calculate transaction costs before sending - **Error detection** - Identify reverts before spending gas - **DeFi operations** - Estimate costs for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | Sender address | | `to` | `DATA` | No | Recipient address | | `gas` | `QUANTITY` | No | Gas limit | | `gasPrice` | `QUANTITY` | No | Gas price | | `value` | `QUANTITY` | No | Value in wei | | `data` | `DATA` | No | Transaction data | ## Request ```json { "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "to": "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "value": "0x1" }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Estimated gas amount in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5208" } ``` **Note**: `0x5208` = 21000 gas (standard ETH transfer) ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "to": "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "value": "0x1" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Estimate simple transfer async function estimateTransfer(to, value) { const gasEstimate = await provider.estimateGas({ to: to, value: parseEther(value) }); console.log('Estimated gas:', gasEstimate.toString()); return gasEstimate; } // Estimate contract call async function estimateContractCall(contract, method, args) { const gasEstimate = await contract[method].estimateGas(...args); console.log('Estimated gas:', gasEstimate.toString()); // Add 20% buffer for safety return gasEstimate * 120n / 100n; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) def estimate_transfer(to, value_in_ether): gas_estimate = w3.eth.estimate_gas({ 'to': to, 'value': w3.to_wei(value_in_ether, 'ether') }) print(f'Estimated gas: {gas_estimate}') return gas_estimate def estimate_contract_call(contract, method, args): func = getattr(contract.functions, method) gas_estimate = func(*args).estimate_gas() # Add 20% buffer return int(gas_estimate * 1.2) # Estimate simple transfer gas = estimate_transfer('0x721EF6871f1c4Efe730dCE047d40D1743B886946', 0.1) ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } toAddress := common.HexToAddress("0x721EF6871f1c4Efe730dCE047d40D1743B886946") msg := ethereum.CallMsg{ To: &toAddress, Value: big.NewInt(1000000000000000000), } gasLimit, err := client.EstimateGas(context.Background(), msg) if err != nil { log.Fatal(err) } fmt.Printf("Estimated gas: %d\n", gasLimit) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Transaction would fail | | -32602 | Invalid params | Invalid transaction parameters | **Tip**: If estimation fails, the transaction would likely revert if sent. ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_feeHistory - Chiliz RPC Method # eth_feeHistory Returns historical gas information on Chiliz for fee estimation. ## Use Cases - **Fee prediction** - Estimate future gas prices based on history - **Gas analytics** - Analyze fee trends over time - **Optimal timing** - Find best times for transactions on sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockCount` | `QUANTITY` | Yes | Number of blocks in the range | | `newestBlock` | `QUANTITY\|TAG` | Yes | Highest block of the range | | `rewardPercentiles` | `Array` | Yes | Percentiles to sample for priority fees | ## Request ```json { "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const feeHistory = await provider.send('eth_feeHistory', ['0xa', 'latest', [25, 50, 75]]); console.log('Base fees:', feeHistory.baseFeePerGas.map(f => formatUnits(f, 'gwei'))); console.log('Reward (25th percentile):', feeHistory.reward.map(r => formatUnits(r[0], 'gwei'))); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) fee_history = w3.eth.fee_history(10, 'latest', [25, 50, 75]) print(f'Base fees: {[w3.from_wei(f, "gwei") for f in fee_history["baseFeePerGas"]]}') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee --- ## eth_gasPrice - Chiliz RPC Method # eth_gasPrice Returns the current gas price on Chiliz in wei. > **Why Chiliz?** Build on the sports-first blockchain powering 2M+ fan token wallets and dozens of licensed sports partnerships with licensed partnerships with major football clubs, MiCA-compliant in EU, OG Esports integration, and SportFi DeFi infrastructure. ## Use Cases The `eth_gasPrice` method is essential for: - **Transaction pricing** - Set appropriate gas prices - **Cost estimation** - Calculate transaction costs before sending - **Gas monitoring** - Track network congestion - **DeFi operations** - Optimize costs for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Current gas price in wei (hexadecimal) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x3b9aca00" } ``` **Note**: `0x3b9aca00` = 1 Gwei (1,000,000,000 wei) ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); const gasPrice = feeData.gasPrice; console.log('Gas Price:', formatUnits(gasPrice, 'gwei'), 'Gwei'); // Calculate transaction cost async function estimateTransactionCost(gasLimit) { const feeData = await provider.getFeeData(); const cost = feeData.gasPrice * BigInt(gasLimit); return formatUnits(cost, 'ether'); } const cost = await estimateTransactionCost(21000); console.log('Transfer cost:', cost, 'ETH'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) gas_price = w3.eth.gas_price print(f'Gas Price: {w3.from_wei(gas_price, "gwei")} Gwei') # Calculate transaction cost def estimate_transaction_cost(gas_limit): gas_price = w3.eth.gas_price cost = gas_price * gas_limit return w3.from_wei(cost, 'ether') cost = estimate_transaction_cost(21000) print(f'Transfer cost: {cost} ETH') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } gasPrice, err := client.SuggestGasPrice(context.Background()) if err != nil { log.Fatal(err) } // Convert to Gwei gwei := new(big.Float).Quo( new(big.Float).SetInt(gasPrice), big.NewFloat(1e9), ) fmt.Printf("Gas Price: %f Gwei\n", gwei) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32603 | Internal error | Node error | ## Related Methods - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee (EIP-1559) - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas needed --- ## eth_getBalance - Chiliz RPC Method # eth_getBalance Returns the balance of a given address on Chiliz. > **Why Chiliz?** Build on the sports-first blockchain powering 2M+ fan token wallets and dozens of licensed sports partnerships with licensed partnerships with major football clubs, MiCA-compliant in EU, OG Esports integration, and SportFi DeFi infrastructure. ## Use Cases The `eth_getBalance` method is essential for: - **Wallet applications** - Display user balances - **Transaction validation** - Check if account has sufficient funds - **DeFi applications** - Monitor collateral and liquidity for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets - **Account monitoring** - Track balance changes over time ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address to check balance for | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Integer of the current balance in wei (hexadecimal) | **Note**: 1 native token = 10^18 wei. Convert using `balance / 10^18`. ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1a055690d9db80000" } ``` ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x721EF6871f1c4Efe730dCE047d40D1743B886946'; const balanceWei = await provider.getBalance(address); const balance = formatEther(balanceWei); console.log(`Balance: ${balance}`); // Get balance at specific block const historicalBalance = await provider.getBalance(address, 1000000); console.log(`Historical balance: ${formatEther(historicalBalance)}`); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x721EF6871f1c4Efe730dCE047d40D1743B886946' balance_wei = w3.eth.get_balance(address) balance = w3.from_wei(balance_wei, 'ether') print(f'Balance: {balance}') # Get balance at specific block historical_balance = w3.eth.get_balance(address, block_identifier=1000000) print(f'Historical balance: {w3.from_wei(historical_balance, "ether")}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0x721EF6871f1c4Efe730dCE047d40D1743B886946") balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } // Convert to ether fbalance := new(big.Float).SetInt(balance) ethValue := new(big.Float).Quo(fbalance, big.NewFloat(1e18)) fmt.Printf("Balance: %f\n", ethValue) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid address format or block parameter | | -32000 | Execution error | Node execution error | ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_getTransactionCount`](./eth_getTransactionCount) - Get account nonce --- ## eth_getBlockByHash - Chiliz RPC Method # eth_getBlockByHash Returns information about a block by hash on Chiliz. > **Why Chiliz?** Build on the sports-first blockchain powering 2M+ fan token wallets and dozens of licensed sports partnerships with licensed partnerships with major football clubs, MiCA-compliant in EU, OG Esports integration, and SportFi DeFi infrastructure. ## Use Cases The `eth_getBlockByHash` method is essential for: - **Block verification** - Verify block data using its unique hash - **Chain reorganization handling** - Track blocks during reorgs - **Cross-chain bridges** - Verify block finality for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets - **Deterministic queries** - Get consistent block data regardless of chain state ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0xa9922ade53a153685d0ee94acdaf34dacc756b4a0170812abd7338daca98c178", false ], "id": 1 } ``` ## Returns Returns the same block object as `eth_getBlockByNumber`, or `null` if no block is found. | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used | | `transactions` | `Array` | Transaction objects or hashes | ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0xa9922ade53a153685d0ee94acdaf34dacc756b4a0170812abd7338daca98c178", false ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0xa9922ade53a153685d0ee94acdaf34dacc756b4a0170812abd7338daca98c178'; const block = await provider.getBlock(blockHash); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) block_hash = '0xa9922ade53a153685d0ee94acdaf34dacc756b4a0170812abd7338daca98c178' block = w3.eth.get_block(block_hash) print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockHash := common.HexToHash("0xa9922ade53a153685d0ee94acdaf34dacc756b4a0170812abd7338daca98c178") block, err := client.BlockByHash(context.Background(), blockHash) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block hash format | | -32000 | Block not found | Block with this hash does not exist | ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) - Get block by number - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number --- ## eth_getBlockByNumber - Chiliz RPC Method # eth_getBlockByNumber Returns information about a block by block number on Chiliz. > **Why Chiliz?** Build on the sports-first blockchain powering 2M+ fan token wallets and dozens of licensed sports partnerships with licensed partnerships with major football clubs, MiCA-compliant in EU, OG Esports integration, and SportFi DeFi infrastructure. ## Use Cases The `eth_getBlockByNumber` method is essential for: - **Block explorers** - Display complete block information - **Transaction indexers** - Process all transactions in a block - **Analytics platforms** - Analyze blockchain data for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets - **Timestamp verification** - Get block timestamps for time-based logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used by all transactions | | `gasLimit` | `QUANTITY` | Maximum gas allowed in block | | `transactions` | `Array` | Array of transaction objects or hashes | | `baseFeePerGas` | `QUANTITY` | Base fee per gas (EIP-1559) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": { "number": "0x5BAD55", "hash": "0xa9922ade53a153685d0ee94acdaf34dacc756b4a0170812abd7338daca98c178", "parentHash": "0x...", "timestamp": "0x64d8f6d0", "gasUsed": "0x1234", "gasLimit": "0x1c9c380", "transactions": [], "baseFeePerGas": "0x5f5e100" } } ``` ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Get latest block const block = await provider.getBlock('latest'); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); console.log('Transactions:', block.transactions.length); // Get block with full transactions const blockWithTxs = await provider.getBlock('latest', true); for (const tx of blockWithTxs.prefetchedTransactions) { console.log('Transaction:', tx.hash); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) # Get latest block block = w3.eth.get_block('latest') print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') print(f'Transactions: {len(block.transactions)}') # Get block with full transactions block_full = w3.eth.get_block('latest', full_transactions=True) for tx in block_full.transactions: print(f'Transaction: {tx.hash.hex()}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } // Get latest block block, err := client.BlockByNumber(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) fmt.Printf("Timestamp: %d\n", block.Time()) fmt.Printf("Transactions: %d\n", len(block.Transactions())) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block number or parameter format | | -32000 | Block not found | Block does not exist | ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number - [`eth_getBlockByHash`](./eth_getBlockByHash) - Get block by hash - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_getCode - Chiliz RPC Method # eth_getCode Returns the bytecode at a given address on Chiliz. > **Why Chiliz?** Build on the sports-first blockchain powering 2M+ fan token wallets and dozens of licensed sports partnerships with licensed partnerships with major football clubs, MiCA-compliant in EU, OG Esports integration, and SportFi DeFi infrastructure. ## Use Cases The `eth_getCode` method is essential for: - **Contract verification** - Check if address is a contract - **Security analysis** - Verify deployed bytecode matches expected - **DeFi integrations** - Validate contracts before interactions - **Protocol analysis** - Analyze contract deployments for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Contract bytecode or `0x` if EOA | ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x721EF6871f1c4Efe730dCE047d40D1743B886946'; const code = await provider.getCode(address); if (code === '0x') { console.log('Address is an EOA (externally owned account)'); } else { console.log('Address is a contract'); console.log('Bytecode length:', code.length); } // Check if address is a contract async function isContract(address) { const code = await provider.getCode(address); return code !== '0x'; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x721EF6871f1c4Efe730dCE047d40D1743B886946' code = w3.eth.get_code(address) if code == b'': print('Address is an EOA') else: print('Address is a contract') print(f'Bytecode length: {len(code.hex())}') # Check if address is a contract def is_contract(address): code = w3.eth.get_code(address) return code != b'' ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0x721EF6871f1c4Efe730dCE047d40D1743B886946") code, err := client.CodeAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } if len(code) == 0 { fmt.Println("Address is an EOA") } else { fmt.Printf("Contract bytecode length: %d\n", len(code)) } } ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_getStorageAt`](./eth_getStorageAt) - Get contract storage --- ## eth_getFilterChanges - Chiliz RPC Method # eth_getFilterChanges Polling method for a filter on Chiliz, returns an array of logs since last poll. ## Use Cases - **Event streaming** - Get new events incrementally - **Real-time monitoring** - Track contract activity for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets - **Efficient indexing** - Process only new events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Poll loop async function pollFilter(filterId, interval = 2000) { while (true) { const changes = await provider.send('eth_getFilterChanges', [filterId]); if (changes.length > 0) { console.log('New events:', changes); } await new Promise(r => setTimeout(r, interval)); } } ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter --- ## eth_getFilterLogs - Chiliz RPC Method # eth_getFilterLogs Returns an array of all logs matching filter with given ID on Chiliz. ## Use Cases - **Historical queries** - Get all matching logs for a filter - **Full event history** - Retrieve complete event data for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const logs = await provider.send('eth_getFilterLogs', [filterId]); console.log('All matching logs:', logs.length); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_getLogs - Chiliz RPC Method # eth_getLogs Returns an array of all logs matching a given filter object on Chiliz. > **Why Chiliz?** Build on the sports-first blockchain powering 2M+ fan token wallets and dozens of licensed sports partnerships with licensed partnerships with major football clubs, MiCA-compliant in EU, OG Esports integration, and SportFi DeFi infrastructure. ## Use Cases The `eth_getLogs` method is essential for: - **Event indexing** - Track contract events for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets - **Token transfers** - Monitor ERC20/ERC721 transfers - **DeFi analytics** - Track swaps, liquidity events, and more - **Notification systems** - Alert on specific on-chain events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block (default: `"latest"`) | | `toBlock` | `QUANTITY\|TAG` | No | Ending block (default: `"latest"`) | | `address` | `DATA\|Array` | No | Contract address(es) to filter | | `topics` | `Array` | No | Array of topic filters | | `blockHash` | `DATA` | No | Filter single block by hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns Array of log objects: | Field | Type | Description | |-------|------|-------------| | `address` | `DATA` | Contract that emitted the log | | `topics` | `Array` | Array of indexed topics | | `data` | `DATA` | Non-indexed log data | | `blockNumber` | `QUANTITY` | Block number | | `transactionHash` | `DATA` | Transaction hash | | `logIndex` | `QUANTITY` | Log index in block | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": [{ "address": "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."], "data": "0x...", "blockNumber": "0x5BAD55", "transactionHash": "0x...", "logIndex": "0x0" }] } ``` ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Get Transfer events const TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'; async function getTransferEvents(tokenAddress, fromBlock, toBlock) { const logs = await provider.getLogs({ address: tokenAddress, topics: [TRANSFER_TOPIC], fromBlock: fromBlock, toBlock: toBlock }); return logs.map(log => ({ from: '0x' + log.topics[1].slice(26), to: '0x' + log.topics[2].slice(26), blockNumber: log.blockNumber, transactionHash: log.transactionHash })); } const events = await getTransferEvents( '0x721EF6871f1c4Efe730dCE047d40D1743B886946', 'latest', 'latest' ); console.log('Transfer events:', events); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' def get_transfer_events(token_address, from_block, to_block): logs = w3.eth.get_logs({ 'address': token_address, 'topics': [TRANSFER_TOPIC], 'fromBlock': from_block, 'toBlock': to_block }) events = [] for log in logs: events.append({ 'from': '0x' + log['topics'][1].hex()[26:], 'to': '0x' + log['topics'][2].hex()[26:], 'block': log['blockNumber'], 'tx': log['transactionHash'].hex() }) return events events = get_transfer_events( '0x721EF6871f1c4Efe730dCE047d40D1743B886946', 'latest', 'latest' ) print(f'Found {len(events)} transfer events') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0x721EF6871f1c4Efe730dCE047d40D1743B886946") transferTopic := common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef") query := ethereum.FilterQuery{ FromBlock: big.NewInt(0), ToBlock: nil, Addresses: []common.Address{contractAddress}, Topics: [][]common.Hash, } logs, err := client.FilterLogs(context.Background(), query) if err != nil { log.Fatal(err) } fmt.Printf("Found %d events\n", len(logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32005 | Query returned more than 10000 results | Reduce block range | | -32602 | Invalid params | Invalid filter parameters | ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create a filter for logs - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for new logs --- ## eth_getStorageAt - Chiliz RPC Method # eth_getStorageAt Returns the value from a storage position at a given address on Chiliz. ## Use Cases - **Contract analysis** - Read raw storage values - **State verification** - Verify contract state - **Security auditing** - Analyze storage layout for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets - **Protocol monitoring** - Track state changes ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte contract address | | `position` | `QUANTITY` | Yes | Storage slot position | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "0x0", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "0x0", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x721EF6871f1c4Efe730dCE047d40D1743B886946'; const slot = 0; const storage = await provider.getStorage(address, slot); console.log('Storage at slot 0:', storage); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x721EF6871f1c4Efe730dCE047d40D1743B886946' storage = w3.eth.get_storage_at(address, 0) print(f'Storage at slot 0: {storage.hex()}') ``` ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_call`](./eth_call) - Call contract functions --- ## eth_getTransactionByHash - Chiliz RPC Method # eth_getTransactionByHash Returns the information about a transaction by transaction hash on Chiliz. > **Why Chiliz?** Build on the sports-first blockchain powering 2M+ fan token wallets and dozens of licensed sports partnerships with licensed partnerships with major football clubs, MiCA-compliant in EU, OG Esports integration, and SportFi DeFi infrastructure. ## Use Cases The `eth_getTransactionByHash` method is essential for: - **Transaction tracking** - Get details of pending or confirmed transactions - **Payment verification** - Verify transaction parameters - **Debugging** - Analyze transaction data for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets - **Block explorers** - Display transaction information ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x01038cb6fa5140b5068293ecaf6e2029eae653b9489388ff252e1c18b4606f39"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `hash` | `DATA` | Transaction hash | | `from` | `DATA` | Sender address | | `to` | `DATA` | Recipient address | | `value` | `QUANTITY` | Value in wei | | `gas` | `QUANTITY` | Gas provided | | `gasPrice` | `QUANTITY` | Gas price in wei | | `input` | `DATA` | Transaction input data | | `nonce` | `QUANTITY` | Sender's nonce | | `blockHash` | `DATA` | Block hash (null if pending) | | `blockNumber` | `QUANTITY` | Block number (null if pending) | ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x01038cb6fa5140b5068293ecaf6e2029eae653b9489388ff252e1c18b4606f39"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x01038cb6fa5140b5068293ecaf6e2029eae653b9489388ff252e1c18b4606f39'; const tx = await provider.getTransaction(txHash); if (tx) { console.log('From:', tx.from); console.log('To:', tx.to); console.log('Value:', formatEther(tx.value)); console.log('Block:', tx.blockNumber); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x01038cb6fa5140b5068293ecaf6e2029eae653b9489388ff252e1c18b4606f39' tx = w3.eth.get_transaction(tx_hash) if tx: print(f'From: {tx["from"]}') print(f'To: {tx["to"]}') print(f'Value: {w3.from_wei(tx["value"], "ether")}') print(f'Block: {tx["blockNumber"]}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x01038cb6fa5140b5068293ecaf6e2029eae653b9489388ff252e1c18b4606f39") tx, isPending, err := client.TransactionByHash(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Pending: %v\n", isPending) fmt.Printf("Value: %s\n", tx.Value().String()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash format | ## Related Methods - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction receipt - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionCount - Chiliz RPC Method # eth_getTransactionCount Returns the number of transactions sent from an address on Chiliz (the nonce). ## Use Cases - **Transaction building** - Get correct nonce for new transactions - **Account analysis** - Count total outgoing transactions - **Nonce management** - Handle pending transaction queues - **Wallet operations** - Prepare transactions for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag (`pending` for next nonce) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x721EF6871f1c4Efe730dCE047d40D1743B886946'; const nonce = await provider.getTransactionCount(address); console.log('Nonce:', nonce); // Get pending nonce for new transaction const pendingNonce = await provider.getTransactionCount(address, 'pending'); console.log('Next nonce:', pendingNonce); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x721EF6871f1c4Efe730dCE047d40D1743B886946' nonce = w3.eth.get_transaction_count(address) print(f'Nonce: {nonce}') # Get pending nonce pending_nonce = w3.eth.get_transaction_count(address, 'pending') print(f'Next nonce: {pending_nonce}') ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionReceipt - Chiliz RPC Method # eth_getTransactionReceipt Returns the receipt of a transaction by transaction hash on Chiliz. Receipt is only available for mined transactions. > **Why Chiliz?** Build on the sports-first blockchain powering 2M+ fan token wallets and dozens of licensed sports partnerships with licensed partnerships with major football clubs, MiCA-compliant in EU, OG Esports integration, and SportFi DeFi infrastructure. ## Use Cases The `eth_getTransactionReceipt` method is essential for: - **Transaction confirmation** - Verify transaction was mined successfully - **Gas analysis** - Check actual gas used vs estimated - **Event parsing** - Read emitted events from logs - **Status verification** - Confirm success/failure for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x01038cb6fa5140b5068293ecaf6e2029eae653b9489388ff252e1c18b4606f39"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `status` | `QUANTITY` | `1` (success) or `0` (failure) | | `transactionHash` | `DATA` | Transaction hash | | `blockHash` | `DATA` | Block hash | | `blockNumber` | `QUANTITY` | Block number | | `gasUsed` | `QUANTITY` | Gas used by this transaction | | `cumulativeGasUsed` | `QUANTITY` | Total gas used in block up to this tx | | `logs` | `Array` | Array of log objects | | `contractAddress` | `DATA` | Created contract address (if deployment) | ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x01038cb6fa5140b5068293ecaf6e2029eae653b9489388ff252e1c18b4606f39"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x01038cb6fa5140b5068293ecaf6e2029eae653b9489388ff252e1c18b4606f39'; const receipt = await provider.getTransactionReceipt(txHash); if (receipt) { console.log('Status:', receipt.status === 1 ? 'Success' : 'Failed'); console.log('Gas Used:', receipt.gasUsed.toString()); console.log('Block:', receipt.blockNumber); console.log('Logs:', receipt.logs.length); // Parse specific events for (const log of receipt.logs) { console.log('Event from:', log.address); } } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x01038cb6fa5140b5068293ecaf6e2029eae653b9489388ff252e1c18b4606f39' receipt = w3.eth.get_transaction_receipt(tx_hash) if receipt: status = 'Success' if receipt['status'] == 1 else 'Failed' print(f'Status: {status}') print(f'Gas Used: {receipt["gasUsed"]}') print(f'Block: {receipt["blockNumber"]}') print(f'Logs: {len(receipt["logs"])}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x01038cb6fa5140b5068293ecaf6e2029eae653b9489388ff252e1c18b4606f39") receipt, err := client.TransactionReceipt(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Status: %d\n", receipt.Status) fmt.Printf("Gas Used: %d\n", receipt.GasUsed) fmt.Printf("Logs: %d\n", len(receipt.Logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash | **Note**: Returns `null` if transaction is not yet mined. ## Related Methods - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details - [`eth_getLogs`](./eth_getLogs) - Query logs by filter --- ## eth_hashrate - Get node hashrate(Chiliz) # eth_hashrate Returns the number of hashes per second that the node is mining with on the Chiliz network. ## Parameters None (this method takes no parameters) ## Returns Returns the current hashrate as a hexadecimal string representing hashes per second. For non-mining nodes or networks using consensus mechanisms other than Proof of Work, this typically returns "0x0". ## Implementation Example ## Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_hashrate", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_hashrate', params: [], id: 1 }) }); const data = await response.json(); console.log('Hash rate:', data.result); ``` ```python url = 'https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY' headers = {'Content-Type': 'application/json'} payload = { "jsonrpc": "2.0", "method": "eth_hashrate", "params": [], "id": 1 } response = requests.post(url, headers=headers, data=json.dumps(payload)) data = response.json() print('Hash rate:', data['result']) ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0" } ``` ## Notes - For Chiliz network (Proof of Authority), this typically returns "0x0" since mining is handled by validators - This method is primarily for compatibility with Ethereum JSON-RPC specification - Useful for applications that need to detect mining capabilities across different networks --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Chiliz documentation](/docs/chiliz).* --- ## eth_maxPriorityFeePerGas - Chiliz RPC Method # eth_maxPriorityFeePerGas Returns the current recommended priority fee per gas on Chiliz for EIP-1559 transactions. ## Use Cases - **EIP-1559 transactions** - Set appropriate priority fees - **Transaction acceleration** - Calculate tips for faster inclusion - **Gas optimization** - Balance speed vs cost for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); console.log('Max Priority Fee:', formatUnits(feeData.maxPriorityFeePerGas, 'gwei'), 'Gwei'); console.log('Max Fee Per Gas:', formatUnits(feeData.maxFeePerGas, 'gwei'), 'Gwei'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) priority_fee = w3.eth.max_priority_fee print(f'Max Priority Fee: {w3.from_wei(priority_fee, "gwei")} Gwei') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get legacy gas price - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data --- ## eth_mining - Check if node is mining(Chiliz) # eth_mining Returns true if client is actively mining new blocks on the Chiliz network. ## Parameters None (this method takes no parameters) ## Returns Returns a boolean value indicating whether the node is actively mining. For Chiliz network (Proof of Authority), this typically returns false since block production is handled by validators rather than miners. ## Implementation Example ## Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_mining', params: [], id: 1 }) }); const data = await response.json(); console.log('Is mining:', data.result); ``` ```python url = 'https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY' headers = {'Content-Type': 'application/json'} payload = { "jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1 } response = requests.post(url, headers=headers, data=json.dumps(payload)) data = response.json() print('Is mining:', data['result']) ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": false } ``` ## Notes - For Chiliz network (Proof of Authority), this typically returns false since block production is handled by validators - This method is primarily for compatibility with Ethereum JSON-RPC specification - Useful for applications that need to detect mining capabilities across different networks --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Chiliz documentation](/docs/chiliz).* --- ## eth_newBlockFilter - Chiliz RPC Method # eth_newBlockFilter Creates a filter on Chiliz to notify when a new block arrives. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newBlockFilter', []); // Poll for new blocks const newBlocks = await provider.send('eth_getFilterChanges', [filterId]); console.log('New block hashes:', newBlocks); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_blockNumber`](./eth_blockNumber) - Get current block --- ## eth_newFilter - Chiliz RPC Method # eth_newFilter Creates a filter object on Chiliz to notify when state changes (logs). ## Use Cases - **Event monitoring** - Subscribe to contract events - **Real-time updates** - Track events for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets - **Indexing** - Build event indexes incrementally ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block | | `toBlock` | `QUANTITY\|TAG` | No | Ending block | | `address` | `DATA\|Array` | No | Contract address(es) | | `topics` | `Array` | No | Topic filters | ## Request ```json { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0x721EF6871f1c4Efe730dCE047d40D1743B886946", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0x721EF6871f1c4Efe730dCE047d40D1743B886946" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Create filter const filterId = await provider.send('eth_newFilter', [{ fromBlock: 'latest', address: '0x721EF6871f1c4Efe730dCE047d40D1743B886946', topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'] }]); // Poll for changes const changes = await provider.send('eth_getFilterChanges', [filterId]); console.log('New events:', changes); // Cleanup await provider.send('eth_uninstallFilter', [filterId]); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for changes - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_newPendingTransactionFilter - Chiliz RPC Method # eth_newPendingTransactionFilter Creates a filter on Chiliz to notify when new pending transactions arrive. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newPendingTransactionFilter', []); // Poll for pending transactions const pendingTxs = await provider.send('eth_getFilterChanges', [filterId]); console.log('Pending transaction hashes:', pendingTxs); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_protocolVersion - Get protocol version(Chiliz) # eth_protocolVersion Returns the current Ethereum protocol version on the Chiliz network. ## Parameters None (this method takes no parameters) ## Returns Returns the protocol version as a hexadecimal string. ## Implementation Example ## Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_protocolVersion", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_protocolVersion', params: [], id: 1 }) }); const data = await response.json(); console.log('Protocol version:', data.result); ``` ```python url = 'https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY' headers = {'Content-Type': 'application/json'} payload = { "jsonrpc": "2.0", "method": "eth_protocolVersion", "params": [], "id": 1 } response = requests.post(url, headers=headers, data=json.dumps(payload)) data = response.json() print('Protocol version:', data['result']) ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x41" } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Chiliz documentation](/docs/chiliz).* --- ## eth_sendRawTransaction - Chiliz RPC Method # eth_sendRawTransaction Submits a pre-signed transaction for broadcast to Chiliz. > **Why Chiliz?** Build on the sports-first blockchain powering 2M+ fan token wallets and dozens of licensed sports partnerships with licensed partnerships with major football clubs, MiCA-compliant in EU, OG Esports integration, and SportFi DeFi infrastructure. ## Use Cases The `eth_sendRawTransaction` method is essential for: - **Broadcasting transactions** - Submit signed transactions to the network - **Wallet operations** - Send native tokens and interact with contracts - **DeFi operations** - Execute swaps, provide liquidity for sports fan tokens (Socios.com), club voting rights, gamified fan experiences, and tokenized sports assets - **Batch operations** - Submit multiple transactions efficiently ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `signedTransactionData` | `DATA` | Yes | The signed transaction data (RLP encoded) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | 32-byte transaction hash | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c808504a817c80082520894..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const wallet = new Wallet('YOUR_PRIVATE_KEY', provider); // Send native tokens async function sendTransaction(to, value) { const tx = await wallet.sendTransaction({ to: to, value: parseEther(value) }); console.log('Transaction hash:', tx.hash); // Wait for confirmation const receipt = await tx.wait(); console.log('Confirmed in block:', receipt.blockNumber); return receipt; } // Send to contract async function sendContractTransaction(contract, method, args, value = '0') { const tx = await contract[method](...args, { value: parseEther(value) }); return await tx.wait(); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) def send_transaction(private_key, to, value_in_ether): account = w3.eth.account.from_key(private_key) # Build transaction tx = { 'nonce': w3.eth.get_transaction_count(account.address), 'to': to, 'value': w3.to_wei(value_in_ether, 'ether'), 'gas': 21000, 'gasPrice': w3.eth.gas_price, 'chainId': w3.eth.chain_id } # Sign transaction signed_tx = account.sign_transaction(tx) # Send transaction tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) print(f'Transaction hash: {tx_hash.hex()}') # Wait for confirmation receipt = w3.eth.wait_for_transaction_receipt(tx_hash) print(f'Confirmed in block: {receipt["blockNumber"]}') return receipt ``` ```go package main "context" "crypto/ecdsa" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY") if err != nil { log.Fatal(err) } publicKey := privateKey.Public() publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey) fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA) nonce, _ := client.PendingNonceAt(context.Background(), fromAddress) value := big.NewInt(1000000000000000000) gasLimit := uint64(21000) gasPrice, _ := client.SuggestGasPrice(context.Background()) toAddress := common.HexToAddress("0x721EF6871f1c4Efe730dCE047d40D1743B886946") tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil) chainID, _ := client.NetworkID(context.Background()) signedTx, _ := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey) err = client.SendTransaction(context.Background(), signedTx) if err != nil { log.Fatal(err) } fmt.Printf("Transaction hash: %s\n", signedTx.Hash().Hex()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Nonce too low | Transaction nonce already used | | -32000 | Insufficient funds | Account has insufficient balance | | -32000 | Gas too low | Gas limit insufficient | | -32000 | Replacement underpriced | Gas price too low for replacement | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas required - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction result --- ## eth_sendTransaction - Send transaction (walle... # eth_sendTransaction > **Important**: Dwellir's shared Chiliz endpoints do not manage user private keys. JSON-RPC nodes cannot unlock your account, so `eth_sendTransaction` calls will fail. Sign transactions client-side and broadcast them with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Why this method is disabled on shared nodes - [`eth_sendTransaction` requires the node to hold and unlock the `from` account's private key](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction). - Managed infrastructure providers disable it for security reasons rather than storing customer keys on shared servers (for example, [Infura explicitly blocks the method on shared endpoints](https://docs.infura.io/api/networks/ethereum/json-rpc-methods/eth_sendtransaction)). ## Recommended workflow 1. Build the raw transaction locally with your wallet or SDK. 2. Sign the payload client-side (hardware wallet, custodial service, or library). 3. Submit the signed hex string with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Example response from the shared endpoint ```bash curl -s -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"0x0000000000000000000000000000000000000000"}],"id":1}' ``` ```json {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"unknown account"}} ``` Need help? Contact our [support team](mailto:support@dwellir.com) or use the dedicated [`eth_sendRawTransaction`](./eth_sendRawTransaction) guide. --- ## eth_signTransaction - Sign transaction (rarel... # eth_signTransaction Signs a transaction using an unlocked account on the node. **Important**: Most RPC providers don't support this method for security reasons, as it requires private keys to be stored on the server. ## Security Considerations - This method requires an unlocked account on the node - Private keys must be available to the RPC server - Most production RPC providers disable this method - Use client-side signing libraries instead for better security ## Parameters 1. `Object` - The transaction object: - `from`: `DATA`, 20 Bytes - The address the transaction is sent from - `to`: `DATA`, 20 Bytes - (optional) The address the transaction is directed to - `gas`: `QUANTITY` - (optional) Integer of the gas provided for the transaction execution - `gasPrice`: `QUANTITY` - (optional) Integer of the gasPrice used for each paid gas - `value`: `QUANTITY` - (optional) Integer of the value sent with this transaction - `data`: `DATA` - (optional) The compiled code of a contract OR the hash of the invoked method signature and encoded parameters ## Returns `DATA` - The signed transaction data, ready for transmission via `eth_sendRawTransaction`. ## Implementation Example ## Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_signTransaction", "params": [{ "from": "0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a" }], "id": 1 }' ``` ```javascript const response = await fetch('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_signTransaction', params: [{ from: '0x9b2055d370f73ec7d8a03e965129118dc8f5bf83', to: '0xd46e8dd67c5d32be8058bb8eb970870f07244567', gas: '0x76c0', gasPrice: '0x9184e72a000', value: '0x9184e72a' }], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0xf86c808504a817c8008276c094d46e8dd67c5d32be8058bb8eb970870f072445675849184e72a8001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804" } ``` **Note**: This method is typically not available on hosted RPC providers for security reasons. The response shows a signed transaction ready for broadcast. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Chiliz documentation](/docs/chiliz).* --- ## eth_syncing - Chiliz RPC Method # eth_syncing Returns syncing status of Chiliz node. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 } ``` ## Returns Returns `false` if not syncing, or an object with sync status. ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const syncing = await provider.send('eth_syncing', []); if (syncing === false) { console.log('Node is fully synced'); } else { console.log('Syncing:', syncing); } ``` ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get current block - [`net_peerCount`](./net_peerCount) - Get peer count --- ## eth_uninstallFilter - Chiliz RPC Method # eth_uninstallFilter Uninstalls a filter on Chiliz. Should be called when no longer needed. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID to uninstall | ## Request ```json { "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if filter was found and uninstalled | ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const success = await provider.send('eth_uninstallFilter', [filterId]); console.log('Filter removed:', success); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter --- ## Chiliz RPC with Dwellir # Chiliz – Build on The Sports Blockchain ## Why Build on Chiliz? Chiliz is the leading blockchain for sports and entertainment, designed to power the $50 billion sports fan engagement market. Built as an Ethereum-compatible network, Chiliz offers: ### ⚽ **Sports-First Ecosystem** - **Fan Tokens™ native support** - Industry-leading fan engagement infrastructure - **2M+ active sports fans** - Direct access to the world's largest web3 sports community - **100+ sports partnerships** - Major clubs and organizations already integrated ### 🚀 **High Performance EVM** - **Fast finality** - Optimized consensus for real-time fan interactions - **Low transaction costs** - Affordable microtransactions for fan engagement - **EVM compatibility** - Full Ethereum tooling and contract support ### 🏆 **Proven Infrastructure** - **Battle-tested platform** - Powering millions of fan interactions since 2019 - **Enterprise-grade security** - Institutional infrastructure for major sports brands - **Scalable architecture** - Built to handle massive fan engagement events ## Quick Start with Chiliz Connect to Chiliz in seconds with Dwellir's optimized endpoints: ### Installation & Setup ```javascript // Connect to Chiliz mainnet const provider = new JsonRpcProvider( 'https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); // Get the latest block const block = await provider.getBlock('latest'); console.log('Latest block:', block.number); // Query account balance const balance = await provider.getBalance('0x...'); console.log('Balance:', balance.toString()); ``` ```javascript const Web3 = require('web3'); // Connect to Chiliz mainnet const web3 = new Web3( 'https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); // Get chain ID to verify connection const chainId = await web3.eth.getChainId(); console.log('Connected to Chiliz:', chainId === 88888); // Get gas price for optimal transaction pricing const gasPrice = await web3.eth.getGasPrice(); console.log('Current gas price:', gasPrice); ``` ```typescript const chiliz = defineChain({ id: 88888, name: 'Chiliz', nativeCurrency: { decimals: 18, name: 'CHZ', symbol: 'CHZ', }, rpcUrls: { default: { http: ['https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'], }, }, blockExplorers: { default: { name: 'ChilizScan', url: 'https://chiliscan.com' }, }, }); // Create Chiliz client const client = createPublicClient({ chain: chiliz, transport: http('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'), }); // Read contract data const data = await client.readContract({ address: '0x...', abi: contractAbi, functionName: 'balanceOf', args: ['0x...'], }); ``` ```python from web3 import Web3 # Connect to Chiliz mainnet w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) # Verify connection and get chain ID assert w3.is_connected() chain_id = w3.eth.chain_id print(f'Connected to Chiliz: {chain_id == 88888}') # Get latest block number block_number = w3.eth.block_number print(f'Latest block: {block_number}') ``` ## Network Information Chain ID 88888 Mainnet Testnet Chain ID 88882 Spicy Testnet Gas Token CHZ Native token RPC Standard Ethereum JSON-RPC 2.0 ## JSON-RPC API Reference Chiliz supports the full [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/). Access all standard methods for seamless EVM integration. ## Common Integration Patterns ### 🔄 Transaction Monitoring Monitor pending and confirmed transactions efficiently: ```javascript // Watch for transaction confirmation async function waitForTransaction(txHash) { const receipt = await provider.waitForTransaction(txHash, 1); // Log transaction success console.log('Transaction confirmed:', receipt.transactionHash); console.log('Gas used:', receipt.gasUsed.toString()); return receipt; } ``` ### 💰 Gas Optimization Optimize gas costs on Chiliz: ```javascript // Estimate gas for optimal transaction pricing const gasEstimate = await provider.estimateGas(tx); // Get current gas price const gasPrice = await provider.getGasPrice(); // Calculate total transaction cost const totalCost = gasEstimate * gasPrice; console.log('Estimated cost:', totalCost.toString(), 'CHZ'); ``` ### 🔍 Event Filtering Efficiently query contract events: ```javascript // Query events with pagination for large datasets async function getEvents(contract, eventName, fromBlock = 0) { const filter = contract.filters[eventName](); const events = []; const batchSize = 5000; // Chiliz recommended batch size for (let i = fromBlock; i <= currentBlock; i += batchSize) { const batch = await contract.queryFilter( filter, i, Math.min(i + batchSize - 1, currentBlock) ); events.push(...batch); } return events; } ``` ## Performance Best Practices ### 1. **Batch Requests** Combine multiple RPC calls for optimal performance: ```javascript const batch = [ { method: 'eth_blockNumber', params: [] }, { method: 'eth_gasPrice', params: [] }, { method: 'eth_getBalance', params: [address, 'latest'] } ]; const results = await provider.send(batch); ``` ### 2. **Connection Pooling** Reuse provider instances to minimize connection overhead: ```javascript // Singleton pattern for provider class ChilizProvider { static instance = null; static getInstance() { if (!this.instance) { this.instance = new JsonRpcProvider( 'https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); } return this.instance; } } ``` ### 3. **Smart Caching** Cache immutable data to reduce API calls: ```javascript const cache = new Map(); async function getCachedBlockData(blockNumber) { const key = `block_${blockNumber}`; if (!cache.has(key)) { const block = await provider.getBlock(blockNumber); cache.set(key, block); } return cache.get(key); } ``` ## Troubleshooting Common Issues ### Error: "Wrong Chain ID" Ensure you're using the correct chain ID for Chiliz: ```javascript // Verify chain connection const network = await provider.getNetwork(); console.log('Connected to chain ID:', network.chainId); // Mainnet should return 88888 (0x15b38 in hex) // Testnet should return 88882 (0x15b32 in hex) ``` ### Error: "Insufficient funds for gas" CHZ is required for all transactions on Chiliz: ```javascript // Check CHZ balance before transaction const balance = await provider.getBalance(address); const gasPrice = await provider.getGasPrice(); const gasEstimate = await provider.estimateGas(tx); const requiredGas = gasPrice * gasEstimate; if (balance < requiredGas + tx.value) { throw new Error(`Need ${(requiredGas + tx.value - balance).toString()} more CHZ`); } ``` ### Error: "Rate limit exceeded" Implement exponential backoff for resilient applications: ```javascript async function callWithRetry(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error.code === 429 && i < maxRetries - 1) { await new Promise(r => setTimeout(r, 2 ** i * 1000)); } else { throw error; } } } } ``` ## FAQs ### What makes Chiliz different from other EVM chains? Chiliz is purpose-built for sports and entertainment, offering native Fan Token infrastructure and direct access to millions of sports fans worldwide. ### Can I use existing Ethereum tools with Chiliz? Yes! Chiliz is fully EVM-compatible, so all Ethereum tools, libraries, and smart contracts work seamlessly. ### What's the native token on Chiliz? CHZ is the native gas token used for all transactions on Chiliz Chain. ### How do I get CHZ for testing? Use the Spicy Testnet with testnet CHZ from official faucets, or contact Dwellir support for testing assistance. ## Smoke Tests ### Test Mainnet Connection ```bash # Test mainnet connectivity curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' ``` ### Test Testnet Connection ```bash # Test Spicy testnet connectivity curl -X POST https://api-chiliz-spicy.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' ``` ### Ethers.js Chain Verification ```javascript const provider = new JsonRpcProvider( 'https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); // Verify connection and chain ID const network = await provider.getNetwork(); console.log('Chain ID:', network.chainId); // Should be 88888 console.log('Block number:', await provider.getBlockNumber()); ``` ### web3.py Connection Test ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) # Verify connection assert w3.is_connected(), "Failed to connect to Chiliz" print(f"Chain ID: {w3.eth.chain_id}") # Should be 88888 print(f"Latest block: {w3.eth.block_number}") ``` ## Migration Guide ### From Ethereum Mainnet Moving from Ethereum to Chiliz requires minimal changes: ```javascript // Before (Ethereum) const provider = new JsonRpcProvider('https://eth-rpc.example.com'); // After (Chiliz) const provider = new JsonRpcProvider( 'https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY' ); // ✅ Smart contracts work identically // ✅ Same tooling and libraries // ✅ Standard EVM opcodes // ⚠️ Different chain ID (88888) // ⚠️ CHZ as gas token instead of ETH // ⚠️ Sports-focused ecosystem ``` ## Resources & Tools ### Official Resources - [Chiliz Documentation](https://docs.chiliz.com) - [Chiliz Explorer](https://scan.chiliz.com) - [Spicy Testnet Explorer](https://spicy-explorer.chiliz.com) ### Sports Ecosystem - [Socios.com](https://socios.com) - Fan Token platform - [Fan Token Directory](https://www.chiliz.com/fan-tokens) - Available fan tokens - [Sports Partnerships](https://www.chiliz.com/partners) - Partner organizations ### Need Help? - 📧 **Email**: support@dwellir.com - 📚 **Docs**: You're here! - 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com) --- *Start building on Chiliz with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)* --- ## net_listening - Chiliz RPC Method # net_listening Returns `true` if client is actively listening for network connections on Chiliz. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if listening | ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const listening = await provider.send('net_listening', []); console.log('Node listening:', listening); ``` ## Related Methods - [`net_peerCount`](./net_peerCount) - Get peer count --- ## net_peerCount - Chiliz RPC Method # net_peerCount Returns number of peers currently connected to Chiliz client. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Number of connected peers (hexadecimal) | ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const peerCount = await provider.send('net_peerCount', []); console.log('Peer count:', parseInt(peerCount, 16)); ``` ## Related Methods - [`net_listening`](./net_listening) - Check if listening --- ## net_version - Chiliz RPC Method # net_version Returns the current network ID on Chiliz. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Network ID as a string | ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const networkId = await provider.send('net_version', []); console.log('Network ID:', networkId); ``` ## Related Methods - [`eth_chainId`](./eth_chainId) - Get chain ID --- ## web3_clientVersion - Chiliz RPC Method # web3_clientVersion Returns the current client version on Chiliz. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Client version string | ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const version = await provider.send('web3_clientVersion', []); console.log('Client version:', version); ``` --- ## web3_sha3 - Chiliz RPC Method # web3_sha3 Returns Keccak-256 (not standard SHA3-256) of the given data on Chiliz. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `data` | `DATA` | Yes | Data to hash | ## Request ```json { "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Keccak-256 hash of the data | ## Code Examples ```bash curl -X POST https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-chiliz-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Using RPC const hash = await provider.send('web3_sha3', ['0x68656c6c6f']); console.log('Hash:', hash); // Using ethers directly (faster) const localHash = keccak256(toUtf8Bytes('hello')); console.log('Local hash:', localHash); ``` --- ## API Key Management Use `dwellir keys` to create, list, update, and delete API keys for your Dwellir account. ## List all keys ```bash dwellir keys list ``` With JSON output: ```bash dwellir keys list --json ``` ```json { "ok": true, "data": [ { "api_key": "d8d3c1c5-c22e-40f3-8407-50fa0e01eef9", "name": "production", "enabled": true, "created_at": "2025-10-14T14:07:24.592946", "updated_at": "2025-10-14T14:07:24.592946" } ], "meta": { "command": "keys.list", "timestamp": "2026-02-26T12:00:00Z" } } ``` The `daily_quota` and `monthly_quota` fields appear only when a quota has been set on the key. Keys without quotas omit these fields (shown as "Unlimited" in human output). ## Create a key ```bash dwellir keys create --name my-key ``` Optionally set quotas at creation time: ```bash dwellir keys create --name ci-key --daily-quota 100000 --monthly-quota 3000000 ``` | Flag | Description | |------|-------------| | `--name` | A descriptive name for the key (required) | | `--daily-quota` | Maximum requests per day (0 = unlimited) | | `--monthly-quota` | Maximum requests per month (0 = unlimited) | ## Update a key Change the name or quotas of an existing key: ```bash dwellir keys update --name new-name --daily-quota 50000 ``` Only the flags you pass are updated. For example, to change just the daily quota: ```bash dwellir keys update --daily-quota 200000 ``` ## Enable and disable a key Temporarily disable a key without deleting it: ```bash dwellir keys disable ``` Re-enable it later: ```bash dwellir keys enable ``` A disabled key returns `403` errors for any API requests made with it. ## Delete a key Permanently remove an API key: ```bash dwellir keys delete ``` :::warning Deletion is permanent. Any application using this key will immediately lose access. Disable the key first if you want to test the impact. ::: ## Scripting example Create a key, extract the ID, and use it in a CI pipeline: ```bash # Create a key and capture the API key value API_KEY=$(dwellir keys create --name "ci-$(date +%Y%m%d)" --daily-quota 50000 --json \ | jq -r '.data.api_key') echo "Created key: $API_KEY" # ... use the key ... # Clean up dwellir keys delete "$API_KEY" ``` ## Next steps - [Discover endpoints](/cli/endpoints) to use with your keys - [Monitor usage](/cli/usage-and-logs) for your keys - Run `dwellir keys --help` for the full list of flags --- ## Authentication(Cli) Authenticate the Dwellir CLI before managing keys, viewing usage, or accessing account data. The method depends on your environment. ## Browser login (interactive) For local development, open a browser-based login flow: ```bash dwellir auth login ``` This opens your default browser to the Dwellir dashboard. After you sign in, the CLI receives a token via a local callback and stores it in your profile. ## Token login (headless / CI) For CI/CD pipelines, Docker containers, or any environment without a browser, pass a token directly: ```bash dwellir auth login --token ``` Alternatively, set the token as an environment variable: ```bash export DWELLIR_TOKEN= ``` When `DWELLIR_TOKEN` is set, the CLI uses it for every command without needing `dwellir auth login`. ### Getting a CLI token 1. Go to [dashboard.dwellir.com](https://dashboard.dwellir.com) 2. Navigate to **Settings > CLI Tokens** (or the [Agents page](https://dashboard.dwellir.com/agents)) 3. Click **Create Token**, give it a name, and copy the value 4. Store the token securely (e.g., as a CI secret) ## Check auth status See who you are logged in as and which profile is active: ```bash dwellir auth status ``` ```bash dwellir auth status --json ``` ```json { "ok": true, "data": { "profile": "default", "user": "you@example.com", "org": "Your Organization" } } ``` The `user` and `org` fields are populated when authenticating via the browser flow. Token-based authentication may return empty values for these fields depending on the token type. ## Print the current token Print the resolved access token to stdout, useful for piping into other tools: ```bash dwellir auth token ``` For example, to pass the Dwellir token to another script: ```bash export TOKEN=$(dwellir auth token) ``` ## Logout Remove local credentials for the active profile: ```bash dwellir auth logout ``` This deletes the profile file from `~/.config/dwellir/profiles/`. It does not revoke the token on the server. ## Token resolution order When the CLI needs an auth token, it checks these sources in order: 1. **`DWELLIR_TOKEN`** environment variable 2. **`--token`** flag passed to the command 3. **Profile file** (resolved via the profile resolution chain below) The first source that provides a non-empty token wins. ## Profile resolution order When the CLI needs to determine which profile to load, it checks: 1. **`--profile`** flag 2. **`DWELLIR_PROFILE`** environment variable 3. **`.dwellir.json`** file in the current directory or any parent directory 4. **`default_profile`** setting in `~/.config/dwellir/config.json` 5. **`"default"`** as a fallback ## Multiple profiles You can maintain separate profiles for different accounts or organizations: ```bash # Login to a "work" profile dwellir auth login --profile work # Login to a "personal" profile dwellir auth login --profile personal # Use a specific profile for one command dwellir keys list --profile work ``` ### Per-project profile binding Create a `.dwellir.json` file in your project root to automatically select a profile when you run commands from that directory: ```json { "profile": "work" } ``` Now any `dwellir` command run inside that project tree uses the `work` profile without needing the `--profile` flag. ## Next steps - [Manage API keys](/cli/api-keys) - [Discover endpoints](/cli/endpoints) - [Configure profiles and defaults](/cli/configuration) --- ## Configuration The Dwellir CLI stores configuration and profile data on disk and can be customized via commands, config files, and environment variables. ## Config location All CLI configuration lives under a single directory: ``` ~/.config/dwellir/ config.json # Global settings profiles/ default.json # Default profile (token, user, org) work.json # Additional profiles ``` Override the config directory with `DWELLIR_CONFIG_DIR`: ```bash export DWELLIR_CONFIG_DIR=/custom/path ``` ## Config commands ### Set a value ```bash dwellir config set ``` Valid keys: | Key | Values | Description | |-----|--------|-------------| | `output` | `json` or `human` | Default output format for all commands | | `default_profile` | any profile name | Profile to use when no other is specified | Examples: ```bash # Always output JSON by default dwellir config set output json # Use the "work" profile by default dwellir config set default_profile work ``` ### Get a value ```bash dwellir config get output ``` ### List all settings ```bash dwellir config list ``` ```bash dwellir config list --json ``` ```json { "ok": true, "data": { "output": "human", "default_profile": "default" } } ``` ## Profiles Profiles store per-account authentication credentials. Each profile is a separate JSON file under `~/.config/dwellir/profiles/`. Create a profile by logging in with a name: ```bash dwellir auth login --profile work dwellir auth login --profile personal ``` Switch profiles per command: ```bash dwellir keys list --profile work dwellir keys list --profile personal ``` Or set a default: ```bash dwellir config set default_profile work ``` ### Per-project profile binding Create a `.dwellir.json` file in any directory to automatically select a profile for that project: ```json { "profile": "work" } ``` When you run any `dwellir` command from that directory (or any subdirectory), the CLI automatically uses the `work` profile. This is useful when you work on multiple projects tied to different Dwellir organizations. The CLI searches for `.dwellir.json` starting from the current directory and walking up to the filesystem root. The first match wins. ## Account info View your organization and plan details: ```bash dwellir account info ``` ```bash dwellir account info --json ``` View subscription details: ```bash dwellir account subscription ``` ## Environment variables Environment variables override config files and flags where noted. | Variable | Description | |----------|-------------| | `DWELLIR_TOKEN` | Auth token override. Takes highest priority in the [token resolution chain](/cli/authentication#token-resolution-order). | | `DWELLIR_PROFILE` | Profile name override. Takes priority over `.dwellir.json` and `default_profile`. | | `DWELLIR_CONFIG_DIR` | Custom config directory (default: `~/.config/dwellir/`) | | `DWELLIR_API_URL` | Override API base URL (default: `https://dashboard.dwellir.com/marly-api`) | | `DWELLIR_DASHBOARD_URL` | Override dashboard URL for browser auth | | `DWELLIR_DOCS_BASE_URL` | Override docs base URL (default: `https://www.dwellir.com/docs`) | | `DWELLIR_DOCS_INDEX_URL` | Override docs index URL (default: `/llms.txt`) | ### CI/CD example A minimal GitHub Actions setup using environment variables: ```yaml jobs: deploy: runs-on: ubuntu-latest steps: - name: Install Dwellir CLI run: curl -fsSL https://raw.githubusercontent.com/dwellir-public/cli/main/scripts/install.sh | sh - name: Create temporary API key env: DWELLIR_TOKEN: ${{ secrets.DWELLIR_CLI_TOKEN }} run: | dwellir keys create --name "ci-${{ github.run_id }}" --daily-quota 50000 --json ``` ## Next steps - [Authentication](/cli/authentication) -- token and profile resolution details - [API Keys](/cli/api-keys) -- manage keys from the CLI - Run `dwellir config --help` for the full list of subcommands --- ## Endpoint Discovery Use `dwellir endpoints` to browse and search all available blockchain networks on Dwellir. ## List all endpoints ```bash dwellir endpoints list ``` This returns every supported chain and network with connection details. ## Search by name Find endpoints matching a keyword: ```bash dwellir endpoints search ethereum ``` ```bash dwellir endpoints search polkadot ``` The search matches against chain names and network identifiers. ## Get a specific chain Retrieve details for a single chain: ```bash dwellir endpoints get base ``` If no match is found, the CLI returns a helpful error: ```bash dwellir endpoints get nonexistent --json ``` ```json { "ok": false, "error": { "code": "not_found", "message": "No endpoints found for 'nonexistent'.", "help": "Run 'dwellir endpoints list' to see all available chains." } } ``` ## Filtering Narrow results using filter flags. These work with `list`, `search`, and `get`: | Flag | Example values | Description | |------|----------------|-------------| | `--ecosystem` | `evm`, `substrate`, `cosmos`, `move`, `hyperliquid`, `other` | Filter by blockchain ecosystem | | `--network` | `mainnet`, `testnet`, or a specific network name | Filter by network name (case-insensitive substring match) | | `--node-type` | `full`, `archive` | Filter by node type (case-insensitive match) | | `--protocol` | `https`, `wss` | Filter by connection protocol | | `--key` | key name or value (optional) | Insert an API key into endpoint URLs. Pass a key name to select a specific key, or use `--key` alone to auto-select (requires exactly one key). | ### Examples List all EVM chains: ```bash dwellir endpoints list --ecosystem evm ``` Show only mainnet endpoints for Ethereum: ```bash dwellir endpoints search ethereum --network mainnet ``` List archive nodes in the Substrate ecosystem: ```bash dwellir endpoints list --ecosystem substrate --node-type archive ``` Combine multiple filters: ```bash dwellir endpoints list --ecosystem evm --network mainnet --node-type archive ``` Get ready-to-use URLs with your API key inserted: ```bash dwellir endpoints search ethereum --key my-key-name --protocol https ``` ## JSON output Use `--json` to get structured data for scripting: ```bash dwellir endpoints search ethereum --protocol https --json ``` ```json { "ok": true, "data": [ { "id": 41, "name": "Ethereum", "ecosystem": "evm", "networks": [ { "id": 43, "name": "Mainnet", "nodes": [ { "id": 404, "https": "https://api-ethereum-mainnet.n.dwellir.com/", "wss": "wss://api-ethereum-mainnet.n.dwellir.com/", "node_type": { "name": "Archive" } } ] } ] } ], "meta": { "command": "endpoints.search", "timestamp": "2026-02-26T12:00:00Z" } } ``` The response is organized as chains containing networks, each with one or more nodes. Each node includes `https` and `wss` URLs where `` is your API key. ## Next steps - [Create an API key](/cli/api-keys) to use with discovered endpoints - [Monitor usage](/cli/usage-and-logs) across your endpoints - See the full [Supported Chains](/getting-started/supported-chains) list for network-specific documentation - Run `dwellir endpoints --help` for the full list of flags --- ## Dwellir CLI The Dwellir CLI (`dwellir`) gives you full access to the Dwellir platform from the command line. Authenticate, manage API keys, discover 150+ blockchain endpoints, monitor usage, and inspect error logs -- all without leaving your terminal. It is built for three audiences: - **Developers** who prefer terminal workflows over a web dashboard - **CI/CD pipelines** that need to provision and rotate API keys automatically - **AI agents** that consume structured JSON output ## Quick start ```bash # Install curl -fsSL https://raw.githubusercontent.com/dwellir-public/cli/main/scripts/install.sh | sh # Authenticate dwellir auth login # List your API keys dwellir keys list # Discover Ethereum endpoints dwellir endpoints search ethereum ``` Also available via [Homebrew, AUR, `go install`, or from source](/cli/installation). ## Output modes Every command supports multiple output modes: - `--human` -- formatted tables and key-value displays (default in interactive terminals) - `--json` -- JSON wrapped in a standard `{ok, data, meta}` envelope for scripting and automation - `--toon` -- experimental TOON format (structured text) When stdout is not a terminal (e.g., piped to another command or run in CI), the CLI automatically outputs JSON. Use `--human` to force human-readable output in non-interactive environments. ```bash dwellir keys list --json ``` JSON responses use a consistent envelope: ```json { "ok": true, "data": { ... }, "meta": { "command": "keys.list", "timestamp": "2026-02-26T12:00:00Z" } } ``` Errors return `ok: false` with an error code, message, and optional help text, plus a non-zero exit code. ## Command overview | Command | Description | |---------|-------------| | `dwellir auth` | Login, logout, check status, print tokens | | `dwellir keys` | Create, list, update, enable, disable, and delete API keys | | `dwellir endpoints` | Browse and search 150+ blockchain endpoints | | `dwellir usage` | View billing-cycle summary, usage by endpoint/method, costs, and RPS | | `dwellir logs` | Inspect error logs, stats, and facet aggregations | | `dwellir account` | View organization info and subscription details | | `dwellir docs` | List, search, and fetch Dwellir documentation as markdown | | `dwellir config` | Get and set CLI configuration values | | `dwellir completion` | Generate or install shell completions (bash, zsh, fish, powershell) | | `dwellir update` | Self-update to the latest release | | `dwellir version` | Print build and version metadata | ## Global flags These flags work on every command: | Flag | Description | |------|-------------| | `--json` | Output as JSON (auto-selected when stdout is not a terminal) | | `--human` | Output as human-readable tables (default in interactive terminals) | | `--toon` | Output as TOON format (experimental) | | `--profile ` | Use a specific auth profile | | `-q`, `--quiet` | Suppress non-essential output | | `--anon-telemetry` | Anonymize telemetry data | Run `dwellir --help` or `dwellir --help` for full usage details. ## Next steps - [Installation](/cli/installation) -- five ways to install the CLI - [Authentication](/cli/authentication) -- browser login, CI tokens, and profiles - [API Keys](/cli/api-keys) -- create and manage keys - [Endpoints](/cli/endpoints) -- discover blockchain networks - [Usage & Logs](/cli/usage-and-logs) -- monitor requests and debug errors - [Configuration](/cli/configuration) -- profiles, environment variables, and per-project settings - [Agent Tooling](/agents) -- migration prompt, agent skills, and documentation endpoints for AI agents --- ## Installation There are five ways to install the Dwellir CLI. Pick whichever suits your environment. ## Homebrew (macOS and Linux) The recommended method for most users: ```bash brew tap dwellir-public/homebrew-tap brew install dwellir ``` To upgrade later: ```bash brew update && brew upgrade dwellir ``` ## AUR (Arch Linux) If you are on Arch Linux, install from the AUR using your preferred helper: ```bash yay -S dwellir-cli-bin ``` ## Install script Download and run the latest release installer: ```bash curl -fsSL https://raw.githubusercontent.com/dwellir-public/cli/main/scripts/install.sh | sh ``` This detects your OS and architecture, downloads the correct binary from GitHub Releases, and places it in a directory on your `PATH`. ## Go install If you have Go 1.24+ installed: ```bash go install github.com/dwellir-public/cli/cmd/dwellir@latest ``` Go places the binary in `$GOPATH/bin` (or `$GOBIN`). Make sure that directory is on your `PATH`. ## Build from source ```bash git clone https://github.com/dwellir-public/cli.git cd cli make build ``` The build outputs `./bin/dwellir`. Move it somewhere on your `PATH`, or run it directly. ## Verify installation Confirm the CLI is installed and working: ```bash dwellir version ``` Example output: ``` Arch amd64 Build Date 2026-02-27T12:50:44Z Commit ca1b849 Go Version go1.24.13 Os linux Version 0.1.14 ``` Use `--json` for machine-readable output: ```bash dwellir version --json ``` ## Self-update After installation, you can update to the latest release from within the CLI itself: ```bash dwellir update ``` This checks GitHub Releases and replaces the running binary in place. If you installed via Homebrew, prefer `brew upgrade dwellir` instead to keep Homebrew's records consistent. ## Next steps Once installed, [authenticate](/cli/authentication) to start using the CLI. --- ## Usage & Logs The Dwellir CLI provides two command groups for monitoring your API activity: `dwellir usage` for request analytics and `dwellir logs` for error inspection. ## Usage ### Billing cycle summary View your total requests for the current billing cycle: ```bash dwellir usage summary ``` ```bash dwellir usage summary --json ``` ### Usage history View request counts grouped by endpoint: ```bash dwellir usage history ``` | Flag | Default | Description | |------|---------|-------------| | `--interval` | `hour` | Aggregation interval: `minute`, `hour`, or `day` | | `--from` | start of billing cycle | Start time in RFC 3339 format | | `--to` | now | End time in RFC 3339 format | | `--api-key` | | Filter by API key value | | `--fqdn` | | Filter by endpoint hostname (FQDN) | | `--method` | | Filter by RPC method | Examples: ```bash # Daily usage grouped by endpoint dwellir usage history --interval day --from 2026-02-19T00:00:00Z # Filter to a specific endpoint dwellir usage history --fqdn api-ethereum-mainnet.n.dwellir.com --interval day # Filter by RPC method dwellir usage history --method eth_call --from 2026-02-01T00:00:00Z ``` ### Usage by RPC method View request counts grouped by RPC method: ```bash dwellir usage methods ``` | Flag | Default | Description | |------|---------|-------------| | `--interval` | `hour` | Aggregation interval: `minute`, `hour`, or `day` | | `--from` | start of billing cycle | Start time in RFC 3339 format | | `--to` | now | End time in RFC 3339 format | | `--api-key` | | Filter by API key value | | `--fqdn` | | Filter by endpoint hostname (FQDN) | ### Requests per second View RPS over time across all endpoints: ```bash dwellir usage rps ``` | Flag | Default | Description | |------|---------|-------------| | `--interval` | `hour` | Aggregation interval: `minute`, `hour`, or `day` | | `--from` | past 24 hours | Start time in RFC 3339 format | | `--to` | now | End time in RFC 3339 format | | `--api-key` | | Filter by API key value | | `--fqdn` | | Filter by endpoint hostname (FQDN) | ```bash dwellir usage rps --json ``` ### Estimated costs View estimated cost breakdown for a usage window (requires Developer plan or higher): ```bash dwellir usage costs ``` | Flag | Default | Description | |------|---------|-------------| | `--interval` | `hour` | Aggregation interval: `minute`, `hour`, or `day` | | `--from` | start of billing cycle | Start time in RFC 3339 format | | `--to` | now | End time in RFC 3339 format | | `--api-key` | | Filter by API key value | | `--fqdn` | | Filter by endpoint hostname (FQDN) | | `--method` | | Filter by RPC method | ### Usage query limits Check your plan's usage query limits (max lookback, supported intervals): ```bash dwellir usage limits ``` ```bash dwellir usage limits --json ``` ## Logs ### Error logs List recent error responses with optional filters: ```bash dwellir logs errors ``` | Flag | Description | |------|-------------| | `--key` | Filter by API key | | `--endpoint` | Filter by endpoint FQDN | | `--status-code` | Filter by HTTP status code | | `--rpc-method` | Filter by RPC method name | | `--from` | Start time (RFC 3339) | | `--to` | End time (RFC 3339) | | `--limit` | Maximum results (default: 50) | | `--cursor` | Pagination cursor for next page | Examples: ```bash # Show rate-limit errors dwellir logs errors --status-code 429 # Errors for a specific key in the last hour dwellir logs errors --key abc12345-... --from 2026-02-26T11:00:00Z # Filter by RPC method dwellir logs errors --rpc-method eth_call --limit 20 # Combine filters dwellir logs errors --endpoint api-ethereum-mainnet.n.dwellir.com --status-code 500 --limit 100 ``` ### Error stats View error counts grouped by status code: ```bash dwellir logs stats ``` Filter the same way as `errors`: ```bash dwellir logs stats --key abc12345-... --from 2026-02-20T00:00:00Z ``` ### Error facets Get aggregated breakdowns of error activity across four dimensions: ```bash dwellir logs facets ``` The output is grouped into four sections: - **FQDNs** -- which endpoints see the most errors - **RPC Methods** -- which methods generate the most errors - **Origins** -- traffic origin breakdown (e.g., `backend` vs `gateway`) - **API Keys** -- error counts per key ```bash dwellir logs facets --from 2026-02-01T00:00:00Z --to 2026-02-28T00:00:00Z --json ``` This is useful for identifying which endpoints or methods generate the most errors. ## Pagination The `logs errors` command supports cursor-based pagination. When more results are available, the response includes a cursor in the metadata: ```bash # Get the first page dwellir logs errors --limit 50 --json # Use the cursor from the response to get the next page dwellir logs errors --limit 50 --cursor --json ``` ## Next steps - [Manage API keys](/cli/api-keys) to adjust quotas when you see rate-limit errors - [Discover endpoints](/cli/endpoints) to check available networks - Run `dwellir usage --help` or `dwellir logs --help` for the full list of flags --- ## debug_traceBlock - Cronos RPC Method # debug_traceBlock Traces all transactions in a block on Cronos by block RLP. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Analyze transaction execution step-by-step - **Smart contract analysis** - Debug contract interactions - **Security auditing** - Trace internal calls for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockRlp` | `DATA` | Yes | RLP-encoded block data | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Use debug_traceBlockByNumber instead (more practical) const traces = await provider.send('debug_traceBlockByNumber', ['latest', {}]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by block number - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by block hash --- ## debug_traceBlockByHash - Cronos RPC Method # debug_traceBlockByHash Traces all transactions in a block on Cronos by block hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0xc8a64cd89ea7954a5f8064bf7c5fb907226e1dbb66a05d6043f7052191686f06", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0xc8a64cd89ea7954a5f8064bf7c5fb907226e1dbb66a05d6043f7052191686f06", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0xc8a64cd89ea7954a5f8064bf7c5fb907226e1dbb66a05d6043f7052191686f06'; const traces = await provider.send('debug_traceBlockByHash', [blockHash, { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by number - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceBlockByNumber - Cronos RPC Method # debug_traceBlockByNumber Traces all transactions in a block on Cronos by block number. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('debug_traceBlockByNumber', ['latest', { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by hash - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceCall - Cronos RPC Method # debug_traceCall Traces a call without creating a transaction on Cronos. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction simulation** - Debug before sending - **Gas analysis** - Analyze gas usage per opcode - **Contract debugging** - Step through execution for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `call` | `Object` | Yes | Call object (same as eth_call) | | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ { "to": "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "data": "0x70a082310000000000000000000000005C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23" }, "latest", {} ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ {"to": "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "data": "0x70a082310000000000000000000000005C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23"}, "latest", {"tracer": "callTracer"} ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const trace = await provider.send('debug_traceCall', [ { to: '0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23', data: '0x70a082310000000000000000000000005C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23' }, 'latest', { tracer: 'callTracer' } ]); console.log('Trace:', trace); ``` ## Related Methods - [`eth_call`](./eth_call) - Execute call without trace - [`debug_traceTransaction`](./debug_traceTransaction) - Trace actual transaction --- ## debug_traceTransaction - Cronos RPC Method # debug_traceTransaction Traces a transaction execution on Cronos by transaction hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Understand exactly what happened - **Failure analysis** - Find where and why a transaction reverted - **Gas optimization** - Analyze gas usage for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Tracer Options - `{}` - Default opcode tracer (verbose) - `{ tracer: "callTracer" }` - Call tree tracer - `{ tracer: "prestateTracer" }` - Pre-state tracer ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x159952dbecdbb7c17e962de632fe2560cddcdb371b4d98f37015e3682669f39c", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x159952dbecdbb7c17e962de632fe2560cddcdb371b4d98f37015e3682669f39c", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x159952dbecdbb7c17e962de632fe2560cddcdb371b4d98f37015e3682669f39c'; // Call tracer - shows internal calls const callTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'callTracer' } ]); console.log('Type:', callTrace.type); console.log('From:', callTrace.from); console.log('To:', callTrace.to); console.log('Gas used:', parseInt(callTrace.gasUsed, 16)); // Prestate tracer - shows state before execution const prestateTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'prestateTracer' } ]); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x159952dbecdbb7c17e962de632fe2560cddcdb371b4d98f37015e3682669f39c' # Call tracer trace = w3.provider.make_request('debug_traceTransaction', [ tx_hash, {'tracer': 'callTracer'} ]) print(f'Trace type: {trace["result"]["type"]}') print(f'Gas used: {int(trace["result"]["gasUsed"], 16)}') ``` ## Related Methods - [`debug_traceCall`](./debug_traceCall) - Trace without executing - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace entire block --- ## eth_accounts - Cronos RPC Method # eth_accounts Returns a list of addresses owned by the client on Cronos. > **Why Cronos?** Build on the EVM-compatible Crypto.com blockchain with fast finality and deep Crypto.com ecosystem integration. ## Important Note On public RPC endpoints like Dwellir, `eth_accounts` returns an empty array because the node does not hold any private keys. This method is primarily useful for: - Local development nodes (Ganache, Hardhat, Anvil) - Private nodes with managed accounts - Wallet provider connections (MetaMask injects accounts) ## When to Use This Method `eth_accounts` is relevant for Cronos developers building DeFi and payment applications in specific scenarios: - **Development Testing** — Retrieve test accounts from local nodes - **Wallet Detection** — Check if a wallet provider has connected accounts - **Client Verification** — Confirm node account access capabilities ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `Array` | List of 20-byte account addresses owned by the client | **Return format**: Array of `0x` prefixed hexadecimal addresses (typically empty for public nodes) ## Request ```json { "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 } ``` ## Response ### Successful Response (Public Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [] } ``` ### Successful Response (Local Development Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [ "0x407d73d8a49eeb85d32cf465507dd71d507100c1", "0x85d32cf465507dd71d507100c1407d73d8a49eeb" ] } ``` ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_accounts', params: [], id: 1 }) }); const { result } = await response.json(); console.log('Accounts:', result); // Using ethers.js const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const accounts = await provider.listAccounts(); console.log('Accounts:', accounts); ``` ```python def get_accounts(): response = requests.post( 'https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_accounts', 'params': [], 'id': 1 } ) return response.json()['result'] accounts = get_accounts() print(f'Accounts: {accounts}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) print(f'Accounts: {w3.eth.accounts}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/rpc" ) func main() { client, err := rpc.Dial("https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } var accounts []string err = client.CallContext(context.Background(), &accounts, "eth_accounts") if err != nil { log.Fatal(err) } fmt.Printf("Accounts: %v\n", accounts) } ``` ## Common Use Cases ### 1. Development Environment Detection Check if running against a development node with test accounts: ```javascript async function isDevEnvironment(provider) { const accounts = await provider.listAccounts(); return accounts.length > 0; } const isDev = await isDevEnvironment(provider); if (isDev) { console.log('Development environment detected'); } ``` ### 2. Wallet Connection Check Verify wallet provider has connected accounts: ```javascript async function checkWalletConnection() { if (typeof window.ethereum === 'undefined') { return { connected: false, reason: 'No wallet detected' }; } const accounts = await window.ethereum.request({ method: 'eth_accounts' }); return { connected: accounts.length > 0, accounts: accounts }; } ``` ### 3. Fallback Account Selection Use first available account or request connection: ```javascript async function getActiveAccount() { // Check existing connections let accounts = await window.ethereum.request({ method: 'eth_accounts' }); // Request connection if no accounts if (accounts.length === 0) { accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); } return accounts[0] || null; } ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32601 | Method not found | Node may not support this method | | -32603 | Internal error | Retry with exponential backoff | ```javascript async function safeGetAccounts(provider) { try { const accounts = await provider.listAccounts(); return { success: true, accounts }; } catch (error) { if (error.code === -32601) { console.warn('eth_accounts not supported on this node'); return { success: false, accounts: [], reason: 'unsupported' }; } throw error; } } ``` ## Related Methods - [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102) — Request wallet connection (browser wallets) - [`eth_getBalance`](./eth_getBalance) — Get account balance - [`eth_getTransactionCount`](./eth_getTransactionCount) — Get account nonce --- ## eth_blockNumber - Cronos RPC Method # eth_blockNumber Returns the number of the most recent block on Cronos. > **Why Cronos?** Build on the EVM-compatible Crypto.com blockchain with fast finality and deep Crypto.com ecosystem integration. ## When to Use This Method `eth_blockNumber` is fundamental for Cronos developers building DeFi and payment applications: - **Syncing Applications** — Keep your dApp in sync with the latest Cronos blockchain state - **Transaction Monitoring** — Verify confirmations by comparing block numbers - **Event Filtering** — Set the correct block range for querying logs on DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations - **Health Checks** — Monitor node connectivity and sync status ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `QUANTITY` | Hexadecimal string representing the current block number | **Return format**: `0x` prefixed hexadecimal (e.g., `0x5BAD55` = 6,008,149 in decimal) ## Request ```json { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } ``` ## Response ### Successful Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5BAD55" } ``` ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error" } } ``` ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }) }); const { result } = await response.json(); const blockNumber = parseInt(result, 16); console.log('Cronos block:', blockNumber); // Using ethers.js const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockNumber = await provider.getBlockNumber(); console.log('Cronos block:', blockNumber); ``` ```python def get_block_number(): response = requests.post( 'https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_blockNumber', 'params': [], 'id': 1 } ) result = response.json()['result'] return int(result, 16) block_number = get_block_number() print(f'Cronos block: {block_number}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) print(f'Cronos block: {w3.eth.block_number}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockNumber, err := client.BlockNumber(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Cronos block: %d\n", blockNumber) } ``` ## Common Use Cases ### 1. Block Confirmation Counter Monitor transaction confirmations on Cronos: ```javascript async function getConfirmations(provider, txHash) { const tx = await provider.getTransaction(txHash); if (!tx || !tx.blockNumber) return 0; const currentBlock = await provider.getBlockNumber(); return currentBlock - tx.blockNumber + 1; } // Wait for specific confirmations async function waitForConfirmations(provider, txHash, confirmations = 6) { let currentConfirmations = 0; while (currentConfirmations < confirmations) { currentConfirmations = await getConfirmations(provider, txHash); console.log(`Confirmations: ${currentConfirmations}/${confirmations}`); await new Promise(r => setTimeout(r, 2000)); } return true; } ``` ### 2. Event Log Filtering Query events from recent blocks on Cronos: ```javascript async function getRecentEvents(provider, contract, eventName, blockRange = 100) { const currentBlock = await provider.getBlockNumber(); const fromBlock = currentBlock - blockRange; const filter = contract.filters[eventName](); const events = await contract.queryFilter(filter, fromBlock, currentBlock); return events; } ``` ### 3. Node Health Monitoring Check if your Cronos node is synced: ```javascript async function checkNodeHealth(provider) { try { const blockNumber = await provider.getBlockNumber(); const block = await provider.getBlock(blockNumber); const now = Date.now() / 1000; const blockAge = now - block.timestamp; if (blockAge > 60) { console.warn(`Node may be behind. Last block was ${blockAge}s ago`); return false; } console.log(`Node healthy. Latest block: ${blockNumber}`); return true; } catch (error) { console.error('Node unreachable:', error); return false; } } ``` ## Performance Optimization ### Caching Strategy Cache block numbers to reduce API calls: ```javascript class BlockNumberCache { constructor(ttl = 2000) { this.cache = null; this.timestamp = 0; this.ttl = ttl; } async get(provider) { const now = Date.now(); if (this.cache && (now - this.timestamp) < this.ttl) { return this.cache; } this.cache = await provider.getBlockNumber(); this.timestamp = now; return this.cache; } invalidate() { this.cache = null; this.timestamp = 0; } } const blockCache = new BlockNumberCache(); ``` ### Batch Requests Combine with other calls for efficiency: ```javascript const batch = [ { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }, { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 }, { jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 } ]; const response = await fetch('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await response.json(); ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32603 | Internal error | Retry with exponential backoff | | -32005 | Rate limit exceeded | Implement rate limiting client-side | | -32000 | Execution reverted | Check node sync status | ```javascript async function safeGetBlockNumber(provider, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await provider.getBlockNumber(); } catch (error) { if (error.code === -32005) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } else if (i === maxRetries - 1) { throw error; } } } } ``` ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) — Get full block details by number - [`eth_getBlockByHash`](./eth_getBlockByHash) — Get block details by hash - [`eth_syncing`](./eth_syncing) — Check if node is still syncing --- ## eth_call - Cronos RPC Method # eth_call Executes a new message call immediately without creating a transaction on Cronos. Used for reading smart contract state. > **Why Cronos?** Build on the EVM-compatible Crypto.com blockchain with fast finality and deep Crypto.com ecosystem integration. ## Use Cases The `eth_call` method is essential for: - **Reading contract state** - Query view/pure functions - **Simulating transactions** - Test execution without gas costs - **DeFi integrations** - Check prices, balances, allowances for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations - **Complex queries** - Execute multi-step contract logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | 20-byte address executing the call | | `to` | `DATA` | Yes | 20-byte contract address | | `gas` | `QUANTITY` | No | Gas limit for the call | | `gasPrice` | `QUANTITY` | No | Gas price in wei | | `value` | `QUANTITY` | No | Value to send in wei | | `data` | `DATA` | Yes | Encoded function call data | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_call", "params": [ { "to": "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "data": "0x70a082310000000000000000000000005C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23" }, "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | The return value of the executed contract function | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000" } ``` ## Code Examples ```bash # Call ERC20 balanceOf function curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{ "to": "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "data": "0x70a082310000000000000000000000005C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23" }, "latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // ERC20 ABI for common functions const ERC20_ABI = [ "function balanceOf(address owner) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function totalSupply() view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)" ]; // Read ERC20 token balance async function getTokenBalance(tokenAddress, walletAddress) { const contract = new Contract(tokenAddress, ERC20_ABI, provider); const balance = await contract.balanceOf(walletAddress); const decimals = await contract.decimals(); const symbol = await contract.symbol(); return { raw: balance.toString(), formatted: (Number(balance) / Math.pow(10, decimals)).toFixed(4), symbol: symbol }; } // Direct eth_call async function directCall(to, data) { const result = await provider.call({ to, data }); return result; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) def get_erc20_balance(token_address, wallet_address): # balanceOf(address) selector function_signature = "balanceOf(address)" function_selector = w3.keccak(text=function_signature)[:4].hex() # Encode address parameter encoded_address = wallet_address[2:].lower().zfill(64) data = function_selector + encoded_address # Make the call result = w3.eth.call({ 'to': token_address, 'data': data }) return int(result.hex(), 16) balance = get_erc20_balance( '0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23', '0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23' ) print(f'Balance: {balance}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23") data := common.FromHex("0x70a082310000000000000000000000005C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23") msg := ethereum.CallMsg{ To: &contractAddress, Data: data, } result, err := client.CallContract(context.Background(), msg, nil) if err != nil { log.Fatal(err) } fmt.Printf("Result: 0x%x\n", result) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Contract function reverted | | -32602 | Invalid parameters | Invalid data encoding | | -32015 | VM execution error | Contract logic error | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas for transaction - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send actual transaction --- ## eth_chainId - Cronos RPC Method # eth_chainId Returns the chain ID used for transaction signing on Cronos. > **Why Cronos?** Build on the EVM-compatible Crypto.com blockchain with fast finality and deep Crypto.com ecosystem integration. ## Use Cases The `eth_chainId` method is essential for: - **Transaction signing** - Ensure transactions are signed for the correct network - **Network verification** - Confirm connection to the expected chain - **Multi-chain apps** - Handle different networks programmatically - **Wallet integration** - Validate network before transactions ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Chain ID in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1" } ``` ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const network = await provider.getNetwork(); console.log('Chain ID:', network.chainId); // Verify network before transaction async function verifyNetwork(expectedChainId) { const network = await provider.getNetwork(); if (network.chainId !== BigInt(expectedChainId)) { throw new Error(`Wrong network. Expected ${expectedChainId}, got ${network.chainId}`); } return true; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) chain_id = w3.eth.chain_id print(f'Chain ID: {chain_id}') # Verify network def verify_network(expected_chain_id): chain_id = w3.eth.chain_id if chain_id != expected_chain_id: raise ValueError(f'Wrong network. Expected {expected_chain_id}, got {chain_id}') return True ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } chainID, err := client.ChainID(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Chain ID: %d\n", chainID) } ``` ## Related Methods - [`net_version`](./net_version) - Get network version - [`eth_syncing`](./eth_syncing) - Check sync status --- ## eth_coinbase - Get Coinbase Address(Cronos) # eth_coinbase Returns the client coinbase address on Optimism Layer 2. ## Implementation Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_coinbase", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_coinbase', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0000000000000000000000000000000000000000" } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Optimism documentation](/docs/optimism).* --- ## eth_estimateGas - Cronos RPC Method # eth_estimateGas Estimates the gas necessary to execute a transaction on Cronos. > **Why Cronos?** Build on the EVM-compatible Crypto.com blockchain with fast finality and deep Crypto.com ecosystem integration. ## Use Cases The `eth_estimateGas` method is essential for: - **Transaction preparation** - Set appropriate gas limits - **Cost estimation** - Calculate transaction costs before sending - **Error detection** - Identify reverts before spending gas - **DeFi operations** - Estimate costs for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | Sender address | | `to` | `DATA` | No | Recipient address | | `gas` | `QUANTITY` | No | Gas limit | | `gasPrice` | `QUANTITY` | No | Gas price | | `value` | `QUANTITY` | No | Value in wei | | `data` | `DATA` | No | Transaction data | ## Request ```json { "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "to": "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "value": "0x1" }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Estimated gas amount in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5208" } ``` **Note**: `0x5208` = 21000 gas (standard ETH transfer) ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "to": "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "value": "0x1" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Estimate simple transfer async function estimateTransfer(to, value) { const gasEstimate = await provider.estimateGas({ to: to, value: parseEther(value) }); console.log('Estimated gas:', gasEstimate.toString()); return gasEstimate; } // Estimate contract call async function estimateContractCall(contract, method, args) { const gasEstimate = await contract[method].estimateGas(...args); console.log('Estimated gas:', gasEstimate.toString()); // Add 20% buffer for safety return gasEstimate * 120n / 100n; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) def estimate_transfer(to, value_in_ether): gas_estimate = w3.eth.estimate_gas({ 'to': to, 'value': w3.to_wei(value_in_ether, 'ether') }) print(f'Estimated gas: {gas_estimate}') return gas_estimate def estimate_contract_call(contract, method, args): func = getattr(contract.functions, method) gas_estimate = func(*args).estimate_gas() # Add 20% buffer return int(gas_estimate * 1.2) # Estimate simple transfer gas = estimate_transfer('0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23', 0.1) ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } toAddress := common.HexToAddress("0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23") msg := ethereum.CallMsg{ To: &toAddress, Value: big.NewInt(1000000000000000000), } gasLimit, err := client.EstimateGas(context.Background(), msg) if err != nil { log.Fatal(err) } fmt.Printf("Estimated gas: %d\n", gasLimit) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Transaction would fail | | -32602 | Invalid params | Invalid transaction parameters | **Tip**: If estimation fails, the transaction would likely revert if sent. ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_estimateL1Fee - Estimate L1 Data Fee # eth_estimateL1Fee Estimates the L1 data fee that would be paid for a given transaction on Optimism Layer 2. This is unique to Optimism's rollup architecture. ## When to Use This Method `eth_estimateL1Fee` is essential for: - **Complete Fee Estimation** - Calculate total transaction cost (L1 + L2 fees) - **Cost Optimization** - Compare different transaction approaches - **User Experience** - Show accurate fee estimates to users - **Rollup Economics** - Understand L1 data costs for your application ## Parameters 1. **Transaction Object** - `from` - Sender address (optional) - `to` - Destination address - `gas` - Gas limit (optional) - `gasPrice` - Gas price (optional) - `value` - Value in wei (optional) - `data` - Transaction data (optional) ## Implementation Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateL1Fee", "params": [{ "from": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", "to": "0x4200000000000000000000000000000000000006", "value": "0xde0b6b3a7640000", "data": "0xa9059cbb0000000000000000000000008ba1f109551bd432803012645hac136c0000000000000000000000000000000000000000000000000de0b6b3a7640000" }], "id": 1 }' ``` ```javascript // Estimate L1 fee for WETH transfer on Optimism const response = await fetch('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_estimateL1Fee', params: [{ from: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", to: "0x4200000000000000000000000000000000000006", // WETH on Optimism value: "0x0", data: "0xa9059cbb0000000000000000000000008ba1f109551bd432803012645hac136c0000000000000000000000000000000000000000000000000de0b6b3a7640000" }], id: 1 }) }); const data = await response.json(); const l1Fee = BigInt(data.result); console.log('L1 data fee:', Number(l1Fee) / 1e18, 'ETH'); // Calculate total transaction cost async function calculateTotalFee(txObject) { // Get L2 execution fee const l2Response = await fetch('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_estimateGas', params: [txObject], id: 2 }) }); const l2Data = await l2Response.json(); const l2Gas = BigInt(l2Data.result); // Get gas price const priceResponse = await fetch('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 3 }) }); const priceData = await priceResponse.json(); const gasPrice = BigInt(priceData.result); const l2Fee = l2Gas * gasPrice; const totalFee = l1Fee + l2Fee; return { l1Fee: Number(l1Fee) / 1e18, l2Fee: Number(l2Fee) / 1e18, totalFee: Number(totalFee) / 1e18, breakdown: { l1Percentage: (Number(l1Fee) / Number(totalFee) * 100).toFixed(2), l2Percentage: (Number(l2Fee) / Number(totalFee) * 100).toFixed(2) } }; } ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x2386f26fc10000" } ``` This represents the L1 data fee in wei. For a typical ERC-20 transfer, this might be around 0.001 ETH. ## Understanding Optimism Fee Structure ### Total Transaction Cost = L1 Data Fee + L2 Execution Fee ```javascript // Complete fee breakdown for Optimism transactions async function getOptimismFeeBreakdown(txObject) { // L1 data fee (varies based on calldata size and L1 gas price) const l1FeeResponse = await fetch('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_estimateL1Fee', params: [txObject], id: 1 }) }); const l1Fee = BigInt((await l1FeeResponse.json()).result); // L2 execution fee (much cheaper than Ethereum mainnet) const l2GasResponse = await fetch('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_estimateGas', params: [txObject], id: 2 }) }); const l2Gas = BigInt((await l2GasResponse.json()).result); const gasPriceResponse = await fetch('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 3 }) }); const gasPrice = BigInt((await gasPriceResponse.json()).result); const l2Fee = l2Gas * gasPrice; console.log('Optimism Fee Breakdown:'); console.log('L1 Data Fee:', Number(l1Fee) / 1e18, 'ETH'); console.log('L2 Execution Fee:', Number(l2Fee) / 1e18, 'ETH'); console.log('Total Fee:', Number(l1Fee + l2Fee) / 1e18, 'ETH'); console.log('L1 Fee %:', (Number(l1Fee) / Number(l1Fee + l2Fee) * 100).toFixed(1) + '%'); return { l1Fee: l1Fee, l2Fee: l2Fee, totalFee: l1Fee + l2Fee }; } ``` ## Optimizing L1 Fees ### Reduce Calldata Size ```javascript // Techniques to minimize L1 data fees class OptimismFeeOptimizer { // Use shorter function selectors when possible static optimizeCalldata(data) { // Remove unnecessary zero bytes // Use packed structs // Minimize string lengths return data; } // Batch multiple operations to amortize L1 costs static async batchOperations(operations) { // Bundle multiple calls into single transaction const batchCalldata = this.encodeBatch(operations); return { to: BATCH_CONTRACT_ADDRESS, data: batchCalldata }; } // Compare costs of different transaction approaches static async compareFees(txOptions) { const fees = []; for (const tx of txOptions) { const l1Fee = await this.estimateL1Fee(tx); fees.push({ transaction: tx, l1Fee: l1Fee, description: tx.description }); } return fees.sort((a, b) => Number(a.l1Fee - b.l1Fee)); } } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Optimism documentation](/docs/optimism).* --- ## eth_feeHistory - Cronos RPC Method # eth_feeHistory Returns historical gas information on Cronos for fee estimation. ## Use Cases - **Fee prediction** - Estimate future gas prices based on history - **Gas analytics** - Analyze fee trends over time - **Optimal timing** - Find best times for transactions on DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockCount` | `QUANTITY` | Yes | Number of blocks in the range | | `newestBlock` | `QUANTITY\|TAG` | Yes | Highest block of the range | | `rewardPercentiles` | `Array` | Yes | Percentiles to sample for priority fees | ## Request ```json { "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const feeHistory = await provider.send('eth_feeHistory', ['0xa', 'latest', [25, 50, 75]]); console.log('Base fees:', feeHistory.baseFeePerGas.map(f => formatUnits(f, 'gwei'))); console.log('Reward (25th percentile):', feeHistory.reward.map(r => formatUnits(r[0], 'gwei'))); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) fee_history = w3.eth.fee_history(10, 'latest', [25, 50, 75]) print(f'Base fees: {[w3.from_wei(f, "gwei") for f in fee_history["baseFeePerGas"]]}') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee --- ## eth_gasPrice - Cronos RPC Method # eth_gasPrice Returns the current gas price on Cronos in wei. > **Why Cronos?** Build on the EVM-compatible Crypto.com blockchain with fast finality and deep Crypto.com ecosystem integration. ## Use Cases The `eth_gasPrice` method is essential for: - **Transaction pricing** - Set appropriate gas prices - **Cost estimation** - Calculate transaction costs before sending - **Gas monitoring** - Track network congestion - **DeFi operations** - Optimize costs for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Current gas price in wei (hexadecimal) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x3b9aca00" } ``` **Note**: `0x3b9aca00` = 1 Gwei (1,000,000,000 wei) ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); const gasPrice = feeData.gasPrice; console.log('Gas Price:', formatUnits(gasPrice, 'gwei'), 'Gwei'); // Calculate transaction cost async function estimateTransactionCost(gasLimit) { const feeData = await provider.getFeeData(); const cost = feeData.gasPrice * BigInt(gasLimit); return formatUnits(cost, 'ether'); } const cost = await estimateTransactionCost(21000); console.log('Transfer cost:', cost, 'ETH'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) gas_price = w3.eth.gas_price print(f'Gas Price: {w3.from_wei(gas_price, "gwei")} Gwei') # Calculate transaction cost def estimate_transaction_cost(gas_limit): gas_price = w3.eth.gas_price cost = gas_price * gas_limit return w3.from_wei(cost, 'ether') cost = estimate_transaction_cost(21000) print(f'Transfer cost: {cost} ETH') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } gasPrice, err := client.SuggestGasPrice(context.Background()) if err != nil { log.Fatal(err) } // Convert to Gwei gwei := new(big.Float).Quo( new(big.Float).SetInt(gasPrice), big.NewFloat(1e9), ) fmt.Printf("Gas Price: %f Gwei\n", gwei) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32603 | Internal error | Node error | ## Related Methods - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee (EIP-1559) - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas needed --- ## eth_getBalance - Cronos RPC Method # eth_getBalance Returns the balance of a given address on Cronos. > **Why Cronos?** Build on the EVM-compatible Crypto.com blockchain with fast finality and deep Crypto.com ecosystem integration. ## Use Cases The `eth_getBalance` method is essential for: - **Wallet applications** - Display user balances - **Transaction validation** - Check if account has sufficient funds - **DeFi applications** - Monitor collateral and liquidity for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations - **Account monitoring** - Track balance changes over time ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address to check balance for | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Integer of the current balance in wei (hexadecimal) | **Note**: 1 native token = 10^18 wei. Convert using `balance / 10^18`. ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1a055690d9db80000" } ``` ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23'; const balanceWei = await provider.getBalance(address); const balance = formatEther(balanceWei); console.log(`Balance: ${balance}`); // Get balance at specific block const historicalBalance = await provider.getBalance(address, 1000000); console.log(`Historical balance: ${formatEther(historicalBalance)}`); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23' balance_wei = w3.eth.get_balance(address) balance = w3.from_wei(balance_wei, 'ether') print(f'Balance: {balance}') # Get balance at specific block historical_balance = w3.eth.get_balance(address, block_identifier=1000000) print(f'Historical balance: {w3.from_wei(historical_balance, "ether")}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23") balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } // Convert to ether fbalance := new(big.Float).SetInt(balance) ethValue := new(big.Float).Quo(fbalance, big.NewFloat(1e18)) fmt.Printf("Balance: %f\n", ethValue) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid address format or block parameter | | -32000 | Execution error | Node execution error | ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_getTransactionCount`](./eth_getTransactionCount) - Get account nonce --- ## eth_getBlockByHash - Cronos RPC Method # eth_getBlockByHash Returns information about a block by hash on Cronos. > **Why Cronos?** Build on the EVM-compatible Crypto.com blockchain with fast finality and deep Crypto.com ecosystem integration. ## Use Cases The `eth_getBlockByHash` method is essential for: - **Block verification** - Verify block data using its unique hash - **Chain reorganization handling** - Track blocks during reorgs - **Cross-chain bridges** - Verify block finality for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations - **Deterministic queries** - Get consistent block data regardless of chain state ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0xc8a64cd89ea7954a5f8064bf7c5fb907226e1dbb66a05d6043f7052191686f06", false ], "id": 1 } ``` ## Returns Returns the same block object as `eth_getBlockByNumber`, or `null` if no block is found. | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used | | `transactions` | `Array` | Transaction objects or hashes | ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0xc8a64cd89ea7954a5f8064bf7c5fb907226e1dbb66a05d6043f7052191686f06", false ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0xc8a64cd89ea7954a5f8064bf7c5fb907226e1dbb66a05d6043f7052191686f06'; const block = await provider.getBlock(blockHash); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) block_hash = '0xc8a64cd89ea7954a5f8064bf7c5fb907226e1dbb66a05d6043f7052191686f06' block = w3.eth.get_block(block_hash) print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockHash := common.HexToHash("0xc8a64cd89ea7954a5f8064bf7c5fb907226e1dbb66a05d6043f7052191686f06") block, err := client.BlockByHash(context.Background(), blockHash) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block hash format | | -32000 | Block not found | Block with this hash does not exist | ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) - Get block by number - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number --- ## eth_getBlockByNumber - Cronos RPC Method # eth_getBlockByNumber Returns information about a block by block number on Cronos. > **Why Cronos?** Build on the EVM-compatible Crypto.com blockchain with fast finality and deep Crypto.com ecosystem integration. ## Use Cases The `eth_getBlockByNumber` method is essential for: - **Block explorers** - Display complete block information - **Transaction indexers** - Process all transactions in a block - **Analytics platforms** - Analyze blockchain data for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations - **Timestamp verification** - Get block timestamps for time-based logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used by all transactions | | `gasLimit` | `QUANTITY` | Maximum gas allowed in block | | `transactions` | `Array` | Array of transaction objects or hashes | | `baseFeePerGas` | `QUANTITY` | Base fee per gas (EIP-1559) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": { "number": "0x5BAD55", "hash": "0xc8a64cd89ea7954a5f8064bf7c5fb907226e1dbb66a05d6043f7052191686f06", "parentHash": "0x...", "timestamp": "0x64d8f6d0", "gasUsed": "0x1234", "gasLimit": "0x1c9c380", "transactions": [], "baseFeePerGas": "0x5f5e100" } } ``` ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Get latest block const block = await provider.getBlock('latest'); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); console.log('Transactions:', block.transactions.length); // Get block with full transactions const blockWithTxs = await provider.getBlock('latest', true); for (const tx of blockWithTxs.prefetchedTransactions) { console.log('Transaction:', tx.hash); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) # Get latest block block = w3.eth.get_block('latest') print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') print(f'Transactions: {len(block.transactions)}') # Get block with full transactions block_full = w3.eth.get_block('latest', full_transactions=True) for tx in block_full.transactions: print(f'Transaction: {tx.hash.hex()}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } // Get latest block block, err := client.BlockByNumber(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) fmt.Printf("Timestamp: %d\n", block.Time()) fmt.Printf("Transactions: %d\n", len(block.Transactions())) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block number or parameter format | | -32000 | Block not found | Block does not exist | ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number - [`eth_getBlockByHash`](./eth_getBlockByHash) - Get block by hash - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_getCode - Cronos RPC Method # eth_getCode Returns the bytecode at a given address on Cronos. > **Why Cronos?** Build on the EVM-compatible Crypto.com blockchain with fast finality and deep Crypto.com ecosystem integration. ## Use Cases The `eth_getCode` method is essential for: - **Contract verification** - Check if address is a contract - **Security analysis** - Verify deployed bytecode matches expected - **DeFi integrations** - Validate contracts before interactions - **Protocol analysis** - Analyze contract deployments for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Contract bytecode or `0x` if EOA | ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23'; const code = await provider.getCode(address); if (code === '0x') { console.log('Address is an EOA (externally owned account)'); } else { console.log('Address is a contract'); console.log('Bytecode length:', code.length); } // Check if address is a contract async function isContract(address) { const code = await provider.getCode(address); return code !== '0x'; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23' code = w3.eth.get_code(address) if code == b'': print('Address is an EOA') else: print('Address is a contract') print(f'Bytecode length: {len(code.hex())}') # Check if address is a contract def is_contract(address): code = w3.eth.get_code(address) return code != b'' ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23") code, err := client.CodeAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } if len(code) == 0 { fmt.Println("Address is an EOA") } else { fmt.Printf("Contract bytecode length: %d\n", len(code)) } } ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_getStorageAt`](./eth_getStorageAt) - Get contract storage --- ## eth_getFilterChanges - Cronos RPC Method # eth_getFilterChanges Polling method for a filter on Cronos, returns an array of logs since last poll. ## Use Cases - **Event streaming** - Get new events incrementally - **Real-time monitoring** - Track contract activity for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations - **Efficient indexing** - Process only new events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Poll loop async function pollFilter(filterId, interval = 2000) { while (true) { const changes = await provider.send('eth_getFilterChanges', [filterId]); if (changes.length > 0) { console.log('New events:', changes); } await new Promise(r => setTimeout(r, interval)); } } ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter --- ## eth_getFilterLogs - Cronos RPC Method # eth_getFilterLogs Returns an array of all logs matching filter with given ID on Cronos. ## Use Cases - **Historical queries** - Get all matching logs for a filter - **Full event history** - Retrieve complete event data for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const logs = await provider.send('eth_getFilterLogs', [filterId]); console.log('All matching logs:', logs.length); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_getLogs - Cronos RPC Method # eth_getLogs Returns an array of all logs matching a given filter object on Cronos. > **Why Cronos?** Build on the EVM-compatible Crypto.com blockchain with fast finality and deep Crypto.com ecosystem integration. ## Use Cases The `eth_getLogs` method is essential for: - **Event indexing** - Track contract events for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations - **Token transfers** - Monitor ERC20/ERC721 transfers - **DeFi analytics** - Track swaps, liquidity events, and more - **Notification systems** - Alert on specific on-chain events ## Cronos Rate Limits :::info Block Range Limit On Cronos, `eth_getLogs` queries are subject to a **maximum block range of 500 blocks**. This means the difference between `fromBlock` and `toBlock` cannot exceed 500 blocks per request. Additionally, each query can return a **maximum of 10,000 log entries**. ::: For querying larger block ranges, split your requests into smaller batches: ```javascript // Example: Query in 500-block batches const BATCH_SIZE = 500; let fromBlock = startBlock; while (fromBlock <= endBlock) { const toBlock = Math.min(fromBlock + BATCH_SIZE - 1, endBlock); const logs = await provider.getLogs({ fromBlock, toBlock, ...filter }); // Process logs fromBlock = toBlock + 1; } ``` ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block (default: `"latest"`) | | `toBlock` | `QUANTITY\|TAG` | No | Ending block (default: `"latest"`) | | `address` | `DATA\|Array` | No | Contract address(es) to filter | | `topics` | `Array` | No | Array of topic filters | | `blockHash` | `DATA` | No | Filter single block by hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns Array of log objects: | Field | Type | Description | |-------|------|-------------| | `address` | `DATA` | Contract that emitted the log | | `topics` | `Array` | Array of indexed topics | | `data` | `DATA` | Non-indexed log data | | `blockNumber` | `QUANTITY` | Block number | | `transactionHash` | `DATA` | Transaction hash | | `logIndex` | `QUANTITY` | Log index in block | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": [{ "address": "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."], "data": "0x...", "blockNumber": "0x5BAD55", "transactionHash": "0x...", "logIndex": "0x0" }] } ``` ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Get Transfer events const TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'; async function getTransferEvents(tokenAddress, fromBlock, toBlock) { const logs = await provider.getLogs({ address: tokenAddress, topics: [TRANSFER_TOPIC], fromBlock: fromBlock, toBlock: toBlock }); return logs.map(log => ({ from: '0x' + log.topics[1].slice(26), to: '0x' + log.topics[2].slice(26), blockNumber: log.blockNumber, transactionHash: log.transactionHash })); } const events = await getTransferEvents( '0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23', 'latest', 'latest' ); console.log('Transfer events:', events); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' def get_transfer_events(token_address, from_block, to_block): logs = w3.eth.get_logs({ 'address': token_address, 'topics': [TRANSFER_TOPIC], 'fromBlock': from_block, 'toBlock': to_block }) events = [] for log in logs: events.append({ 'from': '0x' + log['topics'][1].hex()[26:], 'to': '0x' + log['topics'][2].hex()[26:], 'block': log['blockNumber'], 'tx': log['transactionHash'].hex() }) return events events = get_transfer_events( '0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23', 'latest', 'latest' ) print(f'Found {len(events)} transfer events') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23") transferTopic := common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef") query := ethereum.FilterQuery{ FromBlock: big.NewInt(0), ToBlock: nil, Addresses: []common.Address{contractAddress}, Topics: [][]common.Hash, } logs, err := client.FilterLogs(context.Background(), query) if err != nil { log.Fatal(err) } fmt.Printf("Found %d events\n", len(logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32005 | Query returned more than 10000 results | Reduce block range | | -32602 | Invalid params | Invalid filter parameters | ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create a filter for logs - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for new logs --- ## eth_getStorageAt - Cronos RPC Method # eth_getStorageAt Returns the value from a storage position at a given address on Cronos. ## Use Cases - **Contract analysis** - Read raw storage values - **State verification** - Verify contract state - **Security auditing** - Analyze storage layout for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations - **Protocol monitoring** - Track state changes ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte contract address | | `position` | `QUANTITY` | Yes | Storage slot position | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "0x0", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "0x0", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23'; const slot = 0; const storage = await provider.getStorage(address, slot); console.log('Storage at slot 0:', storage); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23' storage = w3.eth.get_storage_at(address, 0) print(f'Storage at slot 0: {storage.hex()}') ``` ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_call`](./eth_call) - Call contract functions --- ## eth_getTransactionByHash - Cronos RPC Method # eth_getTransactionByHash Returns the information about a transaction by transaction hash on Cronos. > **Why Cronos?** Build on the EVM-compatible Crypto.com blockchain with fast finality and deep Crypto.com ecosystem integration. ## Use Cases The `eth_getTransactionByHash` method is essential for: - **Transaction tracking** - Get details of pending or confirmed transactions - **Payment verification** - Verify transaction parameters - **Debugging** - Analyze transaction data for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations - **Block explorers** - Display transaction information ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x159952dbecdbb7c17e962de632fe2560cddcdb371b4d98f37015e3682669f39c"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `hash` | `DATA` | Transaction hash | | `from` | `DATA` | Sender address | | `to` | `DATA` | Recipient address | | `value` | `QUANTITY` | Value in wei | | `gas` | `QUANTITY` | Gas provided | | `gasPrice` | `QUANTITY` | Gas price in wei | | `input` | `DATA` | Transaction input data | | `nonce` | `QUANTITY` | Sender's nonce | | `blockHash` | `DATA` | Block hash (null if pending) | | `blockNumber` | `QUANTITY` | Block number (null if pending) | ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x159952dbecdbb7c17e962de632fe2560cddcdb371b4d98f37015e3682669f39c"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x159952dbecdbb7c17e962de632fe2560cddcdb371b4d98f37015e3682669f39c'; const tx = await provider.getTransaction(txHash); if (tx) { console.log('From:', tx.from); console.log('To:', tx.to); console.log('Value:', formatEther(tx.value)); console.log('Block:', tx.blockNumber); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x159952dbecdbb7c17e962de632fe2560cddcdb371b4d98f37015e3682669f39c' tx = w3.eth.get_transaction(tx_hash) if tx: print(f'From: {tx["from"]}') print(f'To: {tx["to"]}') print(f'Value: {w3.from_wei(tx["value"], "ether")}') print(f'Block: {tx["blockNumber"]}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x159952dbecdbb7c17e962de632fe2560cddcdb371b4d98f37015e3682669f39c") tx, isPending, err := client.TransactionByHash(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Pending: %v\n", isPending) fmt.Printf("Value: %s\n", tx.Value().String()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash format | ## Related Methods - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction receipt - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionCount - Cronos RPC Method # eth_getTransactionCount Returns the number of transactions sent from an address on Cronos (the nonce). ## Use Cases - **Transaction building** - Get correct nonce for new transactions - **Account analysis** - Count total outgoing transactions - **Nonce management** - Handle pending transaction queues - **Wallet operations** - Prepare transactions for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag (`pending` for next nonce) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const address = '0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23'; const nonce = await provider.getTransactionCount(address); console.log('Nonce:', nonce); // Get pending nonce for new transaction const pendingNonce = await provider.getTransactionCount(address, 'pending'); console.log('Next nonce:', pendingNonce); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) address = '0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23' nonce = w3.eth.get_transaction_count(address) print(f'Nonce: {nonce}') # Get pending nonce pending_nonce = w3.eth.get_transaction_count(address, 'pending') print(f'Next nonce: {pending_nonce}') ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionReceipt - Cronos RPC Method # eth_getTransactionReceipt Returns the receipt of a transaction by transaction hash on Cronos. Receipt is only available for mined transactions. > **Why Cronos?** Build on the EVM-compatible Crypto.com blockchain with fast finality and deep Crypto.com ecosystem integration. ## Use Cases The `eth_getTransactionReceipt` method is essential for: - **Transaction confirmation** - Verify transaction was mined successfully - **Gas analysis** - Check actual gas used vs estimated - **Event parsing** - Read emitted events from logs - **Status verification** - Confirm success/failure for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x159952dbecdbb7c17e962de632fe2560cddcdb371b4d98f37015e3682669f39c"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `status` | `QUANTITY` | `1` (success) or `0` (failure) | | `transactionHash` | `DATA` | Transaction hash | | `blockHash` | `DATA` | Block hash | | `blockNumber` | `QUANTITY` | Block number | | `gasUsed` | `QUANTITY` | Gas used by this transaction | | `cumulativeGasUsed` | `QUANTITY` | Total gas used in block up to this tx | | `logs` | `Array` | Array of log objects | | `contractAddress` | `DATA` | Created contract address (if deployment) | ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x159952dbecdbb7c17e962de632fe2560cddcdb371b4d98f37015e3682669f39c"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x159952dbecdbb7c17e962de632fe2560cddcdb371b4d98f37015e3682669f39c'; const receipt = await provider.getTransactionReceipt(txHash); if (receipt) { console.log('Status:', receipt.status === 1 ? 'Success' : 'Failed'); console.log('Gas Used:', receipt.gasUsed.toString()); console.log('Block:', receipt.blockNumber); console.log('Logs:', receipt.logs.length); // Parse specific events for (const log of receipt.logs) { console.log('Event from:', log.address); } } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x159952dbecdbb7c17e962de632fe2560cddcdb371b4d98f37015e3682669f39c' receipt = w3.eth.get_transaction_receipt(tx_hash) if receipt: status = 'Success' if receipt['status'] == 1 else 'Failed' print(f'Status: {status}') print(f'Gas Used: {receipt["gasUsed"]}') print(f'Block: {receipt["blockNumber"]}') print(f'Logs: {len(receipt["logs"])}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x159952dbecdbb7c17e962de632fe2560cddcdb371b4d98f37015e3682669f39c") receipt, err := client.TransactionReceipt(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Status: %d\n", receipt.Status) fmt.Printf("Gas Used: %d\n", receipt.GasUsed) fmt.Printf("Logs: %d\n", len(receipt.Logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash | **Note**: Returns `null` if transaction is not yet mined. ## Related Methods - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details - [`eth_getLogs`](./eth_getLogs) - Query logs by filter --- ## eth_hashrate - Get Network Hashrate # eth_hashrate Returns the number of hashes per second that the node is mining with on Optimism Layer 2. Always returns 0 as Optimism uses a sequencer model. ## Implementation Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_hashrate", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_hashrate', params: [], id: 1 }) }); const data = await response.json(); console.log('Hashrate:', parseInt(data.result, 16)); // Always 0 on Optimism ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0" } ``` **Note:** Optimism uses a sequencer model for block production, not proof-of-work mining, so hashrate is always 0. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Optimism documentation](/docs/optimism).* --- ## eth_maxPriorityFeePerGas - Cronos RPC Method # eth_maxPriorityFeePerGas Returns the current recommended priority fee per gas on Cronos for EIP-1559 transactions. ## Use Cases - **EIP-1559 transactions** - Set appropriate priority fees - **Transaction acceleration** - Calculate tips for faster inclusion - **Gas optimization** - Balance speed vs cost for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); console.log('Max Priority Fee:', formatUnits(feeData.maxPriorityFeePerGas, 'gwei'), 'Gwei'); console.log('Max Fee Per Gas:', formatUnits(feeData.maxFeePerGas, 'gwei'), 'Gwei'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) priority_fee = w3.eth.max_priority_fee print(f'Max Priority Fee: {w3.from_wei(priority_fee, "gwei")} Gwei') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get legacy gas price - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data --- ## eth_mining - Check Mining Status # eth_mining Returns true if client is actively mining new blocks on Optimism Layer 2. Always returns false on Optimism as it uses a sequencer model. ## Implementation Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_mining', params: [], id: 1 }) }); const data = await response.json(); console.log('Mining status:', data.result); // Always false on Optimism ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": false } ``` **Note:** Optimism uses a sequencer model instead of traditional mining, so this always returns false. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Optimism documentation](/docs/optimism).* --- ## eth_newBlockFilter - Cronos RPC Method # eth_newBlockFilter Creates a filter on Cronos to notify when a new block arrives. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newBlockFilter', []); // Poll for new blocks const newBlocks = await provider.send('eth_getFilterChanges', [filterId]); console.log('New block hashes:', newBlocks); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_blockNumber`](./eth_blockNumber) - Get current block --- ## eth_newFilter - Cronos RPC Method # eth_newFilter Creates a filter object on Cronos to notify when state changes (logs). ## Use Cases - **Event monitoring** - Subscribe to contract events - **Real-time updates** - Track events for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations - **Indexing** - Build event indexes incrementally ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block | | `toBlock` | `QUANTITY\|TAG` | No | Ending block | | `address` | `DATA\|Array` | No | Contract address(es) | | `topics` | `Array` | No | Topic filters | ## Request ```json { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Create filter const filterId = await provider.send('eth_newFilter', [{ fromBlock: 'latest', address: '0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23', topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'] }]); // Poll for changes const changes = await provider.send('eth_getFilterChanges', [filterId]); console.log('New events:', changes); // Cleanup await provider.send('eth_uninstallFilter', [filterId]); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for changes - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_newPendingTransactionFilter - Cronos RPC Method # eth_newPendingTransactionFilter Creates a filter on Cronos to notify when new pending transactions arrive. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newPendingTransactionFilter', []); // Poll for pending transactions const pendingTxs = await provider.send('eth_getFilterChanges', [filterId]); console.log('Pending transaction hashes:', pendingTxs); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_protocolVersion - Get Protocol Version(Cronos) # eth_protocolVersion Returns the current ethereum protocol version used by Optimism Layer 2. ## Implementation Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_protocolVersion", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_protocolVersion', params: [], id: 1 }) }); const data = await response.json(); console.log('Protocol version:', parseInt(data.result, 16)); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x41" } ``` This represents protocol version 65 (0x41 in hex), indicating Ethereum London fork compatibility. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Optimism documentation](/docs/optimism).* --- ## eth_sendRawTransaction - Cronos RPC Method # eth_sendRawTransaction Submits a pre-signed transaction for broadcast to Cronos. > **Why Cronos?** Build on the EVM-compatible Crypto.com blockchain with fast finality and deep Crypto.com ecosystem integration. ## Use Cases The `eth_sendRawTransaction` method is essential for: - **Broadcasting transactions** - Submit signed transactions to the network - **Wallet operations** - Send native tokens and interact with contracts - **DeFi operations** - Execute swaps, provide liquidity for DeFi protocols, NFT marketplaces, and Crypto.com ecosystem integrations - **Batch operations** - Submit multiple transactions efficiently ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `signedTransactionData` | `DATA` | Yes | The signed transaction data (RLP encoded) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | 32-byte transaction hash | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c808504a817c80082520894..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const wallet = new Wallet('YOUR_PRIVATE_KEY', provider); // Send native tokens async function sendTransaction(to, value) { const tx = await wallet.sendTransaction({ to: to, value: parseEther(value) }); console.log('Transaction hash:', tx.hash); // Wait for confirmation const receipt = await tx.wait(); console.log('Confirmed in block:', receipt.blockNumber); return receipt; } // Send to contract async function sendContractTransaction(contract, method, args, value = '0') { const tx = await contract[method](...args, { value: parseEther(value) }); return await tx.wait(); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) def send_transaction(private_key, to, value_in_ether): account = w3.eth.account.from_key(private_key) # Build transaction tx = { 'nonce': w3.eth.get_transaction_count(account.address), 'to': to, 'value': w3.to_wei(value_in_ether, 'ether'), 'gas': 21000, 'gasPrice': w3.eth.gas_price, 'chainId': w3.eth.chain_id } # Sign transaction signed_tx = account.sign_transaction(tx) # Send transaction tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) print(f'Transaction hash: {tx_hash.hex()}') # Wait for confirmation receipt = w3.eth.wait_for_transaction_receipt(tx_hash) print(f'Confirmed in block: {receipt["blockNumber"]}') return receipt ``` ```go package main "context" "crypto/ecdsa" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY") if err != nil { log.Fatal(err) } publicKey := privateKey.Public() publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey) fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA) nonce, _ := client.PendingNonceAt(context.Background(), fromAddress) value := big.NewInt(1000000000000000000) gasLimit := uint64(21000) gasPrice, _ := client.SuggestGasPrice(context.Background()) toAddress := common.HexToAddress("0x5C7F8A570d578ED84E63fdFA7b1eE72dEae1AE23") tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil) chainID, _ := client.NetworkID(context.Background()) signedTx, _ := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey) err = client.SendTransaction(context.Background(), signedTx) if err != nil { log.Fatal(err) } fmt.Printf("Transaction hash: %s\n", signedTx.Hash().Hex()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Nonce too low | Transaction nonce already used | | -32000 | Insufficient funds | Account has insufficient balance | | -32000 | Gas too low | Gas limit insufficient | | -32000 | Replacement underpriced | Gas price too low for replacement | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas required - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction result --- ## eth_sendTransaction - Send Transaction(Cronos) # eth_sendTransaction > **Important**: Dwellir's shared Cronos endpoints do not manage user private keys. JSON-RPC nodes cannot unlock your account, so `eth_sendTransaction` calls will fail. Sign transactions client-side and broadcast them with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Why this method is disabled on shared nodes - [`eth_sendTransaction` requires the node to hold and unlock the `from` account's private key](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction). - Managed infrastructure providers disable it for security reasons rather than storing customer keys on shared servers (for example, [Infura explicitly blocks the method on shared endpoints](https://docs.infura.io/api/networks/ethereum/json-rpc-methods/eth_sendtransaction)). ## Recommended workflow 1. Build the raw transaction locally with your wallet or SDK. 2. Sign the payload client-side (hardware wallet, custodial service, or library). 3. Submit the signed hex string with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Example response from the shared endpoint ```bash curl -s -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"0x0000000000000000000000000000000000000000"}],"id":1}' ``` ```json {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"unknown account"}} ``` Need help? Contact our [support team](mailto:support@dwellir.com) or use the dedicated [`eth_sendRawTransaction`](./eth_sendRawTransaction) guide. --- ## eth_signTransaction - Sign Transaction(Cronos) # eth_signTransaction Signs a transaction that can be submitted to the network at a later time using eth_sendRawTransaction on Optimism Layer 2. ## Parameters 1. **Transaction Object** - `from` - Sender address - `to` - Destination address - `gas` - Gas limit - `gasPrice` - Gas price - `value` - Value in wei - `data` - Transaction data ## Implementation Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_signTransaction", "params": [{ "from": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", "to": "0x8ba1f109551bD432803012645Hac136c", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a" }], "id": 1 }' ``` ```javascript const response = await fetch('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_signTransaction', params: [{ from: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb", to: "0x8ba1f109551bD432803012645Hac136c", gas: "0x76c0", gasPrice: "0x9184e72a000", value: "0x9184e72a" }], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0xf86c808504a817c800825208943535353535353535353535353535353535353535880de0b6b3a76400008025a04f4c17305743700648bc4f6cd3038ec6f6af0df73e31757007b7f59df7bee88da07e1941b264348e80c78c4027afc65a87b0a5e43b86742b8ca0823584c6788fd0" } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Optimism documentation](/docs/optimism).* --- ## eth_syncing - Cronos RPC Method # eth_syncing Returns syncing status of Cronos node. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 } ``` ## Returns Returns `false` if not syncing, or an object with sync status. ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const syncing = await provider.send('eth_syncing', []); if (syncing === false) { console.log('Node is fully synced'); } else { console.log('Syncing:', syncing); } ``` ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get current block - [`net_peerCount`](./net_peerCount) - Get peer count --- ## eth_uninstallFilter - Cronos RPC Method # eth_uninstallFilter Uninstalls a filter on Cronos. Should be called when no longer needed. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID to uninstall | ## Request ```json { "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if filter was found and uninstalled | ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const success = await provider.send('eth_uninstallFilter', [filterId]); console.log('Filter removed:', success); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter --- ## Cronos — EVM Chain for the Crypto.com Ecosystem ## Why Build on Cronos? Cronos is an EVM-compatible Layer 1 built with the Cosmos SDK and Tendermint consensus. It powers the Crypto.com ecosystem while offering a familiar developer experience for Solidity teams. ### ⚡ Production-Ready Performance - ~5–6 second block times with immediate probabilistic finality - Scales via IBC interoperability with the broader Cosmos network - Optimized for low fees (fractions of a cent per transaction) ### 🌐 Strong Ecosystem & Liquidity - Native integration with Crypto.com App and Exchange - 1M+ unique addresses and $100M+ TVL across DeFi protocols - Bridges to Ethereum, Cosmos Hub, and other chains via Gravity Bridge & IBC ### 🧰 Developer-Friendly Tooling - Full Ethereum JSON-RPC surface, compatible with Hardhat, Foundry, Truffle - EVM bytecode equivalence—deploy existing Solidity contracts without changes - Rich tooling for gaming (Cronos Play), DeFi, and NFTs ## Quick Start Connect to Cronos with Dwellir's globally distributed infrastructure: :::info Network Details - **Mainnet Chain ID**: 25 (0x19) - **Testnet Chain ID**: 338 (0x152) - **Native Token**: CRO - **Average Block Time**: ~5.6 seconds ::: ## Installation & Setup ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const { chainId } = await provider.getNetwork(); console.log('Cronos chain ID:', chainId); // 25n const block = await provider.getBlock('latest'); console.log('Latest block:', block.number); ``` ```javascript const web3 = new Web3('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const gasPrice = await web3.eth.getGasPrice(); console.log('Cronos gas price (wei):', gasPrice); const balance = await web3.eth.getBalance('0x000000000000000000000000000000000000dead'); console.log('Balance:', web3.utils.fromWei(balance, 'ether'), 'CRO'); ``` ```typescript const cronos = defineChain({ id: 25, name: 'Cronos', nativeCurrency: { name: 'Cronos', symbol: 'CRO', decimals: 18 }, rpcUrls: { default: { http: ['https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'] } } }); const client = createPublicClient({ chain: cronos, transport: http() }); const gas = await client.estimateGas({ account: '0x000000000000000000000000000000000000dead', to: '0x0000000000000000000000000000000000000000', value: 0n }); console.log('Estimated gas:', gas); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY')) assert w3.is_connected() print('Chain ID:', w3.eth.chain_id) # 25 tx_count = w3.eth.get_transaction_count('0x0000000000000000000000000000000000000000') print('Nonce:', tx_count) ``` ## Available JSON-RPC Methods Cronos exposes the standard Ethereum JSON-RPC interface. Method deep-dives will be added soon; use the dropdown for existing guides and compatibility hints. ## Network Architecture - **Consensus**: Proof-of-Authority (PoA) variant built on Tendermint for fast finality - **IBC Enabled**: Interoperates with Cosmos Hub, Crypto.org, and other IBC networks - **Gravity Bridge**: Facilitates asset transfers to/from Ethereum and other ERC-20 ecosystems - **Cronos Play**: Middleware stack for game developers integrating Unity, Unreal, and C++ SDKs ## Bridging Assets - **Cronos Bridge**: [bridge.cronos.org](https://cronos.org/bridge/) for ETH ↔ CRO transfers - **Gravity Bridge**: Move ERC-20 tokens from Ethereum without centralized custody - **IBC Transfers**: Swap assets between Cronos and Cosmos chains using IBC-enabled wallets like Keplr ## Best Practices 1. **Gas Strategy** — Fetch `eth_feeHistory` or `eth_gasPrice` to adapt to variable network load. 2. **Unit Conventions** — Gas is paid in CRO (18 decimals). Use `web3.utils.toWei` / viem helpers to avoid rounding errors. 3. **Monitor Finality** — Wait for a few confirmations (3–5 blocks) before acting on large-value transfers. 4. **Use IBC Safely** — Confirm counterparty channel IDs when transferring assets cross-chain. ## Tooling & Resources - [Cronos Documentation](https://docs.cronos.org/) - [Cronoscan Explorer](https://explorer.cronos.org/) - [Testnet Explorer](https://explorer.cronos.org/testnet) - [Crypto.com Developer Hub](https://crypto.com/developer) - [Get a Dwellir API Key](https://dashboard.dwellir.com/register) Start building performant, EVM-compatible apps on Cronos with Dwellir's resilient infrastructure. --- ## net_listening - Cronos RPC Method # net_listening Returns `true` if client is actively listening for network connections on Cronos. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if listening | ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const listening = await provider.send('net_listening', []); console.log('Node listening:', listening); ``` ## Related Methods - [`net_peerCount`](./net_peerCount) - Get peer count --- ## net_peerCount - Cronos RPC Method # net_peerCount Returns number of peers currently connected to Cronos client. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Number of connected peers (hexadecimal) | ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const peerCount = await provider.send('net_peerCount', []); console.log('Peer count:', parseInt(peerCount, 16)); ``` ## Related Methods - [`net_listening`](./net_listening) - Check if listening --- ## net_version - Cronos RPC Method # net_version Returns the current network ID on Cronos. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Network ID as a string | ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const networkId = await provider.send('net_version', []); console.log('Network ID:', networkId); ``` ## Related Methods - [`eth_chainId`](./eth_chainId) - Get chain ID --- ## rollup_gasPrices - Get Rollup Gas Prices # rollup_gasPrices Returns the current gas prices for both L1 data submission and L2 execution on Optimism Layer 2. ## When to Use This Method `rollup_gasPrices` is essential for: - **Fee Estimation** - Get both L1 and L2 gas price components - **Cost Analysis** - Understand the breakdown of rollup fees - **Dynamic Pricing** - Adjust transaction timing based on gas costs - **L1/L2 Cost Comparison** - Compare relative costs of L1 vs L2 operations ## Parameters None. This method takes no parameters. ## Implementation Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "rollup_gasPrices", "params": [], "id": 1 }' ``` ```javascript // Get current rollup gas prices on Optimism const response = await fetch('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'rollup_gasPrices', params: [], id: 1 }) }); const data = await response.json(); const gasPrices = data.result; console.log('Optimism Gas Prices:'); console.log('L1 Gas Price:', parseInt(gasPrices.l1GasPrice, 16) / 1e9, 'gwei'); console.log('L2 Gas Price:', parseInt(gasPrices.l2GasPrice, 16) / 1e9, 'gwei'); // Calculate fee estimates with current prices async function estimateFeesWithCurrentPrices(txData) { const gasPrices = await getRollupGasPrices(); // Estimate L2 execution gas const l2GasEstimate = await estimateGas(txData); const l2Fee = BigInt(l2GasEstimate) * BigInt(gasPrices.l2GasPrice); // Estimate L1 data fee (this uses L1 gas price internally) const l1Fee = await estimateL1Fee(txData); const totalFee = l1Fee + l2Fee; return { l1Fee: Number(l1Fee) / 1e18, l2Fee: Number(l2Fee) / 1e18, totalFee: Number(totalFee) / 1e18, gasPrices: { l1GasPrice: parseInt(gasPrices.l1GasPrice, 16), l2GasPrice: parseInt(gasPrices.l2GasPrice, 16) } }; } ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": { "l1GasPrice": "0x34630b8a00", "l2GasPrice": "0x1dcd6500" } } ``` This shows: - **L1 Gas Price**: `0x34630b8a00` (~14 gwei) - for L1 data availability - **L2 Gas Price**: `0x1dcd6500` (~0.5 gwei) - for L2 execution ## Understanding Optimism Gas Price Structure ### Dual Gas Price Model Optimism uses a dual gas price model: 1. **L1 Gas Price**: Cost of posting transaction data to Ethereum mainnet 2. **L2 Gas Price**: Cost of executing transactions on the L2 network ```javascript // Monitor gas price trends on Optimism class OptimismGasPriceMonitor { constructor(apiKey) { this.apiKey = apiKey; this.baseUrl = `https://api-cronos-mainnet-archive.n.dwellir.com/${apiKey}`; } async getCurrentPrices() { const response = await fetch(this.baseUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'rollup_gasPrices', params: [], id: 1 }) }); const data = await response.json(); return { l1GasPrice: parseInt(data.result.l1GasPrice, 16), l2GasPrice: parseInt(data.result.l2GasPrice, 16), timestamp: Date.now() }; } async trackPriceHistory(duration = 3600000) { // 1 hour const history = []; const startTime = Date.now(); while (Date.now() - startTime < duration) { const prices = await this.getCurrentPrices(); history.push(prices); console.log(`L1: ${(prices.l1GasPrice / 1e9).toFixed(2)} gwei, L2: ${(prices.l2GasPrice / 1e9).toFixed(2)} gwei`); // Wait 5 minutes before next sample await new Promise(resolve => setTimeout(resolve, 300000)); } return history; } analyzePriceTrends(history) { const l1Prices = history.map(h => h.l1GasPrice); const l2Prices = history.map(h => h.l2GasPrice); return { l1Stats: { min: Math.min(...l1Prices) / 1e9, max: Math.max(...l1Prices) / 1e9, avg: l1Prices.reduce((a, b) => a + b, 0) / l1Prices.length / 1e9 }, l2Stats: { min: Math.min(...l2Prices) / 1e9, max: Math.max(...l2Prices) / 1e9, avg: l2Prices.reduce((a, b) => a + b, 0) / l2Prices.length / 1e9 } }; } } ``` ### Cost Optimization Strategies ```javascript // Optimize transaction costs based on gas prices class OptimismCostOptimizer { static async getOptimalTransactionTime(txData, maxWaitTime = 3600000) { const monitor = new OptimismGasPriceMonitor(); let bestPrice = Infinity; let bestTime = null; const checkInterval = 300000; // 5 minutes const checks = Math.floor(maxWaitTime / checkInterval); for (let i = 0; i < checks; i++) { const prices = await monitor.getCurrentPrices(); const estimatedCost = await this.estimateTotalCost(txData, prices); if (estimatedCost < bestPrice) { bestPrice = estimatedCost; bestTime = new Date(); } console.log(`Check ${i + 1}/${checks}: Cost ${estimatedCost.toFixed(6)} ETH`); if (i < checks - 1) { await new Promise(resolve => setTimeout(resolve, checkInterval)); } } return { bestPrice: bestPrice, bestTime: bestTime, savingsOpportunity: bestPrice < await this.estimateTotalCost(txData) }; } static async estimateTotalCost(txData, gasPrices = null) { if (!gasPrices) { const monitor = new OptimismGasPriceMonitor(); gasPrices = await monitor.getCurrentPrices(); } // Get L1 fee estimate const l1Response = await fetch('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_estimateL1Fee', params: [txData], id: 1 }) }); const l1Fee = BigInt((await l1Response.json()).result); // Get L2 gas estimate const l2Response = await fetch('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_estimateGas', params: [txData], id: 2 }) }); const l2Gas = BigInt((await l2Response.json()).result); const l2Fee = l2Gas * BigInt(gasPrices.l2GasPrice); return Number(l1Fee + l2Fee) / 1e18; } } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Optimism documentation](/docs/optimism).* --- ## rollup_getInfo - Get Rollup Information # rollup_getInfo Returns comprehensive information about the Optimism rollup, including sequencer status, batch submission details, and rollup configuration. ## When to Use This Method `rollup_getInfo` is essential for: - **Rollup Monitoring** - Check the health and status of the Optimism network - **Sequencer Status** - Monitor sequencer uptime and performance - **Batch Tracking** - Track L1 batch submissions and confirmations - **Network Analytics** - Gather data for Optimism network analysis - **Integration Health Checks** - Verify rollup parameters for applications ## Parameters None. This method takes no parameters. ## Implementation Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "rollup_getInfo", "params": [], "id": 1 }' ``` ```javascript // Get Optimism rollup information const response = await fetch('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'rollup_getInfo', params: [], id: 1 }) }); const data = await response.json(); const rollupInfo = data.result; console.log('Optimism Rollup Info:'); console.log('Mode:', rollupInfo.mode); console.log('Sequencer Running:', rollupInfo.sequencer_running); console.log('Synced L1 Block:', rollupInfo.synced_l1); console.log('Head L1 Block:', rollupInfo.head_l1); console.log('Safe L2 Block:', rollupInfo.safe_l2); console.log('Finalized L2 Block:', rollupInfo.finalized_l2); // Monitor rollup health async function monitorOptimismHealth() { const info = await getRollupInfo(); const health = { sequencerActive: info.sequencer_running, syncStatus: calculateSyncStatus(info), lastBatchTime: info.last_batch_time, l1HeadAge: Date.now() / 1000 - info.head_l1?.timestamp || 0 }; // Alert if sequencer is down if (!health.sequencerActive) { console.warn('⚠️ Optimism sequencer is not running!'); } // Alert if sync is behind if (health.syncStatus < 0.99) { console.warn(`⚠️ Optimism sync behind: ${(health.syncStatus * 100).toFixed(2)}%`); } return health; } function calculateSyncStatus(info) { if (!info.synced_l1 || !info.head_l1) return 0; return info.synced_l1.block_number / info.head_l1.block_number; } ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": { "mode": "sequencer", "sequencer_running": true, "synced_l1": { "block_number": 18500000, "block_hash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", "timestamp": 1699123456 }, "head_l1": { "block_number": 18500010, "block_hash": "0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890", "timestamp": 1699123576 }, "safe_l2": { "block_number": 123456789, "block_hash": "0x9876543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba", "timestamp": 1699123500 }, "finalized_l2": { "block_number": 123456700, "block_hash": "0x456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123", "timestamp": 1699123400 }, "unsafe_l2": { "block_number": 123456800, "block_hash": "0xfedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210", "timestamp": 1699123550 } } } ``` ## Understanding Rollup Information ### Key Fields Explained - **mode**: Operating mode of the node ("sequencer", "verifier", etc.) - **sequencer_running**: Whether the sequencer is actively processing transactions - **synced_l1**: Last L1 block that has been processed by the rollup - **head_l1**: Latest known L1 block - **safe_l2**: L2 block that is considered safe (confirmed on L1) - **finalized_l2**: L2 block that is finalized (cannot be reverted) - **unsafe_l2**: Latest L2 block (may not be confirmed on L1 yet) ### Rollup Health Monitoring ```javascript class OptimismRollupMonitor { constructor(apiKey) { this.apiKey = apiKey; this.baseUrl = `https://api-cronos-mainnet-archive.n.dwellir.com/${apiKey}`; } async getRollupInfo() { const response = await fetch(this.baseUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'rollup_getInfo', params: [], id: 1 }) }); return (await response.json()).result; } async checkRollupHealth() { const info = await this.getRollupInfo(); const now = Math.floor(Date.now() / 1000); const health = { overall: 'healthy', checks: { sequencerActive: { status: info.sequencer_running ? 'pass' : 'fail', message: info.sequencer_running ? 'Sequencer is running' : 'Sequencer is down' }, l1Sync: { status: 'unknown', message: 'L1 sync status' }, l2Progress: { status: 'unknown', message: 'L2 block progression' } } }; // Check L1 sync status if (info.synced_l1 && info.head_l1) { const syncRatio = info.synced_l1.block_number / info.head_l1.block_number; health.checks.l1Sync.status = syncRatio > 0.99 ? 'pass' : 'warn'; health.checks.l1Sync.message = `Synced ${(syncRatio * 100).toFixed(2)}% of L1 blocks`; } // Check L2 block times if (info.unsafe_l2) { const blockAge = now - info.unsafe_l2.timestamp; health.checks.l2Progress.status = blockAge < 60 ? 'pass' : 'warn'; health.checks.l2Progress.message = `Latest L2 block is ${blockAge}s old`; } // Determine overall health const failedChecks = Object.values(health.checks).filter(c => c.status === 'fail').length; const warnChecks = Object.values(health.checks).filter(c => c.status === 'warn').length; if (failedChecks > 0) { health.overall = 'unhealthy'; } else if (warnChecks > 0) { health.overall = 'degraded'; } return health; } async monitorContinuously(interval = 30000) { console.log('🔍 Starting Optimism rollup monitoring...'); setInterval(async () => { try { const health = await this.checkRollupHealth(); const timestamp = new Date().toISOString(); console.log(`[${timestamp}] Rollup Health: ${health.overall.toUpperCase()}`); Object.entries(health.checks).forEach(([check, result]) => { const icon = result.status === 'pass' ? '✅' : result.status === 'warn' ? '⚠️' : '❌'; console.log(` ${icon} ${check}: ${result.message}`); }); if (health.overall !== 'healthy') { console.log(`🚨 ALERT: Optimism rollup is ${health.overall}`); } } catch (error) { console.error('Failed to check rollup health:', error); } }, interval); } } // Usage const monitor = new OptimismRollupMonitor('YOUR_API_KEY'); monitor.monitorContinuously(30000); // Check every 30 seconds ``` ### Batch Submission Tracking ```javascript // Track L1 batch submissions class OptimismBatchTracker { async trackBatchSubmissions() { const info = await this.getRollupInfo(); return { lastL2Block: info.safe_l2?.block_number || 0, lastL1Confirmation: info.synced_l1?.block_number || 0, pendingBlocks: (info.unsafe_l2?.block_number || 0) - (info.safe_l2?.block_number || 0), estimatedConfirmationTime: this.estimateConfirmationTime(info) }; } estimateConfirmationTime(info) { // Optimism typically submits batches every ~10-20 minutes // Plus ~12 minutes for L1 confirmations const avgBatchInterval = 15 * 60; // 15 minutes const l1ConfirmationTime = 12 * 60; // 12 minutes return avgBatchInterval + l1ConfirmationTime; } } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Optimism documentation](/docs/optimism).* --- ## web3_clientVersion - Cronos RPC Method # web3_clientVersion Returns the current client version on Cronos. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Client version string | ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); const version = await provider.send('web3_clientVersion', []); console.log('Client version:', version); ``` --- ## web3_sha3 - Cronos RPC Method # web3_sha3 Returns Keccak-256 (not standard SHA3-256) of the given data on Cronos. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `data` | `DATA` | Yes | Data to hash | ## Request ```json { "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Keccak-256 hash of the data | ## Code Examples ```bash curl -X POST https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-cronos-mainnet-archive.n.dwellir.com/YOUR_API_KEY'); // Using RPC const hash = await provider.send('web3_sha3', ['0x68656c6c6f']); console.log('Hash:', hash); // Using ethers directly (faster) const localHash = keccak256(toUtf8Bytes('hello')); console.log('Local hash:', localHash); ``` --- ## author_pendingExtrinsics - Enjin RPC Method # author_pendingExtrinsics Returns all pending extrinsics in the transaction pool on Enjin. ## Use Cases - **Mempool monitoring** - Track pending transactions - **Transaction status** - Check if your transaction is pending for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Pool analysis** - Monitor network activity ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "author_pendingExtrinsics", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_pendingExtrinsics", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const pending = await api.rpc.author.pendingExtrinsics(); console.log('Pending extrinsics:', pending.length); pending.forEach((ext, idx) => { console.log(`${idx}: ${ext.method.section}.${ext.method.method}`); }); await api.disconnect(); ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction --- ## author_rotateKeys - Enjin RPC Method # author_rotateKeys Generate a new set of session keys on Enjin. This method creates fresh cryptographic keys for validator operations and stores them in the node's keystore. The returned keys must be registered on-chain via `session.setKeys`. ## Use Cases - **Validator setup** - Generate initial session keys for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Key rotation** - Periodically rotate keys for security best practices - **Recovery** - Generate new keys after potential key compromise ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | `Bytes` | Concatenated SCALE-encoded public keys for all session key types | ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_rotateKeys", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Generate new session keys const keys = await api.rpc.author.rotateKeys(); console.log('New session keys:', keys.toHex()); // These keys need to be registered on-chain: // api.tx.session.setKeys(keys, proof) await api.disconnect(); ``` ```python url = 'https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'author_rotateKeys', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json() if 'result' in result: session_keys = result['result'] print(f'New session keys: {session_keys}') print('Register these keys using session.setKeys extrinsic') else: print(f"Error: {result.get('error')}") ``` ## Validator Setup Workflow 1. **Generate keys** - Call `author_rotateKeys` on your validator node 2. **Register on-chain** - Submit `session.setKeys(keys, proof)` extrinsic 3. **Wait for session** - Keys become active in the next session 4. **Verify** - Check `session.nextKeys` storage ## Security Considerations - Only call this method on your own validator node - Session keys are stored in the node's keystore - Rotate keys periodically and after any security incident - Never expose this RPC method publicly ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit setKeys transaction - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - View pending transactions --- ## author_submitAndWatchExtrinsic - Enjin RPC Method # author_submitAndWatchExtrinsic Submit a signed extrinsic to and subscribe to status updates. This WebSocket method provides real-time feedback on transaction progress from submission through finalization. ## Use Cases - **Transaction tracking** - Monitor extrinsic lifecycle for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **UI feedback** - Show users real-time transaction status - **Confirmation workflows** - Wait for specific finality level before proceeding ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `Bytes` | Yes | SCALE-encoded signed extrinsic | ## Returns Returns a subscription that emits `ExtrinsicStatus` updates: | Status | Description | |--------|-------------| | `future` | In future queue (nonce too high) | | `ready` | In ready queue, waiting for block | | `broadcast` | Broadcast to peers | | `inBlock` | Included in block (hash provided) | | `retracted` | Block retracted (reorg) | | `finalityTimeout` | Finality timeout | | `finalized` | Finalized in block (hash provided) | | `usurped` | Replaced by another extrinsic | | `dropped` | Dropped from pool | | `invalid` | Invalid extrinsic | ## Code Examples ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const keyring = new Keyring({ type: 'sr25519' }); // Create and sign a transfer const sender = keyring.addFromUri('//Alice'); const transfer = api.tx.balances.transferKeepAlive( '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 1000000000000n ); // Submit and watch const unsub = await transfer.signAndSend(sender, ({ status, events }) => { console.log(`Status: ${status.type}`); if (status.isInBlock) { console.log(`Included in block: ${status.asInBlock.toHex()}`); } if (status.isFinalized) { console.log(`Finalized in block: ${status.asFinalized.toHex()}`); unsub(); } }); ``` ```python async def submit_and_watch(signed_extrinsic_hex): uri = 'wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: # Submit and subscribe await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'author_submitAndWatchExtrinsic', 'params': [signed_extrinsic_hex], 'id': 1 })) # Get subscription ID response = json.loads(await ws.recv()) if 'error' in response: print(f"Error: {response['error']}") return sub_id = response['result'] print(f'Watching with subscription: {sub_id}') # Listen for status updates while True: message = json.loads(await ws.recv()) if 'params' in message: status = message['params']['result'] print(f"Status: {status}") # Check for finalization if isinstance(status, dict) and 'finalized' in status: print(f"Finalized in: {status['finalized']}") break # asyncio.run(submit_and_watch('0x...')) ``` ## Status Flow ``` ready → broadcast → inBlock → finalized ↘ retracted (if reorg) ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit without watching (fire-and-forget) - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - View transaction pool - [`payment_queryInfo`](./payment_queryInfo) - Estimate fees before submission --- ## author_submitExtrinsic - Enjin RPC Method # author_submitExtrinsic Submit a signed extrinsic to Enjin for inclusion in a block. ## Use Cases - **Transaction submission** - Broadcast signed transactions - **dApp interactions** - Execute on-chain operations for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Automated systems** - Submit programmatic transactions ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `String` | Yes | Hex-encoded signed extrinsic | ## Request ```json { "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": ["0x..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Transaction hash | ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": ["0x..."], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const keyring = new Keyring({ type: 'sr25519' }); const sender = keyring.addFromUri('//Alice'); // Build and sign transaction const transfer = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000); const hash = await transfer.signAndSend(sender); console.log('Transaction hash:', hash.toHex()); await api.disconnect(); ``` ## Related Methods - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - Get pending transactions - [`payment_queryInfo`](./payment_queryInfo) - Estimate fees --- ## beefy_getFinalizedHead - Enjin RPC Method # beefy_getFinalizedHead Returns the block hash of the latest BEEFY-finalized block on Enjin. BEEFY (Bridge Efficiency Enabling Finality Yielder) provides additional finality proofs optimized for light clients and bridges. ## Use Cases - **Cross-chain bridges** - Verify finality proofs for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Light clients** - Efficient finality verification without full GRANDPA proofs - **Trustless bridges** - Generate compact finality proofs for external chains ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | `Hash` | Block hash of the latest BEEFY-finalized block | ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "beefy_getFinalizedHead", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get BEEFY finalized head const beefyHead = await api.rpc.beefy.getFinalizedHead(); console.log('BEEFY finalized:', beefyHead.toHex()); // Compare with GRANDPA finalized const grandpaHead = await api.rpc.chain.getFinalizedHead(); console.log('GRANDPA finalized:', grandpaHead.toHex()); await api.disconnect(); ``` ```python url = 'https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'beefy_getFinalizedHead', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json() if 'result' in result: print(f"BEEFY finalized: {result['result']}") else: print(f"Error: {result.get('error')}") ``` ## BEEFY vs GRANDPA Finality | Aspect | GRANDPA | BEEFY | |--------|---------|-------| | **Purpose** | Primary finality | Bridge-optimized finality | | **Proof size** | Larger (full validator set) | Compact (aggregated signatures) | | **Latency** | Immediate | Slightly delayed | | **Use case** | On-chain finality | Cross-chain bridges | ## Availability BEEFY is enabled on relay chains and some parachains. If BEEFY is not enabled, this method will return an error. ## Related Methods - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - GRANDPA finalized head - [`grandpa_roundState`](./grandpa_roundState) - GRANDPA consensus state - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks --- ## chain_getBlock - Enjin RPC Method # chain_getBlock Retrieves complete block information from Enjin, including the block header, extrinsics, and justifications. > **Why Enjin?** Build on the purpose-built NFT blockchain with protocol-level minting and $100M Metaverse Fund with NFT functions at protocol level, Fuel Tanks for subsidized fees, 700-1000 TPS, 6-second finality, and ERC-1155 standard pioneer. ## Use Cases The `chain_getBlock` method is essential for: - **Block explorers** - Display complete block information - **Chain analysis** - Analyze block production patterns - **Transaction verification** - Confirm extrinsic inclusion for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Data indexing** - Build historical blockchain databases ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Hex-encoded block hash. If omitted, returns latest block | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getBlock", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `block` | `Object` | Complete block data | | `block.header` | `Object` | Block header information | | `block.header.parentHash` | `String` | Hash of the parent block | | `block.header.number` | `String` | Block number (hex-encoded) | | `block.header.stateRoot` | `String` | Root of the state trie | | `block.header.extrinsicsRoot` | `String` | Root of the extrinsics trie | | `block.extrinsics` | `Array` | Array of extrinsics in the block | | `justifications` | `Array` | Block justifications (if available) | ## Code Examples ```bash # Get latest block curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": [], "id": 1 }' # Get specific block curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get latest block const latestHash = await api.rpc.chain.getBlockHash(); const latestBlock = await api.rpc.chain.getBlock(latestHash); console.log('Latest block:', { number: latestBlock.block.header.number.toNumber(), hash: latestHash.toHex(), extrinsicsCount: latestBlock.block.extrinsics.length }); // Get specific block const blockHash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'; const block = await api.rpc.chain.getBlock(blockHash); console.log('Block extrinsics:', block.block.extrinsics.length); await api.disconnect(); ``` ```python def get_block(block_hash=None): url = 'https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY' params = [block_hash] if block_hash else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getBlock', 'params': params, 'id': 1 } response = requests.post(url, json=payload) data = response.json() if 'error' in data: raise Exception(f"RPC Error: {data['error']}") return data['result'] # Get latest block latest_block = get_block() block_number = int(latest_block['block']['header']['number'], 16) print(f'Latest block number: {block_number}') # Get specific block specific_block = get_block('0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3') print(f"Extrinsics count: {len(specific_block['block']['extrinsics'])}") ``` ## Related Methods - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number - [`chain_getHeader`](./chain_getHeader) - Get block header only - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get finalized block hash --- ## chain_getBlockHash - Enjin RPC Method # chain_getBlockHash Returns the block hash for a given block number on Enjin. ## Use Cases - **Historical queries** - Convert block numbers to hashes - **Block navigation** - Navigate blockchain history for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Data indexing** - Build block number to hash mappings ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `Number` | No | Block number. If omitted, returns latest block hash | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getBlockHash", "params": [1000000], "id": 1 } ``` ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlockHash", "params": [1000000], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get hash for specific block number const blockNumber = 1000000; const blockHash = await api.rpc.chain.getBlockHash(blockNumber); console.log(`Block ${blockNumber} hash:`, blockHash.toHex()); await api.disconnect(); ``` ```python def get_block_hash(block_number=None): url = 'https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY' params = [block_number] if block_number is not None else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getBlockHash', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] block_hash = get_block_hash(1000000) print(f'Block hash: {block_hash}') ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get block by hash - [`chain_getHeader`](./chain_getHeader) - Get block header --- ## chain_getFinalizedHead - Enjin RPC Method # chain_getFinalizedHead Returns the hash of the last finalized block on Enjin. ## Use Cases - **Confirmed state** - Query state that cannot be reverted - **Transaction confirmation** - Verify transaction finality for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Safe checkpoints** - Use finalized blocks for critical operations ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const finalizedHash = await api.rpc.chain.getFinalizedHead(); console.log('Finalized block hash:', finalizedHash.toHex()); // Get finalized block details const block = await api.rpc.chain.getBlock(finalizedHash); console.log('Finalized block number:', block.block.header.number.toNumber()); await api.disconnect(); ``` ```python def get_finalized_head(): url = 'https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'chain_getFinalizedHead', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] finalized_hash = get_finalized_head() print(f'Finalized block hash: {finalized_hash}') ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get block by hash - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number --- ## chain_getHeader - Enjin RPC Method # chain_getHeader Returns the block header for a given hash on Enjin. ## Use Cases - **Lightweight queries** - Get header without full block data - **Chain synchronization** - Track block production for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Parent chain navigation** - Follow parentHash links ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash. If omitted, returns latest header | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getHeader", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 } ``` ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getHeader", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get latest header const header = await api.rpc.chain.getHeader(); console.log('Block number:', header.number.toNumber()); console.log('Parent hash:', header.parentHash.toHex()); await api.disconnect(); ``` ```python def get_header(block_hash=None): url = 'https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY' params = [block_hash] if block_hash else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getHeader', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] header = get_header() print(f"Block number: {int(header['number'], 16)}") ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get full block with extrinsics - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number --- ## chain_subscribeFinalizedHeads - Enjin RPC Method # chain_subscribeFinalizedHeads Subscribe to receive notifications when blocks are finalized on Enjin. Finalized blocks are guaranteed to never be reverted, making this essential for applications requiring strong consistency. ## Use Cases - **Exchange deposits** - Only credit funds after finalization for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Bridge operations** - Wait for finality before cross-chain transfers - **Critical state changes** - Ensure irreversibility for important transactions ## Parameters This method takes no parameters. ## Returns Returns a subscription ID. The subscription emits `Header` objects for each finalized block: | Field | Type | Description | |-------|------|-------------| | `parentHash` | `Hash` | Parent block hash | | `number` | `BlockNumber` | Block number | | `stateRoot` | `Hash` | State trie root hash | | `extrinsicsRoot` | `Hash` | Extrinsics trie root hash | | `digest` | `Digest` | Block digest with consensus logs | ## Code Examples ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Subscribe to finalized heads const unsubscribe = await api.rpc.chain.subscribeFinalizedHeads((header) => { console.log(`Finalized block #${header.number}`); console.log(` Hash: ${header.hash.toHex()}`); // Safe to consider this block permanent processConfirmedBlock(header); }); // Later: unsubscribe() ``` ```python async def subscribe_finalized(): uri = 'wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'chain_subscribeFinalizedHeads', 'params': [], 'id': 1 })) response = json.loads(await ws.recv()) sub_id = response['result'] print(f'Subscribed to finalized heads: {sub_id}') while True: message = json.loads(await ws.recv()) if 'params' in message: header = message['params']['result'] block_num = int(header['number'], 16) print(f"Finalized: #{block_num}") asyncio.run(subscribe_finalized()) ``` ## Finality Lag Finalized blocks typically lag behind the best block by a few blocks due to GRANDPA consensus requirements. This is normal and ensures Byzantine fault tolerance. ## Related Methods - [`chain_subscribeNewHeads`](./chain_subscribeNewHeads) - Subscribe to all new blocks (not just finalized) - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get current finalized block hash - [`grandpa_roundState`](./grandpa_roundState) - Monitor GRANDPA consensus progress --- ## chain_subscribeNewHeads - Enjin RPC Method # chain_subscribeNewHeads Subscribe to receive notifications when new block headers are produced on Enjin. This WebSocket subscription provides real-time updates for each new block. ## Use Cases - **Block monitoring** - Track new blocks in real-time for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Event indexing** - Trigger processing when new blocks arrive - **Chain synchronization** - Keep external systems in sync with the chain ## Parameters This method takes no parameters. ## Returns Returns a subscription ID. The subscription emits `Header` objects for each new block: | Field | Type | Description | |-------|------|-------------| | `parentHash` | `Hash` | Parent block hash | | `number` | `BlockNumber` | Block number | | `stateRoot` | `Hash` | State trie root hash | | `extrinsicsRoot` | `Hash` | Extrinsics trie root hash | | `digest` | `Digest` | Block digest with consensus logs | ## Code Examples ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Subscribe to new heads const unsubscribe = await api.rpc.chain.subscribeNewHeads((header) => { console.log(`New block #${header.number}`); console.log(` Hash: ${header.hash.toHex()}`); console.log(` Parent: ${header.parentHash.toHex()}`); console.log(` State root: ${header.stateRoot.toHex()}`); }); // Later: unsubscribe() ``` ```python async def subscribe_new_heads(): uri = 'wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: # Subscribe to new heads await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'chain_subscribeNewHeads', 'params': [], 'id': 1 })) # Get subscription ID response = json.loads(await ws.recv()) sub_id = response['result'] print(f'Subscribed with ID: {sub_id}') # Listen for new headers while True: message = json.loads(await ws.recv()) if 'params' in message: header = message['params']['result'] print(f"Block #{int(header['number'], 16)}") print(f" Hash: {header['parentHash']}") asyncio.run(subscribe_new_heads()) ``` ## Subscription vs Polling | Approach | Latency | Resource Usage | Use Case | |----------|---------|----------------|----------| | `subscribeNewHeads` | Immediate | Low (push-based) | Real-time monitoring | | Polling `getHeader` | Block time + poll interval | Higher (repeated requests) | Simple integrations | ## Related Methods - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks only - [`chain_getHeader`](./chain_getHeader) - Get a specific block header - [`chain_getBlock`](./chain_getBlock) - Get full block with extrinsics --- ## grandpa_roundState - Enjin RPC Method # grandpa_roundState Returns the state of the current GRANDPA finality round on Enjin. GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) is the finality gadget used by Substrate chains. ## Use Cases - **Finality monitoring** - Track consensus progress for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Validator analysis** - Monitor prevote/precommit participation - **Chain health checks** - Detect finality delays or stalls ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `setId` | `u64` | Current authority set ID | | `best` | `RoundState` | Best round state | | `background` | `Vec` | Background rounds | ### RoundState Structure | Field | Type | Description | |-------|------|-------------| | `round` | `u64` | Round number | | `totalWeight` | `u64` | Total validator weight | | `thresholdWeight` | `u64` | Weight needed for supermajority | | `prevotes` | `Prevotes` | Prevote information | | `precommits` | `Precommits` | Precommit information | ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "grandpa_roundState", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const roundState = await api.rpc.grandpa.roundState(); console.log('Set ID:', roundState.setId.toString()); console.log('Best round:', roundState.best.round.toString()); console.log('Total weight:', roundState.best.totalWeight.toString()); console.log('Threshold:', roundState.best.thresholdWeight.toString()); await api.disconnect(); ``` ```python url = 'https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'grandpa_roundState', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json()['result'] print(f"Set ID: {result['setId']}") print(f"Round: {result['best']['round']}") print(f"Total weight: {result['best']['totalWeight']}") ``` ## Understanding GRANDPA Rounds 1. **Prevote phase** - Validators vote on best block they've seen 2. **Precommit phase** - Validators commit to finalize if supermajority prevoted 3. **Finalization** - Block is finalized when 2/3+ weight precommits ## Related Methods - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get current finalized hash - [`beefy_getFinalizedHead`](./beefy_getFinalizedHead) - BEEFY finality (if enabled) --- ## Enjin RPC with Dwellir # Build on Enjin Matrix – The NFT-Native Application Layer ## Why Build on Enjin Matrix? ### 🎮 NFT-First Runtime - Protocol-level NFT minting, on-chain metadata, and marketplace enforcement remove the need for bespoke smart contracts ([Enjin Blockchain overview](https://enjin.io/technology/blockchain)). - ENJ-denominated fees are tuned for games and app developers, giving predictable operating costs for live services ([Enjin Blockchain overview](https://enjin.io/technology/blockchain)). ### ⚙️ Fuel Tanks & Managed Wallets - Fuel tanks sponsor transaction fees for specific players or apps, smoothing onboarding into Matrixchain ([Fuel Tanks docs](https://docs.enjin.io/docs/creating-a-fuel-tank)). - Managed wallets let users receive NFTs before creating self-custodial accounts, ideal for mainstream launches ([Managed wallets docs](https://docs.enjin.io/docs/using-managed-wallets)). ### 🛡️ Dual-Layer Security - Matrixchain execution is secured by the Enjin Relaychain, combining Aura authoring with relay-governed GRANDPA finality ([Enjin Blockchain overview](https://enjin.io/technology/blockchain)). - Custom matrixchains can connect while inheriting the same security and cross-chain routing primitives provided by the Relaychain ([Enjin Blockchain overview](https://enjin.io/technology/blockchain)). ## Quick Start with Enjin :::info Get your API key Sign up at the Dwellir dashboard to generate an API key, then replace `YOUR_API_KEY` in the endpoints above. Keys can be scoped per environment to manage limits and analytics. ::: ### Installation & Setup ```bash # Health check curl -s https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"system_health","params":[],"id":1}' # Latest finalized head curl -s https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"chain_getFinalizedHead","params":[],"id":2}' # Runtime versions curl -s https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"state_getRuntimeVersion","params":[],"id":3}' ``` ```typescript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const [chain, runtime, head] = await Promise.all([ api.rpc.system.chain(), api.rpc.state.getRuntimeVersion(), api.rpc.chain.getHeader() ]); console.log(`Connected to ${chain} specVersion ${runtime.specVersion}`); console.log(`Best block #${head.number.toNumber()} (${head.hash.toHex()})`); const validator = 'efS1ZdvCHHviX7qnTGZEZQX9Uz3qpibG9L5RpF9niM8ne5RBn'; const account = await api.query.system.account(validator); console.log('Validator free balance:', account.data.free.toHuman()); ``` ```rust use subxt::{OnlineClient, PolkadotConfig}; use subxt::ext::sp_core::crypto::AccountId32; #[tokio::main] async fn main() -> anyhow::Result<()> { let api = OnlineClient::::from_url( "wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY" ).await?; let runtime = api.rpc().runtime_version(None).await?; println!("specVersion={} txVersion={}", runtime.spec_version, runtime.transaction_version); let account: AccountId32 = "efS1ZdvCHHviX7qnTGZEZQX9Uz3qpibG9L5RpF9niM8ne5RBn".parse()?; let balance = api .storage() .at_latest() .await? .fetch(&subxt::dynamic::storage("System", "Account", vec![account.clone().into()])) .await?; println!("Account info: {:?}", balance); Ok(()) } ``` ```python from substrateinterface import SubstrateInterface substrate = SubstrateInterface( url="wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY" ) chain = substrate.rpc_request("system_chain", []) print("Chain:", chain["result"]) account_info = substrate.query( module='System', storage_function='Account', params=['efS1ZdvCHHviX7qnTGZEZQX9Uz3qpibG9L5RpF9niM8ne5RBn'] ) print("Free balance:", account_info.value['data']['free']) ``` ## Network Information Genesis Hash 0x3af4ff48ec76d2efc8476730f423ac07e25ad48f5f4c9dc39c778b164d808615 Verified via `chain_getBlockHash(0)` Runtime Spec 1022 Transaction version 11 (`state_getRuntimeVersion`) SS58 Prefix 1110 `system_properties` result Native Token ENJ 18 decimals (`system_properties`) :::info Matrix Ecosystem Snapshot (3 Oct 2025) - **Relay chain**: Enjin Relaychain (`0xd8761d3c88f26dc12875c00d3165f7d67243d56fc85b4cf19937601a7916e5a9`, verified via `chain_getBlockHash(0)` on [archive.relay.blockchain.enjin.io](https://archive.relay.blockchain.enjin.io)) - **Finality**: Aura authorship with GRANDPA finality shared by the Enjin Relaychain - **Address format**: SS58 prefix `1110` returned by `system_properties` on [archive.matrix.blockchain.enjin.io](https://archive.matrix.blockchain.enjin.io) - **Runtime**: spec version `1022`, transaction version `11` per `state_getRuntimeVersion` on [archive.matrix.blockchain.enjin.io](https://archive.matrix.blockchain.enjin.io) - **Explorers**: [Matrix Console](https://console.enjin.io) (mainnet & canary) - **Canary runtime**: Enjin Matrix Canary (`wss://api-enjin-canary-matrix.n.dwellir.com/YOUR_API_KEY`) ::: ## Available JSON-RPC Methods ### Core Substrate Namespaces | Group | Purpose | Reference | |-------|---------|-----------| | `system_*` | Node identity, health, and network properties | [`system_chain`](/enjin/system_chain), [`system_health`](/enjin/system_health), [`system_properties`](/enjin/system_properties), [`system_version`](/enjin/system_version) | | `chain_*` | Retrieve block data and follow new or finalized heads | [`chain_getBlockHash`](/enjin/chain_getBlockHash), [`chain_getBlock`](/enjin/chain_getBlock), [`chain_getHeader`](/enjin/chain_getHeader), [`chain_getFinalizedHead`](/enjin/chain_getFinalizedHead), [`chain_subscribeNewHeads`](/enjin/chain_subscribeNewHeads), [`chain_subscribeFinalizedHeads`](/enjin/chain_subscribeFinalizedHeads) | | `state_*` | Read storage, query metadata, and execute runtime APIs | [`state_call`](/enjin/state_call), [`state_getKeys`](/enjin/state_getKeys), [`state_getKeysPaged`](/enjin/state_getKeysPaged), [`state_getMetadata`](/enjin/state_getMetadata), [`state_getRuntimeVersion`](/enjin/state_getRuntimeVersion), [`state_getStorage`](/enjin/state_getStorage) | | `author_*` | Submit signed extrinsics and stream lifecycle events | [`author_submitExtrinsic`](/enjin/author_submitExtrinsic), [`author_submitAndWatchExtrinsic`](/enjin/author_submitAndWatchExtrinsic), [`author_pendingExtrinsics`](/enjin/author_pendingExtrinsics), [`author_rotateKeys`](/enjin/author_rotateKeys) | | `payment_*` | Estimate fees payable in ENJ | [`payment_queryInfo`](/enjin/payment_queryInfo), [`payment_queryFeeDetails`](/enjin/payment_queryFeeDetails) | | `rpc_methods` | Enumerate every RPC namespace exposed by your node | [`rpc_methods`](/enjin/rpc_methods) | | `childstate_*` | Interact with child tries used by pallets | `childstate_getKeys`, `childstate_getKeysPaged`, `childstate_getStorage` | | `offchain_*` | Inspect or mutate node-local offchain worker storage | `offchain_localStorageGet`, `offchain_localStorageSet` | ### Matrix-Specific Extensions | Namespace | Purpose | Notes | |-----------|---------|-------| | `fuelTanks_*` | Determine sponsorship coverage from fuel tanks | Requires authenticated access; discover endpoints via [`rpc_methods`](/enjin/rpc_methods). | | `multitokens_*` | Read cross-game NFT inventory and claimable drops | Returns managed-wallet data for onboarding flows. | | `ismp_*` | Inspect interoperability packets and consensus state | Enables monitoring for custom matrixchains secured by Enjin Relaychain. | | `transactionWatch_v1_*` | Subscribe to transaction status without author RPC | Lightweight watchers for infrastructure dashboards. | > **Tip:** Use [`rpc_methods`](/enjin/rpc_methods) to verify which optional namespaces (fuel tanks, multitokens, ISMP) are enabled for your API key and environment. Additional Substrate namespaces such as `childstate_*`, `offchain_*`, and read-proof helpers follow the standard Substrate semantics; their availability depends on node configuration and authorization. Use `rpc_methods` to inspect support before invoking them from clients. ## Common Integration Patterns - **Fuel tank sponsorship** – poll `fuelTanks_selectFuelTank` to determine which tank will cover fees for a user, then handle top-ups via governance-controlled accounts. - **Managed wallet onboarding** – detect custodial wallets via metadata and migrate them to self-custody by monitoring `Balances.Transfer` events to managed accounts. - **NFT marketplace indexing** – subscribe to `chain_subscribeFinalizedHeads`, pull block extrinsics, and decode marketplace pallets to track listings, royalty enforcement, and burns. ## Performance Best Practices - Prefer WebSocket endpoints for subscriptions and batched queries; fall back to HTTPS for stateless reads. - Cache runtime metadata keyed by `specVersion` to avoid re-fetching large SCALE blobs on each connection. - Use `state_getKeysPaged` with modest page sizes (≤500) when walking storage maps to respect rate limits. - Implement exponential backoff and retry logic for transient `429` or networking errors. ## Troubleshooting - **Connection refused** – ensure `YOUR_API_KEY` is present and the hostname matches the region you activated in Dwellir. - **Invalid SS58** – use prefix `1110` when encoding Matrixchain addresses; relay chain accounts use prefix `2135`. - **Extrinsic failures** – decode the `DispatchError` using the latest metadata; many marketplace pallets return module-specific error codes. - **Missing custom RPCs** – extend Polkadot.js type bundles with Enjin-specific RPC definitions when `API/INIT` warns about undecorated methods. ## Smoke Tests Run these endpoints after deployment to validate connectivity: ```bash # Health (should report peers > 0) curl -s https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"system_health","params":[],"id":1}' # Latest finalized hash curl -s https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"chain_getFinalizedHead","params":[],"id":2}' # Runtime versions curl -s https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"state_getRuntimeVersion","params":[],"id":3}' # RPC surface area curl -s https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"rpc_methods","params":[],"id":4}' ``` ## Migration Guide (Polkadot/Westend → Enjin Matrix) 1. **Endpoints** – replace legacy Polkadot/Westend RPC URLs with Dwellir Matrix endpoints listed above. 2. **Address format** – re-encode accounts with SS58 prefix `1110`; update wallet tooling accordingly. 3. **Fee economics** – call `payment_queryInfo` to account for ENJ-denominated fees and optional fuel tank sponsorships. 4. **Runtime pallets** – verify availability of Matrix-specific pallets (fuel tanks, managed wallets) and adjust type bundles. 5. **Event handling** – update indexers to interpret Enjin marketplace and multitoken events instead of Polkadot parachain events. ## Resources & Tools - [Enjin Blockchain Technology Overview](https://enjin.io/technology/blockchain) – architecture, performance targets, and ecosystem highlights. - [Console Explorer](https://console.enjin.io) – monitor blocks, accounts, and collections across mainnet and canary. - [Dwellir Dashboard](https://dashboard.dwellir.com) – manage API keys, usage analytics, and plan limits. - [Subscan (Matrixchain)](https://matrix.subscan.io) – alternative explorer for validators and extrinsics. --- Ready to go live? Deploy against Matrix mainnet using Dwellir’s globally anycasted infrastructure, then automate observability with the smoke tests above. --- ## payment_queryFeeDetails - Enjin RPC Method # payment_queryFeeDetails Returns a detailed breakdown of fees for a given extrinsic on Enjin. Unlike `payment_queryInfo` which returns the total fee, this method separates the fee into its component parts. ## Use Cases - **Fee analysis** - Understand fee composition for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Optimization** - Identify which fee component dominates costs - **Debugging** - Diagnose unexpected fee amounts ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `Bytes` | Yes | SCALE-encoded extrinsic (signed or unsigned) | | `blockHash` | `Hash` | No | Block hash for fee calculation context | ## Returns | Field | Type | Description | |-------|------|-------------| | `inclusionFee` | `Option` | Fee details (null for unsigned extrinsics) | ### InclusionFee Structure | Field | Type | Description | |-------|------|-------------| | `baseFee` | `Balance` | Fixed base fee per extrinsic | | `lenFee` | `Balance` | Fee based on encoded extrinsic length | | `adjustedWeightFee` | `Balance` | Fee based on execution weight | ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "payment_queryFeeDetails", "params": ["0x...encodedExtrinsic"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Create a sample transfer const tx = api.tx.balances.transferKeepAlive( '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 1000000000000n ); // Get fee details const feeDetails = await api.rpc.payment.queryFeeDetails(tx.toHex()); if (feeDetails.inclusionFee.isSome) { const fee = feeDetails.inclusionFee.unwrap(); console.log('Base fee:', fee.baseFee.toString()); console.log('Length fee:', fee.lenFee.toString()); console.log('Weight fee:', fee.adjustedWeightFee.toString()); } await api.disconnect(); ``` ```python url = 'https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY' # Replace with actual encoded extrinsic encoded_extrinsic = '0x...' payload = { 'jsonrpc': '2.0', 'method': 'payment_queryFeeDetails', 'params': [encoded_extrinsic], 'id': 1 } response = requests.post(url, json=payload) result = response.json()['result'] if result['inclusionFee']: fee = result['inclusionFee'] print(f"Base fee: {fee['baseFee']}") print(f"Length fee: {fee['lenFee']}") print(f"Weight fee: {fee['adjustedWeightFee']}") ``` ## Fee Components Explained | Component | Calculation | Optimization | |-----------|-------------|--------------| | **Base fee** | Fixed per extrinsic | Batch calls to share base fee | | **Length fee** | `length * lengthToFee` | Minimize call data size | | **Weight fee** | `weight * weightToFee` | Choose efficient operations | ## Related Methods - [`payment_queryInfo`](./payment_queryInfo) - Get total fee estimate - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction - [`state_call`](./state_call) - Call TransactionPaymentApi directly --- ## payment_queryInfo - Enjin RPC Method # payment_queryInfo Estimates the fee for an extrinsic on Enjin. ## Use Cases - **Fee estimation** - Calculate transaction costs before sending - **UI display** - Show fees to users for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Transaction planning** - Ensure sufficient funds ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `String` | Yes | Hex-encoded unsigned extrinsic | | `blockHash` | `String` | No | Block hash for fee calculation | ## Request ```json { "jsonrpc": "2.0", "method": "payment_queryInfo", "params": ["0x..."], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `weight` | `Object` | Transaction weight | | `class` | `String` | Dispatch class | | `partialFee` | `String` | Estimated fee | ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "payment_queryInfo", "params": ["0x..."], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Create transfer (unsigned for estimation) const transfer = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000); const info = await transfer.paymentInfo('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'); console.log('Partial fee:', info.partialFee.toHuman()); await api.disconnect(); ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction --- ## rpc_methods - Enjin RPC Method # rpc_methods Returns a list of all RPC methods available on Enjin. ## Use Cases - **API discovery** - List all available methods - **Compatibility checking** - Verify method availability for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Documentation** - Auto-generate method lists ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const methods = await api.rpc.rpc.methods(); console.log('Available methods:', methods.methods.length); await api.disconnect(); ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## state_call - Enjin RPC Method # state_call Calls a runtime API method on Enjin. ## Use Cases - **Runtime computations** - Execute runtime logic without transactions - **Account queries** - Use AccountNonceApi for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Fee estimation** - Use TransactionPaymentApi ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `method` | `String` | Yes | Runtime API method name | | `data` | `String` | Yes | SCALE-encoded call data | | `blockHash` | `String` | No | Block hash for historical call | ## Request ```json { "jsonrpc": "2.0", "method": "state_call", "params": ["AccountNonceApi_account_nonce", "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"], "id": 1 } ``` ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_call", "params": ["AccountNonceApi_account_nonce", "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get account nonce via runtime API const account = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const result = await api.call.accountNonceApi.accountNonce(account); console.log('Account nonce:', result.toNumber()); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Query storage - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## state_getKeys - JSON-RPC Method(Enjin) ## Description Returns a list of storage keys that share a given prefix. This method is helpful when you need to discover child keys beneath a map, such as iterating through all system accounts or fuel tank records in Enjin Matrix. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `prefix` | string | Yes | Hex-encoded storage prefix (typically `twox128(module) + hasher(storage)`) | `blockHash` | string \| null | No | Block hash for historical queries; `null` uses the best block | ## Returns An array of hex-encoded storage keys matching the supplied prefix. ## Request Example ```json { "jsonrpc": "2.0", "method": "state_getKeys", "params": [ "0x26aa394eea5630e07c48ae0c9558cef7", null ], "id": 1 } ``` ## Response Example (truncated) ```json { "jsonrpc": "2.0", "result": [ "0x26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac", "0x26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850", "0x26aa394eea5630e07c48ae0c9558cef734abf5cb34d6244378cddbf18e849d96", "…" ], "id": 1 } ``` ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getKeys", "params": ["0x26aa394eea5630e07c48ae0c9558cef7", null], "id": 1 }' ``` ```python prefix = "0x26aa394eea5630e07c48ae0c9558cef7" # twox128("System") response = requests.post( "https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY", headers={"Content-Type": "application/json"}, data=json.dumps({ "jsonrpc": "2.0", "method": "state_getKeys", "params": [prefix, None], "id": 1, }), timeout=10, ) keys = response.json()["result"] print(f"Returned {len(keys)} keys") ``` ```javascript const prefix = '0x26aa394eea5630e07c48ae0c9558cef7'; // Module: System const body = { jsonrpc: '2.0', method: 'state_getKeys', params: [prefix, null], id: 1 }; const keys = await fetch('https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then((r) => r.json()); console.log(keys.result.length); ``` ## Tips - Use `state_getKeysPaged` for large datasets; it adds pagination controls to avoid heavy responses. - Combine with `state_getStorage` to fetch the associated values for each discovered key. - Remember that map storage keys append hashes and encoded keys (e.g., `Blake2_128Concat(AccountId)`), so you may need to post-process the suffix. --- ## state_getKeysPaged - Enjin RPC Method # state_getKeysPaged Returns storage keys with pagination on Enjin. ## Use Cases - **Storage iteration** - Enumerate storage map entries - **Data export** - Bulk export chain data for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Account enumeration** - List all accounts ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `prefix` | `String` | Yes | Storage key prefix | | `count` | `Number` | Yes | Maximum keys to return | | `startKey` | `String` | No | Key to start after | | `blockHash` | `String` | No | Block hash for historical query | ## Request ```json { "jsonrpc": "2.0", "method": "state_getKeysPaged", "params": ["0x...", 100], "id": 1 } ``` ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getKeysPaged", "params": ["0x26aa394eea5630e07c48ae0c9558cef7", 100], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get all accounts (paginated) const keys = await api.rpc.state.getKeysPaged( api.query.system.account.keyPrefix(), 100 ); console.log('Found accounts:', keys.length); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Get storage value - [`state_queryStorageAt`](./state_queryStorageAt) - Batch storage query --- ## state_getMetadata - Enjin RPC Method # state_getMetadata Returns the runtime metadata on Enjin. ## Use Cases - **Runtime introspection** - Discover available pallets and calls - **Extrinsic building** - Get call and type information for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Storage key generation** - Build storage keys from metadata - **Client generation** - Auto-generate typed APIs ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash for historical metadata | ## Request ```json { "jsonrpc": "2.0", "method": "state_getMetadata", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getMetadata", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get runtime metadata const metadata = await api.rpc.state.getMetadata(); // List available pallets const pallets = metadata.asLatest.pallets.map(p => p.name.toString()); console.log('Available pallets:', pallets); // Get specific pallet info const systemPallet = metadata.asLatest.pallets.find(p => p.name.toString() === 'System'); console.log('System pallet calls:', systemPallet.calls.isSome ? 'Available' : 'None'); await api.disconnect(); ``` ```python def get_metadata(): url = 'https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'state_getMetadata', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] metadata_hex = get_metadata() print(f'Metadata length: {len(metadata_hex)} bytes') ``` ## Related Methods - [`state_getRuntimeVersion`](./state_getRuntimeVersion) - Get runtime version - [`state_getStorage`](./state_getStorage) - Query storage --- ## state_getRuntimeVersion - Enjin RPC Method # state_getRuntimeVersion Returns the runtime version on Enjin. ## Use Cases - **Version checking** - Verify runtime compatibility - **Upgrade detection** - Monitor for runtime upgrades on high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Client compatibility** - Ensure API compatibility ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash for historical version | ## Request ```json { "jsonrpc": "2.0", "method": "state_getRuntimeVersion", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getRuntimeVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const version = await api.rpc.state.getRuntimeVersion(); console.log('Spec name:', version.specName.toString()); console.log('Spec version:', version.specVersion.toNumber()); console.log('Impl version:', version.implVersion.toNumber()); await api.disconnect(); ``` ```python def get_runtime_version(): url = 'https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'state_getRuntimeVersion', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] version = get_runtime_version() print(f"Spec: {version['specName']} v{version['specVersion']}") ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata - [`system_version`](./system_version) - Get node version --- ## state_getStorage - Enjin RPC Method # state_getStorage Returns a storage entry at a specific key on Enjin. > **Why Enjin?** Build on the purpose-built NFT blockchain with protocol-level minting and $100M Metaverse Fund with NFT functions at protocol level, Fuel Tanks for subsidized fees, 700-1000 TPS, 6-second finality, and ERC-1155 standard pioneer. ## Use Cases - **State queries** - Read on-chain storage values - **Account balances** - Query account data for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Pallet storage** - Access runtime storage items - **Historical state** - Query state at specific blocks ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `key` | `String` | Yes | Storage key (hex-encoded) | | `blockHash` | `String` | No | Block hash for historical query | ## Request ```json { "jsonrpc": "2.0", "method": "state_getStorage", "params": [""], "id": 1 } ``` ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getStorage", "params": [""], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query account balance const account = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const accountInfo = await api.query.system.account(account); console.log('Free balance:', accountInfo.data.free.toString()); // Query at specific block const blockHash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'; const historicalBalance = await api.query.system.account.at(blockHash, account); console.log('Historical balance:', historicalBalance.data.free.toString()); await api.disconnect(); ``` ```python def get_storage(key, block_hash=None): url = 'https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY' params = [key] if block_hash is None else [key, block_hash] payload = { 'jsonrpc': '2.0', 'method': 'state_getStorage', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] # Query :code storage (runtime wasm) storage_key = '' value = get_storage(storage_key) print(f'Storage value: {value[:66]}...' if value else 'None') ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata - [`state_getKeysPaged`](./state_getKeysPaged) - Enumerate storage keys --- ## state_queryStorageAt - Enjin RPC Method # state_queryStorageAt Query multiple storage keys at a specific block on Enjin. ## Use Cases - **Batch queries** - Efficiently query multiple storage items - **Snapshot state** - Get consistent multi-key state for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Data analysis** - Compare storage across blocks ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `keys` | `Array` | Yes | Array of storage keys | | `blockHash` | `String` | No | Block hash for query | ## Request ```json { "jsonrpc": "2.0", "method": "state_queryStorageAt", "params": [[""]], "id": 1 } ``` ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_queryStorageAt", "params": [[""]], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query multiple accounts at once const accounts = ['5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY']; const entries = await api.query.system.account.multi(accounts); entries.forEach((info, idx) => { console.log(`Account ${idx}: ${info.data.free.toString()}`); }); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Single storage query - [`state_getKeysPaged`](./state_getKeysPaged) - Enumerate keys --- ## system_chain - Enjin RPC Method # system_chain Returns the chain name on Enjin. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const chain = await api.rpc.system.chain(); console.log('Chain:', chain.toString()); await api.disconnect(); ``` ## Related Methods - [`system_name`](./system_name) - Get node implementation name - [`system_version`](./system_version) - Get node version --- ## system_health - Enjin RPC Method # system_health Returns the health status of the Enjin node. ## Use Cases - **Health checks** - Monitor node availability - **Load balancing** - Route traffic based on health for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **Sync status** - Verify node is synced ## Parameters This method accepts no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `peers` | `Number` | Connected peer count | | `isSyncing` | `Boolean` | Whether node is syncing | | `shouldHavePeers` | `Boolean` | Whether node should have peers | ## Request ```json { "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const health = await api.rpc.system.health(); console.log('Peers:', health.peers.toNumber()); console.log('Is syncing:', health.isSyncing.isTrue); await api.disconnect(); ``` ```python def get_health(): url = 'https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'system_health', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] health = get_health() print(f"Peers: {health['peers']}") print(f"Syncing: {health['isSyncing']}") ``` ## Related Methods - [`system_version`](./system_version) - Get node version - [`system_chain`](./system_chain) - Get chain name --- ## system_name - Enjin RPC Method # system_name Returns the node implementation name on Enjin. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_name", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_name", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const name = await api.rpc.system.name(); console.log('Node name:', name.toString()); await api.disconnect(); ``` ## Related Methods - [`system_version`](./system_version) - Get node version - [`system_chain`](./system_chain) - Get chain name --- ## system_properties - Enjin RPC Method # system_properties Returns chain properties including token symbol and decimals on Enjin. ## Use Cases - **Token formatting** - Get decimals and symbol for high-volume NFT minting (2,000+ per tx), gaming assets, and cross-chain NFT transfers via Paratoken standard - **UI configuration** - Configure wallets and dApps - **Address formatting** - Get SS58 prefix ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_properties", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_properties", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const props = await api.rpc.system.properties(); console.log('Token symbol:', props.tokenSymbol.toString()); console.log('Token decimals:', props.tokenDecimals.toString()); console.log('SS58 prefix:', props.ss58Format.toString()); await api.disconnect(); ``` ## Related Methods - [`system_chain`](./system_chain) - Get chain name - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## system_version - Enjin RPC Method # system_version Returns the node implementation version on Enjin. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_version", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_version", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-enjin-matrixchain.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const version = await api.rpc.system.version(); console.log('Version:', version.toString()); await api.disconnect(); ``` ## Related Methods - [`system_chain`](./system_chain) - Get chain name - [`state_getRuntimeVersion`](./state_getRuntimeVersion) - Get runtime version --- ## debug_traceBlock - Ethereum RPC Method # debug_traceBlock Traces all transactions in a block on Ethereum by block RLP. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Analyze transaction execution step-by-step - **Smart contract analysis** - Debug contract interactions - **Security auditing** - Trace internal calls for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockRlp` | `DATA` | Yes | RLP-encoded block data | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); // Use debug_traceBlockByNumber instead (more practical) const traces = await provider.send('debug_traceBlockByNumber', ['latest', {}]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by block number - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by block hash --- ## debug_traceBlockByHash - Ethereum RPC Method # debug_traceBlockByHash Traces all transactions in a block on Ethereum by block hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd'; const traces = await provider.send('debug_traceBlockByHash', [blockHash, { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by number - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceBlockByNumber - Ethereum RPC Method # debug_traceBlockByNumber Traces all transactions in a block on Ethereum by block number. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('debug_traceBlockByNumber', ['latest', { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by hash - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceCall - Ethereum RPC Method # debug_traceCall Traces a call without creating a transaction on Ethereum. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction simulation** - Debug before sending - **Gas analysis** - Analyze gas usage per opcode - **Contract debugging** - Step through execution for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `call` | `Object` | Yes | Call object (same as eth_call) | | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ { "to": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "data": "0x70a08231000000000000000000000000d8dA6BF26964aF9D7eEd9e03E53415D37aA96045" }, "latest", {} ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ {"to": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "data": "0x70a08231000000000000000000000000d8dA6BF26964aF9D7eEd9e03E53415D37aA96045"}, "latest", {"tracer": "callTracer"} ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const trace = await provider.send('debug_traceCall', [ { to: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', data: '0x70a08231000000000000000000000000d8dA6BF26964aF9D7eEd9e03E53415D37aA96045' }, 'latest', { tracer: 'callTracer' } ]); console.log('Trace:', trace); ``` ## Related Methods - [`eth_call`](./eth_call) - Execute call without trace - [`debug_traceTransaction`](./debug_traceTransaction) - Trace actual transaction --- ## debug_traceTransaction - Ethereum RPC Method # debug_traceTransaction Traces a transaction execution on Ethereum by transaction hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Understand exactly what happened - **Failure analysis** - Find where and why a transaction reverted - **Gas optimization** - Analyze gas usage for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Tracer Options - `{}` - Default opcode tracer (verbose) - `{ tracer: "callTracer" }` - Call tree tracer - `{ tracer: "prestateTracer" }` - Pre-state tracer ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a'; // Call tracer - shows internal calls const callTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'callTracer' } ]); console.log('Type:', callTrace.type); console.log('From:', callTrace.from); console.log('To:', callTrace.to); console.log('Gas used:', parseInt(callTrace.gasUsed, 16)); // Prestate tracer - shows state before execution const prestateTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'prestateTracer' } ]); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a' # Call tracer trace = w3.provider.make_request('debug_traceTransaction', [ tx_hash, {'tracer': 'callTracer'} ]) print(f'Trace type: {trace["result"]["type"]}') print(f'Gas used: {int(trace["result"]["gasUsed"], 16)}') ``` ## Related Methods - [`debug_traceCall`](./debug_traceCall) - Trace without executing - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace entire block --- ## eth_accounts - Ethereum RPC Method # eth_accounts Returns a list of addresses owned by the client on Ethereum. > **Why Ethereum?** Build on the world's leading smart contract platform with the largest developer ecosystem with battle-tested security, institutional adoption, and unmatched ecosystem with $166B+ TVL. ## Important Note On public RPC endpoints like Dwellir, `eth_accounts` returns an empty array because the node does not hold any private keys. This method is primarily useful for: - Local development nodes (Ganache, Hardhat, Anvil) - Private nodes with managed accounts - Wallet provider connections (MetaMask injects accounts) ## When to Use This Method `eth_accounts` is relevant for DeFi developers, NFT creators, and enterprise blockchain teams in specific scenarios: - **Development Testing** — Retrieve test accounts from local nodes - **Wallet Detection** — Check if a wallet provider has connected accounts - **Client Verification** — Confirm node account access capabilities ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `Array` | List of 20-byte account addresses owned by the client | **Return format**: Array of `0x` prefixed hexadecimal addresses (typically empty for public nodes) ## Request ```json { "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 } ``` ## Response ### Successful Response (Public Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [] } ``` ### Successful Response (Local Development Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [ "0x407d73d8a49eeb85d32cf465507dd71d507100c1", "0x85d32cf465507dd71d507100c1407d73d8a49eeb" ] } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_accounts', params: [], id: 1 }) }); const { result } = await response.json(); console.log('Accounts:', result); // Using ethers.js const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const accounts = await provider.listAccounts(); console.log('Accounts:', accounts); ``` ```python def get_accounts(): response = requests.post( 'https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_accounts', 'params': [], 'id': 1 } ) return response.json()['result'] accounts = get_accounts() print(f'Accounts: {accounts}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) print(f'Accounts: {w3.eth.accounts}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/rpc" ) func main() { client, err := rpc.Dial("https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } var accounts []string err = client.CallContext(context.Background(), &accounts, "eth_accounts") if err != nil { log.Fatal(err) } fmt.Printf("Accounts: %v\n", accounts) } ``` ## Common Use Cases ### 1. Development Environment Detection Check if running against a development node with test accounts: ```javascript async function isDevEnvironment(provider) { const accounts = await provider.listAccounts(); return accounts.length > 0; } const isDev = await isDevEnvironment(provider); if (isDev) { console.log('Development environment detected'); } ``` ### 2. Wallet Connection Check Verify wallet provider has connected accounts: ```javascript async function checkWalletConnection() { if (typeof window.ethereum === 'undefined') { return { connected: false, reason: 'No wallet detected' }; } const accounts = await window.ethereum.request({ method: 'eth_accounts' }); return { connected: accounts.length > 0, accounts: accounts }; } ``` ### 3. Fallback Account Selection Use first available account or request connection: ```javascript async function getActiveAccount() { // Check existing connections let accounts = await window.ethereum.request({ method: 'eth_accounts' }); // Request connection if no accounts if (accounts.length === 0) { accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); } return accounts[0] || null; } ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32601 | Method not found | Node may not support this method | | -32603 | Internal error | Retry with exponential backoff | ```javascript async function safeGetAccounts(provider) { try { const accounts = await provider.listAccounts(); return { success: true, accounts }; } catch (error) { if (error.code === -32601) { console.warn('eth_accounts not supported on this node'); return { success: false, accounts: [], reason: 'unsupported' }; } throw error; } } ``` ## Related Methods - [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102) — Request wallet connection (browser wallets) - [`eth_getBalance`](./eth_getBalance) — Get account balance - [`eth_getTransactionCount`](./eth_getTransactionCount) — Get account nonce --- ## eth_blockNumber - Ethereum RPC Method # eth_blockNumber Returns the number of the most recent block on Ethereum. > **Why Ethereum?** Build on the world's leading smart contract platform with the largest developer ecosystem with battle-tested security, institutional adoption, and unmatched ecosystem with $166B+ TVL. ## When to Use This Method `eth_blockNumber` is fundamental for DeFi developers, NFT creators, and enterprise blockchain teams: - **Syncing Applications** — Keep your dApp in sync with the latest Ethereum blockchain state - **Transaction Monitoring** — Verify confirmations by comparing block numbers - **Event Filtering** — Set the correct block range for querying logs on DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps - **Health Checks** — Monitor node connectivity and sync status ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `QUANTITY` | Hexadecimal string representing the current block number | **Return format**: `0x` prefixed hexadecimal (e.g., `0x5BAD55` = 6,008,149 in decimal) ## Request ```json { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } ``` ## Response ### Successful Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5BAD55" } ``` ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error" } } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }) }); const { result } = await response.json(); const blockNumber = parseInt(result, 16); console.log('Ethereum block:', blockNumber); // Using ethers.js const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const blockNumber = await provider.getBlockNumber(); console.log('Ethereum block:', blockNumber); ``` ```python def get_block_number(): response = requests.post( 'https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_blockNumber', 'params': [], 'id': 1 } ) result = response.json()['result'] return int(result, 16) block_number = get_block_number() print(f'Ethereum block: {block_number}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) print(f'Ethereum block: {w3.eth.block_number}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockNumber, err := client.BlockNumber(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Ethereum block: %d\n", blockNumber) } ``` ## Common Use Cases ### 1. Block Confirmation Counter Monitor transaction confirmations on Ethereum: ```javascript async function getConfirmations(provider, txHash) { const tx = await provider.getTransaction(txHash); if (!tx || !tx.blockNumber) return 0; const currentBlock = await provider.getBlockNumber(); return currentBlock - tx.blockNumber + 1; } // Wait for specific confirmations async function waitForConfirmations(provider, txHash, confirmations = 6) { let currentConfirmations = 0; while (currentConfirmations < confirmations) { currentConfirmations = await getConfirmations(provider, txHash); console.log(`Confirmations: ${currentConfirmations}/${confirmations}`); await new Promise(r => setTimeout(r, 2000)); } return true; } ``` ### 2. Event Log Filtering Query events from recent blocks on Ethereum: ```javascript async function getRecentEvents(provider, contract, eventName, blockRange = 100) { const currentBlock = await provider.getBlockNumber(); const fromBlock = currentBlock - blockRange; const filter = contract.filters[eventName](); const events = await contract.queryFilter(filter, fromBlock, currentBlock); return events; } ``` ### 3. Node Health Monitoring Check if your Ethereum node is synced: ```javascript async function checkNodeHealth(provider) { try { const blockNumber = await provider.getBlockNumber(); const block = await provider.getBlock(blockNumber); const now = Date.now() / 1000; const blockAge = now - block.timestamp; if (blockAge > 60) { console.warn(`Node may be behind. Last block was ${blockAge}s ago`); return false; } console.log(`Node healthy. Latest block: ${blockNumber}`); return true; } catch (error) { console.error('Node unreachable:', error); return false; } } ``` ## Performance Optimization ### Caching Strategy Cache block numbers to reduce API calls: ```javascript class BlockNumberCache { constructor(ttl = 2000) { this.cache = null; this.timestamp = 0; this.ttl = ttl; } async get(provider) { const now = Date.now(); if (this.cache && (now - this.timestamp) < this.ttl) { return this.cache; } this.cache = await provider.getBlockNumber(); this.timestamp = now; return this.cache; } invalidate() { this.cache = null; this.timestamp = 0; } } const blockCache = new BlockNumberCache(); ``` ### Batch Requests Combine with other calls for efficiency: ```javascript const batch = [ { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }, { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 }, { jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 } ]; const response = await fetch('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await response.json(); ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32603 | Internal error | Retry with exponential backoff | | -32005 | Rate limit exceeded | Implement rate limiting client-side | | -32000 | Execution reverted | Check node sync status | ```javascript async function safeGetBlockNumber(provider, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await provider.getBlockNumber(); } catch (error) { if (error.code === -32005) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } else if (i === maxRetries - 1) { throw error; } } } } ``` ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) — Get full block details by number - [`eth_getBlockByHash`](./eth_getBlockByHash) — Get block details by hash - [`eth_syncing`](./eth_syncing) — Check if node is still syncing --- ## eth_call - Ethereum RPC Method # eth_call Executes a new message call immediately without creating a transaction on Ethereum. Used for reading smart contract state. > **Why Ethereum?** Build on the world's leading smart contract platform with the largest developer ecosystem with battle-tested security, institutional adoption, and unmatched ecosystem with $166B+ TVL. ## Use Cases The `eth_call` method is essential for: - **Reading contract state** - Query view/pure functions - **Simulating transactions** - Test execution without gas costs - **DeFi integrations** - Check prices, balances, allowances for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps - **Complex queries** - Execute multi-step contract logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | 20-byte address executing the call | | `to` | `DATA` | Yes | 20-byte contract address | | `gas` | `QUANTITY` | No | Gas limit for the call | | `gasPrice` | `QUANTITY` | No | Gas price in wei | | `value` | `QUANTITY` | No | Value to send in wei | | `data` | `DATA` | Yes | Encoded function call data | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_call", "params": [ { "to": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "data": "0x70a08231000000000000000000000000d8dA6BF26964aF9D7eEd9e03E53415D37aA96045" }, "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | The return value of the executed contract function | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000" } ``` ## Code Examples ```bash # Call ERC20 balanceOf function curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{ "to": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "data": "0x70a08231000000000000000000000000d8dA6BF26964aF9D7eEd9e03E53415D37aA96045" }, "latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); // ERC20 ABI for common functions const ERC20_ABI = [ "function balanceOf(address owner) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function totalSupply() view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)" ]; // Read ERC20 token balance async function getTokenBalance(tokenAddress, walletAddress) { const contract = new Contract(tokenAddress, ERC20_ABI, provider); const balance = await contract.balanceOf(walletAddress); const decimals = await contract.decimals(); const symbol = await contract.symbol(); return { raw: balance.toString(), formatted: (Number(balance) / Math.pow(10, decimals)).toFixed(4), symbol: symbol }; } // Direct eth_call async function directCall(to, data) { const result = await provider.call({ to, data }); return result; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) def get_erc20_balance(token_address, wallet_address): # balanceOf(address) selector function_signature = "balanceOf(address)" function_selector = w3.keccak(text=function_signature)[:4].hex() # Encode address parameter encoded_address = wallet_address[2:].lower().zfill(64) data = function_selector + encoded_address # Make the call result = w3.eth.call({ 'to': token_address, 'data': data }) return int(result.hex(), 16) balance = get_erc20_balance( '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045' ) print(f'Balance: {balance}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045") data := common.FromHex("0x70a08231000000000000000000000000d8dA6BF26964aF9D7eEd9e03E53415D37aA96045") msg := ethereum.CallMsg{ To: &contractAddress, Data: data, } result, err := client.CallContract(context.Background(), msg, nil) if err != nil { log.Fatal(err) } fmt.Printf("Result: 0x%x\n", result) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Contract function reverted | | -32602 | Invalid parameters | Invalid data encoding | | -32015 | VM execution error | Contract logic error | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas for transaction - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send actual transaction --- ## eth_chainId - Ethereum RPC Method # eth_chainId Returns the chain ID used for transaction signing on Ethereum. > **Why Ethereum?** Build on the world's leading smart contract platform with the largest developer ecosystem with battle-tested security, institutional adoption, and unmatched ecosystem with $166B+ TVL. ## Use Cases The `eth_chainId` method is essential for: - **Transaction signing** - Ensure transactions are signed for the correct network - **Network verification** - Confirm connection to the expected chain - **Multi-chain apps** - Handle different networks programmatically - **Wallet integration** - Validate network before transactions ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Chain ID in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1" } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const network = await provider.getNetwork(); console.log('Chain ID:', network.chainId); // Verify network before transaction async function verifyNetwork(expectedChainId) { const network = await provider.getNetwork(); if (network.chainId !== BigInt(expectedChainId)) { throw new Error(`Wrong network. Expected ${expectedChainId}, got ${network.chainId}`); } return true; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) chain_id = w3.eth.chain_id print(f'Chain ID: {chain_id}') # Verify network def verify_network(expected_chain_id): chain_id = w3.eth.chain_id if chain_id != expected_chain_id: raise ValueError(f'Wrong network. Expected {expected_chain_id}, got {chain_id}') return True ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } chainID, err := client.ChainID(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Chain ID: %d\n", chainID) } ``` ## Related Methods - [`net_version`](./net_version) - Get network version - [`eth_syncing`](./eth_syncing) - Check sync status --- ## eth_coinbase - Get coinbase address(Ethereum) # eth_coinbase Get coinbase address on the Ethereum network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_coinbase](https://ethereum.org/developers/docs/apis/json-rpc/#eth_coinbase) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_coinbase", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_coinbase', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Ethereum documentation](/docs/ethereum).* --- ## eth_estimateGas - Ethereum RPC Method # eth_estimateGas Estimates the gas necessary to execute a transaction on Ethereum. > **Why Ethereum?** Build on the world's leading smart contract platform with the largest developer ecosystem with battle-tested security, institutional adoption, and unmatched ecosystem with $166B+ TVL. ## Use Cases The `eth_estimateGas` method is essential for: - **Transaction preparation** - Set appropriate gas limits - **Cost estimation** - Calculate transaction costs before sending - **Error detection** - Identify reverts before spending gas - **DeFi operations** - Estimate costs for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | Sender address | | `to` | `DATA` | No | Recipient address | | `gas` | `QUANTITY` | No | Gas limit | | `gasPrice` | `QUANTITY` | No | Gas price | | `value` | `QUANTITY` | No | Value in wei | | `data` | `DATA` | No | Transaction data | ## Request ```json { "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "to": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "value": "0x1" }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Estimated gas amount in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5208" } ``` **Note**: `0x5208` = 21000 gas (standard ETH transfer) ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "to": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "value": "0x1" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); // Estimate simple transfer async function estimateTransfer(to, value) { const gasEstimate = await provider.estimateGas({ to: to, value: parseEther(value) }); console.log('Estimated gas:', gasEstimate.toString()); return gasEstimate; } // Estimate contract call async function estimateContractCall(contract, method, args) { const gasEstimate = await contract[method].estimateGas(...args); console.log('Estimated gas:', gasEstimate.toString()); // Add 20% buffer for safety return gasEstimate * 120n / 100n; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) def estimate_transfer(to, value_in_ether): gas_estimate = w3.eth.estimate_gas({ 'to': to, 'value': w3.to_wei(value_in_ether, 'ether') }) print(f'Estimated gas: {gas_estimate}') return gas_estimate def estimate_contract_call(contract, method, args): func = getattr(contract.functions, method) gas_estimate = func(*args).estimate_gas() # Add 20% buffer return int(gas_estimate * 1.2) # Estimate simple transfer gas = estimate_transfer('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', 0.1) ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } toAddress := common.HexToAddress("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045") msg := ethereum.CallMsg{ To: &toAddress, Value: big.NewInt(1000000000000000000), } gasLimit, err := client.EstimateGas(context.Background(), msg) if err != nil { log.Fatal(err) } fmt.Printf("Estimated gas: %d\n", gasLimit) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Transaction would fail | | -32602 | Invalid params | Invalid transaction parameters | **Tip**: If estimation fails, the transaction would likely revert if sent. ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_feeHistory - Ethereum RPC Method # eth_feeHistory Returns historical gas information on Ethereum for fee estimation. ## Use Cases - **Fee prediction** - Estimate future gas prices based on history - **Gas analytics** - Analyze fee trends over time - **Optimal timing** - Find best times for transactions on DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockCount` | `QUANTITY` | Yes | Number of blocks in the range | | `newestBlock` | `QUANTITY\|TAG` | Yes | Highest block of the range | | `rewardPercentiles` | `Array` | Yes | Percentiles to sample for priority fees | ## Request ```json { "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const feeHistory = await provider.send('eth_feeHistory', ['0xa', 'latest', [25, 50, 75]]); console.log('Base fees:', feeHistory.baseFeePerGas.map(f => formatUnits(f, 'gwei'))); console.log('Reward (25th percentile):', feeHistory.reward.map(r => formatUnits(r[0], 'gwei'))); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) fee_history = w3.eth.fee_history(10, 'latest', [25, 50, 75]) print(f'Base fees: {[w3.from_wei(f, "gwei") for f in fee_history["baseFeePerGas"]]}') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee --- ## eth_gasPrice - Ethereum RPC Method # eth_gasPrice Returns the current gas price on Ethereum in wei. > **Why Ethereum?** Build on the world's leading smart contract platform with the largest developer ecosystem with battle-tested security, institutional adoption, and unmatched ecosystem with $166B+ TVL. ## Use Cases The `eth_gasPrice` method is essential for: - **Transaction pricing** - Set appropriate gas prices - **Cost estimation** - Calculate transaction costs before sending - **Gas monitoring** - Track network congestion - **DeFi operations** - Optimize costs for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Current gas price in wei (hexadecimal) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x3b9aca00" } ``` **Note**: `0x3b9aca00` = 1 Gwei (1,000,000,000 wei) ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); const gasPrice = feeData.gasPrice; console.log('Gas Price:', formatUnits(gasPrice, 'gwei'), 'Gwei'); // Calculate transaction cost async function estimateTransactionCost(gasLimit) { const feeData = await provider.getFeeData(); const cost = feeData.gasPrice * BigInt(gasLimit); return formatUnits(cost, 'ether'); } const cost = await estimateTransactionCost(21000); console.log('Transfer cost:', cost, 'ETH'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) gas_price = w3.eth.gas_price print(f'Gas Price: {w3.from_wei(gas_price, "gwei")} Gwei') # Calculate transaction cost def estimate_transaction_cost(gas_limit): gas_price = w3.eth.gas_price cost = gas_price * gas_limit return w3.from_wei(cost, 'ether') cost = estimate_transaction_cost(21000) print(f'Transfer cost: {cost} ETH') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } gasPrice, err := client.SuggestGasPrice(context.Background()) if err != nil { log.Fatal(err) } // Convert to Gwei gwei := new(big.Float).Quo( new(big.Float).SetInt(gasPrice), big.NewFloat(1e9), ) fmt.Printf("Gas Price: %f Gwei\n", gwei) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32603 | Internal error | Node error | ## Related Methods - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee (EIP-1559) - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas needed --- ## eth_getBalance - Ethereum RPC Method # eth_getBalance Returns the balance of a given address on Ethereum. > **Why Ethereum?** Build on the world's leading smart contract platform with the largest developer ecosystem with battle-tested security, institutional adoption, and unmatched ecosystem with $166B+ TVL. ## Use Cases The `eth_getBalance` method is essential for: - **Wallet applications** - Display user balances - **Transaction validation** - Check if account has sufficient funds - **DeFi applications** - Monitor collateral and liquidity for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps - **Account monitoring** - Track balance changes over time ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address to check balance for | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Integer of the current balance in wei (hexadecimal) | **Note**: 1 native token = 10^18 wei. Convert using `balance / 10^18`. ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1a055690d9db80000" } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'; const balanceWei = await provider.getBalance(address); const balance = formatEther(balanceWei); console.log(`Balance: ${balance}`); // Get balance at specific block const historicalBalance = await provider.getBalance(address, 1000000); console.log(`Historical balance: ${formatEther(historicalBalance)}`); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045' balance_wei = w3.eth.get_balance(address) balance = w3.from_wei(balance_wei, 'ether') print(f'Balance: {balance}') # Get balance at specific block historical_balance = w3.eth.get_balance(address, block_identifier=1000000) print(f'Historical balance: {w3.from_wei(historical_balance, "ether")}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045") balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } // Convert to ether fbalance := new(big.Float).SetInt(balance) ethValue := new(big.Float).Quo(fbalance, big.NewFloat(1e18)) fmt.Printf("Balance: %f\n", ethValue) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid address format or block parameter | | -32000 | Execution error | Node execution error | ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_getTransactionCount`](./eth_getTransactionCount) - Get account nonce --- ## eth_getBlockByHash - Ethereum RPC Method # eth_getBlockByHash Returns information about a block by hash on Ethereum. > **Why Ethereum?** Build on the world's leading smart contract platform with the largest developer ecosystem with battle-tested security, institutional adoption, and unmatched ecosystem with $166B+ TVL. ## Use Cases The `eth_getBlockByHash` method is essential for: - **Block verification** - Verify block data using its unique hash - **Chain reorganization handling** - Track blocks during reorgs - **Cross-chain bridges** - Verify block finality for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps - **Deterministic queries** - Get consistent block data regardless of chain state ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd", false ], "id": 1 } ``` ## Returns Returns the same block object as `eth_getBlockByNumber`, or `null` if no block is found. | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used | | `transactions` | `Array` | Transaction objects or hashes | ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd", false ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd'; const block = await provider.getBlock(blockHash); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) block_hash = '0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd' block = w3.eth.get_block(block_hash) print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockHash := common.HexToHash("0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd") block, err := client.BlockByHash(context.Background(), blockHash) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block hash format | | -32000 | Block not found | Block with this hash does not exist | ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) - Get block by number - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number --- ## eth_getBlockByNumber - Ethereum RPC Method # eth_getBlockByNumber Returns information about a block by block number on Ethereum. > **Why Ethereum?** Build on the world's leading smart contract platform with the largest developer ecosystem with battle-tested security, institutional adoption, and unmatched ecosystem with $166B+ TVL. ## Use Cases The `eth_getBlockByNumber` method is essential for: - **Block explorers** - Display complete block information - **Transaction indexers** - Process all transactions in a block - **Analytics platforms** - Analyze blockchain data for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps - **Timestamp verification** - Get block timestamps for time-based logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used by all transactions | | `gasLimit` | `QUANTITY` | Maximum gas allowed in block | | `transactions` | `Array` | Array of transaction objects or hashes | | `baseFeePerGas` | `QUANTITY` | Base fee per gas (EIP-1559) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": { "number": "0x5BAD55", "hash": "0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd", "parentHash": "0x...", "timestamp": "0x64d8f6d0", "gasUsed": "0x1234", "gasLimit": "0x1c9c380", "transactions": [], "baseFeePerGas": "0x5f5e100" } } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); // Get latest block const block = await provider.getBlock('latest'); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); console.log('Transactions:', block.transactions.length); // Get block with full transactions const blockWithTxs = await provider.getBlock('latest', true); for (const tx of blockWithTxs.prefetchedTransactions) { console.log('Transaction:', tx.hash); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) # Get latest block block = w3.eth.get_block('latest') print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') print(f'Transactions: {len(block.transactions)}') # Get block with full transactions block_full = w3.eth.get_block('latest', full_transactions=True) for tx in block_full.transactions: print(f'Transaction: {tx.hash.hex()}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } // Get latest block block, err := client.BlockByNumber(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) fmt.Printf("Timestamp: %d\n", block.Time()) fmt.Printf("Transactions: %d\n", len(block.Transactions())) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block number or parameter format | | -32000 | Block not found | Block does not exist | ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number - [`eth_getBlockByHash`](./eth_getBlockByHash) - Get block by hash - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_getCode - Ethereum RPC Method # eth_getCode Returns the bytecode at a given address on Ethereum. > **Why Ethereum?** Build on the world's leading smart contract platform with the largest developer ecosystem with battle-tested security, institutional adoption, and unmatched ecosystem with $166B+ TVL. ## Use Cases The `eth_getCode` method is essential for: - **Contract verification** - Check if address is a contract - **Security analysis** - Verify deployed bytecode matches expected - **DeFi integrations** - Validate contracts before interactions - **Protocol analysis** - Analyze contract deployments for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Contract bytecode or `0x` if EOA | ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'; const code = await provider.getCode(address); if (code === '0x') { console.log('Address is an EOA (externally owned account)'); } else { console.log('Address is a contract'); console.log('Bytecode length:', code.length); } // Check if address is a contract async function isContract(address) { const code = await provider.getCode(address); return code !== '0x'; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045' code = w3.eth.get_code(address) if code == b'': print('Address is an EOA') else: print('Address is a contract') print(f'Bytecode length: {len(code.hex())}') # Check if address is a contract def is_contract(address): code = w3.eth.get_code(address) return code != b'' ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045") code, err := client.CodeAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } if len(code) == 0 { fmt.Println("Address is an EOA") } else { fmt.Printf("Contract bytecode length: %d\n", len(code)) } } ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_getStorageAt`](./eth_getStorageAt) - Get contract storage --- ## eth_getFilterChanges - Ethereum RPC Method # eth_getFilterChanges Polling method for a filter on Ethereum, returns an array of logs since last poll. ## Use Cases - **Event streaming** - Get new events incrementally - **Real-time monitoring** - Track contract activity for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps - **Efficient indexing** - Process only new events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); // Poll loop async function pollFilter(filterId, interval = 2000) { while (true) { const changes = await provider.send('eth_getFilterChanges', [filterId]); if (changes.length > 0) { console.log('New events:', changes); } await new Promise(r => setTimeout(r, interval)); } } ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter --- ## eth_getFilterLogs - Ethereum RPC Method # eth_getFilterLogs Returns an array of all logs matching filter with given ID on Ethereum. ## Use Cases - **Historical queries** - Get all matching logs for a filter - **Full event history** - Retrieve complete event data for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const logs = await provider.send('eth_getFilterLogs', [filterId]); console.log('All matching logs:', logs.length); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_getLogs - Ethereum RPC Method # eth_getLogs Returns an array of all logs matching a given filter object on Ethereum. > **Why Ethereum?** Build on the world's leading smart contract platform with the largest developer ecosystem with battle-tested security, institutional adoption, and unmatched ecosystem with $166B+ TVL. ## Use Cases The `eth_getLogs` method is essential for: - **Event indexing** - Track contract events for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps - **Token transfers** - Monitor ERC20/ERC721 transfers - **DeFi analytics** - Track swaps, liquidity events, and more - **Notification systems** - Alert on specific on-chain events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block (default: `"latest"`) | | `toBlock` | `QUANTITY\|TAG` | No | Ending block (default: `"latest"`) | | `address` | `DATA\|Array` | No | Contract address(es) to filter | | `topics` | `Array` | No | Array of topic filters | | `blockHash` | `DATA` | No | Filter single block by hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns Array of log objects: | Field | Type | Description | |-------|------|-------------| | `address` | `DATA` | Contract that emitted the log | | `topics` | `Array` | Array of indexed topics | | `data` | `DATA` | Non-indexed log data | | `blockNumber` | `QUANTITY` | Block number | | `transactionHash` | `DATA` | Transaction hash | | `logIndex` | `QUANTITY` | Log index in block | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": [{ "address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."], "data": "0x...", "blockNumber": "0x5BAD55", "transactionHash": "0x...", "logIndex": "0x0" }] } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); // Get Transfer events const TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'; async function getTransferEvents(tokenAddress, fromBlock, toBlock) { const logs = await provider.getLogs({ address: tokenAddress, topics: [TRANSFER_TOPIC], fromBlock: fromBlock, toBlock: toBlock }); return logs.map(log => ({ from: '0x' + log.topics[1].slice(26), to: '0x' + log.topics[2].slice(26), blockNumber: log.blockNumber, transactionHash: log.transactionHash })); } const events = await getTransferEvents( '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', 'latest', 'latest' ); console.log('Transfer events:', events); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' def get_transfer_events(token_address, from_block, to_block): logs = w3.eth.get_logs({ 'address': token_address, 'topics': [TRANSFER_TOPIC], 'fromBlock': from_block, 'toBlock': to_block }) events = [] for log in logs: events.append({ 'from': '0x' + log['topics'][1].hex()[26:], 'to': '0x' + log['topics'][2].hex()[26:], 'block': log['blockNumber'], 'tx': log['transactionHash'].hex() }) return events events = get_transfer_events( '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', 'latest', 'latest' ) print(f'Found {len(events)} transfer events') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045") transferTopic := common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef") query := ethereum.FilterQuery{ FromBlock: big.NewInt(0), ToBlock: nil, Addresses: []common.Address{contractAddress}, Topics: [][]common.Hash, } logs, err := client.FilterLogs(context.Background(), query) if err != nil { log.Fatal(err) } fmt.Printf("Found %d events\n", len(logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32005 | Query returned more than 10000 results | Reduce block range | | -32602 | Invalid params | Invalid filter parameters | ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create a filter for logs - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for new logs --- ## eth_getStorageAt - Ethereum RPC Method # eth_getStorageAt Returns the value from a storage position at a given address on Ethereum. ## Use Cases - **Contract analysis** - Read raw storage values - **State verification** - Verify contract state - **Security auditing** - Analyze storage layout for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps - **Protocol monitoring** - Track state changes ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte contract address | | `position` | `QUANTITY` | Yes | Storage slot position | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "0x0", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "0x0", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'; const slot = 0; const storage = await provider.getStorage(address, slot); console.log('Storage at slot 0:', storage); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045' storage = w3.eth.get_storage_at(address, 0) print(f'Storage at slot 0: {storage.hex()}') ``` ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_call`](./eth_call) - Call contract functions --- ## eth_getTransactionByHash - Ethereum RPC Method # eth_getTransactionByHash Returns the information about a transaction by transaction hash on Ethereum. > **Why Ethereum?** Build on the world's leading smart contract platform with the largest developer ecosystem with battle-tested security, institutional adoption, and unmatched ecosystem with $166B+ TVL. ## Use Cases The `eth_getTransactionByHash` method is essential for: - **Transaction tracking** - Get details of pending or confirmed transactions - **Payment verification** - Verify transaction parameters - **Debugging** - Analyze transaction data for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps - **Block explorers** - Display transaction information ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `hash` | `DATA` | Transaction hash | | `from` | `DATA` | Sender address | | `to` | `DATA` | Recipient address | | `value` | `QUANTITY` | Value in wei | | `gas` | `QUANTITY` | Gas provided | | `gasPrice` | `QUANTITY` | Gas price in wei | | `input` | `DATA` | Transaction input data | | `nonce` | `QUANTITY` | Sender's nonce | | `blockHash` | `DATA` | Block hash (null if pending) | | `blockNumber` | `QUANTITY` | Block number (null if pending) | ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a'; const tx = await provider.getTransaction(txHash); if (tx) { console.log('From:', tx.from); console.log('To:', tx.to); console.log('Value:', formatEther(tx.value)); console.log('Block:', tx.blockNumber); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a' tx = w3.eth.get_transaction(tx_hash) if tx: print(f'From: {tx["from"]}') print(f'To: {tx["to"]}') print(f'Value: {w3.from_wei(tx["value"], "ether")}') print(f'Block: {tx["blockNumber"]}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a") tx, isPending, err := client.TransactionByHash(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Pending: %v\n", isPending) fmt.Printf("Value: %s\n", tx.Value().String()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash format | ## Related Methods - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction receipt - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionCount - Ethereum RPC Method # eth_getTransactionCount Returns the number of transactions sent from an address on Ethereum (the nonce). ## Use Cases - **Transaction building** - Get correct nonce for new transactions - **Account analysis** - Count total outgoing transactions - **Nonce management** - Handle pending transaction queues - **Wallet operations** - Prepare transactions for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag (`pending` for next nonce) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'; const nonce = await provider.getTransactionCount(address); console.log('Nonce:', nonce); // Get pending nonce for new transaction const pendingNonce = await provider.getTransactionCount(address, 'pending'); console.log('Next nonce:', pendingNonce); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045' nonce = w3.eth.get_transaction_count(address) print(f'Nonce: {nonce}') # Get pending nonce pending_nonce = w3.eth.get_transaction_count(address, 'pending') print(f'Next nonce: {pending_nonce}') ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionReceipt - Ethereum RPC Method # eth_getTransactionReceipt Returns the receipt of a transaction by transaction hash on Ethereum. Receipt is only available for mined transactions. > **Why Ethereum?** Build on the world's leading smart contract platform with the largest developer ecosystem with battle-tested security, institutional adoption, and unmatched ecosystem with $166B+ TVL. ## Use Cases The `eth_getTransactionReceipt` method is essential for: - **Transaction confirmation** - Verify transaction was mined successfully - **Gas analysis** - Check actual gas used vs estimated - **Event parsing** - Read emitted events from logs - **Status verification** - Confirm success/failure for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `status` | `QUANTITY` | `1` (success) or `0` (failure) | | `transactionHash` | `DATA` | Transaction hash | | `blockHash` | `DATA` | Block hash | | `blockNumber` | `QUANTITY` | Block number | | `gasUsed` | `QUANTITY` | Gas used by this transaction | | `cumulativeGasUsed` | `QUANTITY` | Total gas used in block up to this tx | | `logs` | `Array` | Array of log objects | | `contractAddress` | `DATA` | Created contract address (if deployment) | ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a'; const receipt = await provider.getTransactionReceipt(txHash); if (receipt) { console.log('Status:', receipt.status === 1 ? 'Success' : 'Failed'); console.log('Gas Used:', receipt.gasUsed.toString()); console.log('Block:', receipt.blockNumber); console.log('Logs:', receipt.logs.length); // Parse specific events for (const log of receipt.logs) { console.log('Event from:', log.address); } } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a' receipt = w3.eth.get_transaction_receipt(tx_hash) if receipt: status = 'Success' if receipt['status'] == 1 else 'Failed' print(f'Status: {status}') print(f'Gas Used: {receipt["gasUsed"]}') print(f'Block: {receipt["blockNumber"]}') print(f'Logs: {len(receipt["logs"])}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a") receipt, err := client.TransactionReceipt(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Status: %d\n", receipt.Status) fmt.Printf("Gas Used: %d\n", receipt.GasUsed) fmt.Printf("Logs: %d\n", len(receipt.Logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash | **Note**: Returns `null` if transaction is not yet mined. ## Related Methods - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details - [`eth_getLogs`](./eth_getLogs) - Query logs by filter --- ## eth_hashrate - Get node hashrate(Ethereum) # eth_hashrate Get node hashrate on the Ethereum network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_hashrate](https://ethereum.org/developers/docs/apis/json-rpc/#eth_hashrate) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_hashrate", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_hashrate', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Ethereum documentation](/docs/ethereum).* --- ## eth_maxPriorityFeePerGas - Ethereum RPC Method # eth_maxPriorityFeePerGas Returns the current recommended priority fee per gas on Ethereum for EIP-1559 transactions. ## Use Cases - **EIP-1559 transactions** - Set appropriate priority fees - **Transaction acceleration** - Calculate tips for faster inclusion - **Gas optimization** - Balance speed vs cost for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); console.log('Max Priority Fee:', formatUnits(feeData.maxPriorityFeePerGas, 'gwei'), 'Gwei'); console.log('Max Fee Per Gas:', formatUnits(feeData.maxFeePerGas, 'gwei'), 'Gwei'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) priority_fee = w3.eth.max_priority_fee print(f'Max Priority Fee: {w3.from_wei(priority_fee, "gwei")} Gwei') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get legacy gas price - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data --- ## eth_mining - Check if node is mining(Ethereum) # eth_mining Check if node is mining on the Ethereum network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_mining](https://ethereum.org/developers/docs/apis/json-rpc/#eth_mining) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_mining', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Ethereum documentation](/docs/ethereum).* --- ## eth_newBlockFilter - Ethereum RPC Method # eth_newBlockFilter Creates a filter on Ethereum to notify when a new block arrives. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newBlockFilter', []); // Poll for new blocks const newBlocks = await provider.send('eth_getFilterChanges', [filterId]); console.log('New block hashes:', newBlocks); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_blockNumber`](./eth_blockNumber) - Get current block --- ## eth_newFilter - Ethereum RPC Method # eth_newFilter Creates a filter object on Ethereum to notify when state changes (logs). ## Use Cases - **Event monitoring** - Subscribe to contract events - **Real-time updates** - Track events for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps - **Indexing** - Build event indexes incrementally ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block | | `toBlock` | `QUANTITY\|TAG` | No | Ending block | | `address` | `DATA\|Array` | No | Contract address(es) | | `topics` | `Array` | No | Topic filters | ## Request ```json { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); // Create filter const filterId = await provider.send('eth_newFilter', [{ fromBlock: 'latest', address: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'] }]); // Poll for changes const changes = await provider.send('eth_getFilterChanges', [filterId]); console.log('New events:', changes); // Cleanup await provider.send('eth_uninstallFilter', [filterId]); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for changes - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_newPendingTransactionFilter - Ethereum RPC Method # eth_newPendingTransactionFilter Creates a filter on Ethereum to notify when new pending transactions arrive. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newPendingTransactionFilter', []); // Poll for pending transactions const pendingTxs = await provider.send('eth_getFilterChanges', [filterId]); console.log('Pending transaction hashes:', pendingTxs); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_protocolVersion - Get protocol version(Ethereum) # eth_protocolVersion Get protocol version on the Ethereum network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_protocolVersion](https://ethereum.org/developers/docs/apis/json-rpc/#eth_protocolversion) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_protocolVersion", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_protocolVersion', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Ethereum documentation](/docs/ethereum).* --- ## eth_sendRawTransaction - Ethereum RPC Method # eth_sendRawTransaction Submits a pre-signed transaction for broadcast to Ethereum. > **Why Ethereum?** Build on the world's leading smart contract platform with the largest developer ecosystem with battle-tested security, institutional adoption, and unmatched ecosystem with $166B+ TVL. ## Use Cases The `eth_sendRawTransaction` method is essential for: - **Broadcasting transactions** - Submit signed transactions to the network - **Wallet operations** - Send native tokens and interact with contracts - **DeFi operations** - Execute swaps, provide liquidity for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps - **Batch operations** - Submit multiple transactions efficiently ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `signedTransactionData` | `DATA` | Yes | The signed transaction data (RLP encoded) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | 32-byte transaction hash | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c808504a817c80082520894..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const wallet = new Wallet('YOUR_PRIVATE_KEY', provider); // Send native tokens async function sendTransaction(to, value) { const tx = await wallet.sendTransaction({ to: to, value: parseEther(value) }); console.log('Transaction hash:', tx.hash); // Wait for confirmation const receipt = await tx.wait(); console.log('Confirmed in block:', receipt.blockNumber); return receipt; } // Send to contract async function sendContractTransaction(contract, method, args, value = '0') { const tx = await contract[method](...args, { value: parseEther(value) }); return await tx.wait(); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) def send_transaction(private_key, to, value_in_ether): account = w3.eth.account.from_key(private_key) # Build transaction tx = { 'nonce': w3.eth.get_transaction_count(account.address), 'to': to, 'value': w3.to_wei(value_in_ether, 'ether'), 'gas': 21000, 'gasPrice': w3.eth.gas_price, 'chainId': w3.eth.chain_id } # Sign transaction signed_tx = account.sign_transaction(tx) # Send transaction tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) print(f'Transaction hash: {tx_hash.hex()}') # Wait for confirmation receipt = w3.eth.wait_for_transaction_receipt(tx_hash) print(f'Confirmed in block: {receipt["blockNumber"]}') return receipt ``` ```go package main "context" "crypto/ecdsa" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY") if err != nil { log.Fatal(err) } publicKey := privateKey.Public() publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey) fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA) nonce, _ := client.PendingNonceAt(context.Background(), fromAddress) value := big.NewInt(1000000000000000000) gasLimit := uint64(21000) gasPrice, _ := client.SuggestGasPrice(context.Background()) toAddress := common.HexToAddress("0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045") tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil) chainID, _ := client.NetworkID(context.Background()) signedTx, _ := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey) err = client.SendTransaction(context.Background(), signedTx) if err != nil { log.Fatal(err) } fmt.Printf("Transaction hash: %s\n", signedTx.Hash().Hex()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Nonce too low | Transaction nonce already used | | -32000 | Insufficient funds | Account has insufficient balance | | -32000 | Gas too low | Gas limit insufficient | | -32000 | Replacement underpriced | Gas price too low for replacement | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas required - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction result --- ## eth_sendTransaction - Send transaction (wal...(Ethereum) # eth_sendTransaction > **Important**: Dwellir's shared Ethereum endpoints do not manage user private keys. JSON-RPC nodes cannot unlock your account, so `eth_sendTransaction` calls will fail. Sign transactions client-side and broadcast them with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Why this method is disabled on shared nodes - [`eth_sendTransaction` requires the node to hold and unlock the `from` account's private key](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction). - Managed infrastructure providers disable it for security reasons rather than storing customer keys on shared servers (for example, [Infura explicitly blocks the method on shared endpoints](https://docs.infura.io/api/networks/ethereum/json-rpc-methods/eth_sendtransaction)). ## Recommended workflow 1. Build the raw transaction locally with your wallet or SDK. 2. Sign the payload client-side (hardware wallet, custodial service, or library). 3. Submit the signed hex string with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Example response from the shared endpoint ```bash curl -s -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"0x0000000000000000000000000000000000000000"}],"id":1}' ``` ```json {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"unknown account"}} ``` Need help? Contact our [support team](mailto:support@dwellir.com) or use the dedicated [`eth_sendRawTransaction`](./eth_sendRawTransaction) guide. --- ## eth_signTransaction - Sign transaction (rar...(Ethereum) # eth_signTransaction Signs a transaction using an unlocked account on the node. **Important**: Most RPC providers don't support this method for security reasons, as it requires private keys to be stored on the server. ## Security Considerations - This method requires an unlocked account on the node - Private keys must be available to the RPC server - Most production RPC providers disable this method - Use client-side signing libraries instead for better security ## Parameters 1. `Object` - The transaction object: - `from`: `DATA`, 20 Bytes - The address the transaction is sent from - `to`: `DATA`, 20 Bytes - (optional) The address the transaction is directed to - `gas`: `QUANTITY` - (optional) Integer of the gas provided for the transaction execution - `gasPrice`: `QUANTITY` - (optional) Integer of the gasPrice used for each paid gas - `value`: `QUANTITY` - (optional) Integer of the value sent with this transaction - `data`: `DATA` - (optional) The compiled code of a contract OR the hash of the invoked method signature and encoded parameters ## Returns `DATA` - The signed transaction data, ready for transmission via `eth_sendRawTransaction`. ## Implementation Example ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_signTransaction", "params": [{ "from": "0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a" }], "id": 1 }' ``` ```javascript const response = await fetch('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_signTransaction', params: [{ from: '0x9b2055d370f73ec7d8a03e965129118dc8f5bf83', to: '0xd46e8dd67c5d32be8058bb8eb970870f07244567', gas: '0x76c0', gasPrice: '0x9184e72a000', value: '0x9184e72a' }], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0xf86c808504a817c8008276c094d46e8dd67c5d32be8058bb8eb970870f072445675849184e72a8001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804" } ``` **Note**: This method is typically not available on hosted RPC providers for security reasons. The response shows a signed transaction ready for broadcast. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Ethereum documentation](/docs/ethereum).* --- ## eth_syncing - Ethereum RPC Method # eth_syncing Returns syncing status of Ethereum node. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 } ``` ## Returns Returns `false` if not syncing, or an object with sync status. ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const syncing = await provider.send('eth_syncing', []); if (syncing === false) { console.log('Node is fully synced'); } else { console.log('Syncing:', syncing); } ``` ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get current block - [`net_peerCount`](./net_peerCount) - Get peer count --- ## eth_uninstallFilter - Ethereum RPC Method # eth_uninstallFilter Uninstalls a filter on Ethereum. Should be called when no longer needed. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID to uninstall | ## Request ```json { "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if filter was found and uninstalled | ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const success = await provider.send('eth_uninstallFilter', [filterId]); console.log('Filter removed:', success); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter --- ## Ethereum RPC with Dwellir # Ethereum – Build on the World's Leading Smart Contract Platform ## Why Build on Ethereum? Ethereum is the original and most established smart contract platform, offering unparalleled security, decentralization, and ecosystem support: ### 🛡️ **Unmatched Security** - **Longest-running proof-of-stake network** - Battle-tested since 2015, secured by PoS since 2022 - **$100B+ in value secured** - Highest total value locked across all chains - **10,000+ validators** - Maximally decentralized consensus mechanism ### 🌍 **Largest Ecosystem** - **3,000+ dApps** - Richest application ecosystem in web3 - **$50B+ DeFi TVL** - Largest decentralized finance ecosystem - **Major institutions** - Direct integration by Fortune 500 companies ### 🔧 **Developer Excellence** - **EVM standard** - Reference implementation for smart contract execution - **Mature tooling** - Best-in-class development frameworks and libraries - **Network effects** - Largest community of developers and users ## Quick Start with Ethereum Connect to Ethereum in seconds with Dwellir's optimized endpoints: ### Installation & Setup ```javascript // Connect to Ethereum mainnet const provider = new JsonRpcProvider( 'https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY' ); // Get the latest block const block = await provider.getBlock('latest'); console.log('Latest block:', block.number); // Query account balance const balance = await provider.getBalance('0x...'); console.log('Balance:', balance.toString()); ``` ```javascript const Web3 = require('web3'); // Connect to Ethereum mainnet const web3 = new Web3( 'https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY' ); // Get chain ID to verify connection const chainId = await web3.eth.getChainId(); console.log('Connected to Ethereum:', chainId === 1); // Get gas price for optimal transaction pricing const gasPrice = await web3.eth.getGasPrice(); console.log('Current gas price:', gasPrice); ``` ```typescript // Create Ethereum client const client = createPublicClient({ chain: mainnet, transport: http('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'), }); // Read contract data const data = await client.readContract({ address: '0x...', abi: contractAbi, functionName: 'balanceOf', args: ['0x...'], }); ``` ```python from web3 import Web3 # Connect to Ethereum mainnet web3 = Web3(Web3.HTTPProvider( 'https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY' )) # Verify connection print('Connected:', web3.is_connected()) print('Chain ID:', web3.eth.chain_id) # Get latest block latest_block = web3.eth.get_block('latest') print(f'Latest block: {latest_block.number}') ``` ## Network Information Chain ID 1 Mainnet Block Time 12 seconds Average Gas Token ETH Native token RPC Standard Ethereum JSON-RPC 2.0 ## JSON-RPC API Reference Ethereum supports the full [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/). ## Common Integration Patterns ### 🔄 Transaction Monitoring Monitor pending and confirmed transactions efficiently: ```javascript // Watch for transaction confirmation async function waitForTransaction(txHash) { const receipt = await provider.waitForTransaction(txHash, 1); // Check transaction status if (receipt.status === 1) { console.log('Transaction successful'); } else { console.log('Transaction failed'); } return receipt; } ``` ### 💰 Gas Optimization Optimize gas costs on Ethereum mainnet: ```javascript // Get current fee data (EIP-1559) const feeData = await provider.getFeeData(); // Estimate gas for transaction const gasEstimate = await provider.estimateGas(tx); // Calculate total cost const totalCost = gasEstimate * feeData.gasPrice; console.log('Estimated cost:', totalCost); ``` ### 🔍 Event Filtering Efficiently query contract events with proper pagination: ```javascript // Query events with automatic retry and pagination async function getEvents(contract, eventName, fromBlock = 0) { const filter = contract.filters[eventName](); const events = []; const batchSize = 2000; // Recommended batch size const latestBlock = await provider.getBlockNumber(); for (let i = fromBlock; i <= latestBlock; i += batchSize) { const toBlock = Math.min(i + batchSize - 1, latestBlock); const batch = await contract.queryFilter(filter, i, toBlock); events.push(...batch); } return events; } ``` ## Performance Best Practices ### 1. **Batch Requests** Combine multiple RPC calls for optimal performance: ```javascript const batch = [ { method: 'eth_blockNumber', params: [] }, { method: 'eth_gasPrice', params: [] }, { method: 'eth_getBalance', params: [address, 'latest'] } ]; const results = await provider.send(batch); ``` ### 2. **Connection Pooling** Reuse provider instances to minimize connection overhead: ```javascript // Singleton pattern for provider class EthereumProvider { static instance = null; static getInstance() { if (!this.instance) { this.instance = new JsonRpcProvider( 'https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY' ); } return this.instance; } } ``` ### 3. **Smart Caching** Cache immutable data to reduce API calls: ```javascript const cache = new Map(); async function getCachedBlockData(blockNumber) { const key = `block_${blockNumber}`; if (!cache.has(key)) { const block = await provider.getBlock(blockNumber); cache.set(key, block); } return cache.get(key); } ``` ## Troubleshooting Common Issues ### Error: "Insufficient funds for gas" Ethereum transactions require ETH for gas fees: ```javascript // Always account for gas in balance checks const balance = await provider.getBalance(address); const gasPrice = await provider.getGasPrice(); const gasLimit = await provider.estimateGas(tx); const gasCost = gasPrice * gasLimit; if (balance < (tx.value + gasCost)) { throw new Error(`Need ${(tx.value + gasCost) - balance} more wei`); } ``` ### Error: "Transaction underpriced" Use current market gas prices: ```javascript // Get current fee data const feeData = await provider.getFeeData(); const tx = { to: recipient, value: amount, maxFeePerGas: feeData.maxFeePerGas, maxPriorityFeePerGas: feeData.maxPriorityFeePerGas, gasLimit: 21000n }; ``` ### Error: "Rate limit exceeded" Implement exponential backoff for resilient applications: ```javascript async function callWithRetry(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error.code === 429 && i < maxRetries - 1) { await new Promise(r => setTimeout(r, 2 ** i * 1000)); } else { throw error; } } } } ``` ## Smoke Tests ### Test Connection with cURL ```bash # Test Ethereum mainnet curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' # Test Ethereum Sepolia curl -X POST https://api-ethereum-sepolia.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' ``` ### Test with Ethers.js ```javascript // Test mainnet connection const mainnetProvider = new JsonRpcProvider( 'https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY' ); const blockNumber = await mainnetProvider.getBlockNumber(); const network = await mainnetProvider.getNetwork(); console.log('Block number:', blockNumber); console.log('Chain ID:', network.chainId); // Should be 1n ``` ### Test with Web3.py ```python from web3 import Web3 # Test connection web3 = Web3(Web3.HTTPProvider( 'https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY' )) print('Connected:', web3.is_connected()) print('Chain ID:', web3.eth.chain_id) # Should be 1 print('Block number:', web3.eth.block_number) ``` ## Migration Guide ### Migrating to Dwellir Replace your existing RPC endpoint with Dwellir: ```javascript // Before const provider = new JsonRpcProvider('https://other-provider.com'); // After const provider = new JsonRpcProvider( 'https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY' ); // ✅ All existing code works identically // ✅ Same JSON-RPC methods supported // ✅ Same response formats // ⚠️ Update your API endpoint URL // ⚠️ Add your Dwellir API key ``` ## Resources & Tools ### Official Resources - [Ethereum Documentation](https://ethereum.org/en/developers/) - [EIP Standards](https://eips.ethereum.org/) - [Etherscan Block Explorer](https://etherscan.io) ### Developer Tools - [Hardhat](https://hardhat.org/) - [Foundry](https://getfoundry.sh/) - [Truffle](https://trufflesuite.com/) - [Remix IDE](https://remix.ethereum.org/) ### Need Help? - 📧 **Email**: support@dwellir.com - 📚 **Docs**: You're here! - 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com) --- *Start building on Ethereum with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)* --- ## net_listening - Ethereum RPC Method # net_listening Returns `true` if client is actively listening for network connections on Ethereum. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if listening | ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const listening = await provider.send('net_listening', []); console.log('Node listening:', listening); ``` ## Related Methods - [`net_peerCount`](./net_peerCount) - Get peer count --- ## net_peerCount - Ethereum RPC Method # net_peerCount Returns number of peers currently connected to Ethereum client. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Number of connected peers (hexadecimal) | ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const peerCount = await provider.send('net_peerCount', []); console.log('Peer count:', parseInt(peerCount, 16)); ``` ## Related Methods - [`net_listening`](./net_listening) - Check if listening --- ## net_version - Ethereum RPC Method # net_version Returns the current network ID on Ethereum. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Network ID as a string | ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const networkId = await provider.send('net_version', []); console.log('Network ID:', networkId); ``` ## Related Methods - [`eth_chainId`](./eth_chainId) - Get chain ID --- ## trace_block - Ethereum RPC Method # trace_block Returns traces for all transactions in a block on Ethereum. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Block analysis** - Inspect all internal transactions in a block - **MEV research** - Analyze transaction ordering and internal calls - **Indexing** - Build comprehensive transaction indexes for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex or tag (`latest`, `earliest`, `pending`) | ## Request ```json { "jsonrpc": "2.0", "method": "trace_block", "params": ["latest"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_block", "params": ["latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('trace_block', ['latest']); console.log('Traces in block:', traces.length); for (const trace of traces.slice(0, 5)) { console.log(` ${trace.action.from} -> ${trace.action.to} (${trace.type})`); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) traces = w3.provider.make_request('trace_block', ['latest']) for trace in traces['result'][:5]: action = trace['action'] print(f'{action["from"]} -> {action.get("to", "CREATE")} ({trace["type"]})') ``` ## Related Methods - [`trace_filter`](./trace_filter) - Filter traces by address or block range - [`trace_transaction`](./trace_transaction) - Trace a specific transaction - [`trace_get`](./trace_get) - Get a specific trace by index --- ## trace_call - Ethereum RPC Method # trace_call Traces a call without creating a transaction on Ethereum, returning the trace output. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Call simulation** - Preview internal calls before sending a transaction - **Contract interaction analysis** - Understand how contracts interact - **Gas estimation** - Analyze gas usage patterns for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `callObject` | `Object` | Yes | Transaction call object (`from`, `to`, `gas`, `value`, `data`) | | `traceTypes` | `Array` | Yes | Trace types: `["trace"]`, `["vmTrace"]`, `["stateDiff"]`, or combinations | | `blockNumber` | `QUANTITY\|TAG` | No | Block number or tag (default: `latest`) | ## Request ```json { "jsonrpc": "2.0", "method": "trace_call", "params": [ { "to": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "data": "0x70a08231000000000000000000000000d8dA6BF26964aF9D7eEd9e03E53415D37aA96045" }, ["trace"], "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_call", "params": [ {"to": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "data": "0x70a08231000000000000000000000000d8dA6BF26964aF9D7eEd9e03E53415D37aA96045"}, ["trace"], "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const result = await provider.send('trace_call', [ { to: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', data: '0x70a08231000000000000000000000000d8dA6BF26964aF9D7eEd9e03E53415D37aA96045' }, ['trace'], 'latest' ]); console.log('Trace output:', result.trace); console.log('VM trace:', result.vmTrace); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) result = w3.provider.make_request('trace_call', [ { 'to': '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', 'data': '0x70a08231000000000000000000000000d8dA6BF26964aF9D7eEd9e03E53415D37aA96045' }, ['trace'], 'latest' ]) print(f'Trace: {result["result"]["trace"]}') ``` ## Related Methods - [`trace_filter`](./trace_filter) - Filter traces by criteria - [`eth_call`](./eth_call) - Execute call without trace - [`trace_transaction`](./trace_transaction) - Trace a specific transaction --- ## trace_callMany - Ethereum RPC Method # trace_callMany Traces multiple calls in sequence on Ethereum, where each call can depend on the state changes of the previous one. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Multi-step simulation** - Simulate a sequence of dependent transactions - **Arbitrage analysis** - Test multi-hop swap paths - **Batch operations** - Preview multiple contract interactions for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `calls` | `Array` | Yes | Array of `[callObject, traceTypes]` pairs | | `blockNumber` | `QUANTITY\|TAG` | No | Block number or tag (default: `latest`) | Each element in `calls` is a tuple of: - `callObject` - Transaction call object (`from`, `to`, `gas`, `value`, `data`) - `traceTypes` - Array of trace types: `["trace"]`, `["vmTrace"]`, `["stateDiff"]` ## Request ```json { "jsonrpc": "2.0", "method": "trace_callMany", "params": [ [ [{"to": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "data": "0x70a08231000000000000000000000000d8dA6BF26964aF9D7eEd9e03E53415D37aA96045"}, ["trace"]], [{"to": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "data": "0x18160ddd"}, ["trace"]] ], "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_callMany", "params": [ [ [{"to": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "data": "0x70a08231000000000000000000000000d8dA6BF26964aF9D7eEd9e03E53415D37aA96045"}, ["trace"]], [{"to": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045", "data": "0x18160ddd"}, ["trace"]] ], "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const results = await provider.send('trace_callMany', [ [ [{ to: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', data: '0x70a08231000000000000000000000000d8dA6BF26964aF9D7eEd9e03E53415D37aA96045' }, ['trace']], [{ to: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', data: '0x18160ddd' }, ['trace']] ], 'latest' ]); console.log('Call results:', results.length); for (const result of results) { console.log(' Output:', result.output); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) results = w3.provider.make_request('trace_callMany', [ [ [{'to': '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', 'data': '0x70a08231000000000000000000000000d8dA6BF26964aF9D7eEd9e03E53415D37aA96045'}, ['trace']], [{'to': '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045', 'data': '0x18160ddd'}, ['trace']] ], 'latest' ]) for i, result in enumerate(results['result']): print(f'Call {i}: output={result.get("output", "N/A")}') ``` ## Related Methods - [`trace_call`](./trace_call) - Trace a single call - [`eth_call`](./eth_call) - Execute call without trace --- ## trace_filter - Ethereum RPC Method # trace_filter Returns traces matching a filter on Ethereum. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Address activity** - Find all internal transactions involving an address - **Contract monitoring** - Track calls to specific contracts - **Forensic analysis** - Investigate transaction patterns for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterObject` | `Object` | Yes | Filter criteria (see below) | ### Filter Object Fields | Field | Type | Description | |-------|------|-------------| | `fromBlock` | `QUANTITY\|TAG` | Start block (hex or tag) | | `toBlock` | `QUANTITY\|TAG` | End block (hex or tag) | | `fromAddress` | `Array` | Filter by sender addresses | | `toAddress` | `Array` | Filter by receiver addresses | | `after` | `QUANTITY` | Offset for pagination | | `count` | `QUANTITY` | Max results to return | ## Request ```json { "jsonrpc": "2.0", "method": "trace_filter", "params": [{ "fromBlock": "latest", "toBlock": "latest", "toAddress": ["0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"], "count": 10 }], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_filter", "params": [{ "fromBlock": "latest", "toBlock": "latest", "toAddress": ["0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"], "count": 10 }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('trace_filter', [{ fromBlock: 'latest', toBlock: 'latest', toAddress: ['0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'], count: 10 }]); console.log('Matching traces:', traces.length); for (const trace of traces) { console.log(` Block ${trace.blockNumber}: ${trace.action.from} -> ${trace.action.to}`); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) traces = w3.provider.make_request('trace_filter', [{ 'fromBlock': 'latest', 'toBlock': 'latest', 'toAddress': ['0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'], 'count': 10 }]) for trace in traces['result']: action = trace['action'] print(f'Block {trace["blockNumber"]}: {action["from"]} -> {action.get("to", "CREATE")}') ``` ## Related Methods - [`trace_block`](./trace_block) - Get all traces in a block - [`trace_transaction`](./trace_transaction) - Get traces for a specific transaction - [`eth_getLogs`](./eth_getLogs) - Filter event logs --- ## trace_get - Ethereum RPC Method # trace_get Returns a trace at a specific position within a transaction on Ethereum. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Specific trace lookup** - Get a single trace by its position index - **Internal call inspection** - Examine a specific internal call - **Targeted debugging** - Investigate particular call depth for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `indices` | `Array` | Yes | Trace index positions (e.g., `["0x0"]` for the first trace) | ## Request ```json { "jsonrpc": "2.0", "method": "trace_get", "params": ["0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a", ["0x0"]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_get", "params": ["0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a", ["0x0"]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const trace = await provider.send('trace_get', [ '0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a', ['0x0'] ]); console.log('Trace type:', trace.type); console.log('From:', trace.action.from); console.log('To:', trace.action.to); console.log('Value:', trace.action.value); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) trace = w3.provider.make_request('trace_get', [ '0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a', ['0x0'] ]) result = trace['result'] print(f'Type: {result["type"]}') print(f'From: {result["action"]["from"]}') print(f'To: {result["action"]["to"]}') ``` ## Related Methods - [`trace_transaction`](./trace_transaction) - Get all traces for a transaction - [`trace_block`](./trace_block) - Get all traces in a block --- ## trace_replayBlockTransactions - Ethereum RPC Method # trace_replayBlockTransactions Replays all transactions in a block on Ethereum and returns the requested traces. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Block replay** - Re-execute all transactions with full trace output - **State diff analysis** - Get state changes for every transaction in a block - **VM trace extraction** - Obtain detailed EVM execution traces for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex or tag | | `traceTypes` | `Array` | Yes | Trace types: `["trace"]`, `["vmTrace"]`, `["stateDiff"]`, or combinations | ## Request ```json { "jsonrpc": "2.0", "method": "trace_replayBlockTransactions", "params": ["latest", ["trace"]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_replayBlockTransactions", "params": ["latest", ["trace"]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const results = await provider.send('trace_replayBlockTransactions', [ 'latest', ['trace'] ]); console.log('Transactions replayed:', results.length); for (const result of results.slice(0, 3)) { console.log(` Tx ${result.transactionHash}: ${result.trace.length} traces`); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) results = w3.provider.make_request('trace_replayBlockTransactions', [ 'latest', ['trace'] ]) for tx in results['result'][:3]: print(f'Tx {tx["transactionHash"]}: {len(tx["trace"])} traces') ``` ## Related Methods - [`trace_replayTransaction`](./trace_replayTransaction) - Replay a single transaction - [`trace_block`](./trace_block) - Get traces without replay - [`trace_filter`](./trace_filter) - Filter traces by criteria --- ## trace_replayTransaction - Ethereum RPC Method # trace_replayTransaction Replays a transaction on Ethereum and returns the requested traces. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction replay** - Re-execute a transaction with full trace output - **State diff extraction** - Get exact state changes from a transaction - **VM trace debugging** - Get opcode-level execution details for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `traceTypes` | `Array` | Yes | Trace types: `["trace"]`, `["vmTrace"]`, `["stateDiff"]`, or combinations | ## Request ```json { "jsonrpc": "2.0", "method": "trace_replayTransaction", "params": ["0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a", ["trace"]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_replayTransaction", "params": ["0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a", ["trace"]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const result = await provider.send('trace_replayTransaction', [ '0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a', ['trace'] ]); console.log('Trace:', result.trace.length, 'entries'); console.log('State diff:', result.stateDiff ? 'present' : 'not requested'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) result = w3.provider.make_request('trace_replayTransaction', [ '0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a', ['trace'] ]) trace = result['result'] print(f'Trace entries: {len(trace["trace"])}') ``` ## Related Methods - [`trace_replayBlockTransactions`](./trace_replayBlockTransactions) - Replay all transactions in a block - [`trace_transaction`](./trace_transaction) - Get traces without replay - [`trace_block`](./trace_block) - Get all traces in a block --- ## trace_transaction - Ethereum RPC Method # trace_transaction Returns all traces for a specific transaction on Ethereum. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction analysis** - See all internal calls made by a transaction - **Token transfer tracking** - Trace value flows through contracts - **Debugging** - Understand execution flow for DeFi protocols (60% market share), NFT marketplaces, DAOs, and enterprise dApps ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "trace_transaction", "params": ["0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_transaction", "params": ["0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('trace_transaction', [ '0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a' ]); console.log('Traces:', traces.length); for (const trace of traces) { console.log(` ${trace.action.from} -> ${trace.action.to} (${trace.type})`); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY')) traces = w3.provider.make_request('trace_transaction', [ '0x42690cc81dfd7f6a5ebc973fd8c4912e6068df47646c665a1b54fae904b0470a' ]) for trace in traces['result']: action = trace['action'] print(f'{action["from"]} -> {action.get("to", "CREATE")} ({trace["type"]})') ``` ## Related Methods - [`trace_get`](./trace_get) - Get a specific trace by index - [`trace_block`](./trace_block) - Get all traces in a block - [`trace_filter`](./trace_filter) - Filter traces by criteria --- ## web3_clientVersion - Ethereum RPC Method # web3_clientVersion Returns the current client version on Ethereum. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Client version string | ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); const version = await provider.send('web3_clientVersion', []); console.log('Client version:', version); ``` --- ## web3_sha3 - Ethereum RPC Method # web3_sha3 Returns Keccak-256 (not standard SHA3-256) of the given data on Ethereum. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `data` | `DATA` | Yes | Data to hash | ## Request ```json { "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Keccak-256 hash of the data | ## Code Examples ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); // Using RPC const hash = await provider.send('web3_sha3', ['0x68656c6c6f']); console.log('Hash:', hash); // Using ethers directly (faster) const localHash = keccak256(toUtf8Bytes('hello')); console.log('Local hash:', localHash); ``` --- ## debug_traceBlock - Flow EVM RPC Method # debug_traceBlock Traces all transactions in a block on Flow EVM Gateway by block RLP. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Analyze transaction execution step-by-step - **Smart contract analysis** - Debug contract interactions - **Security auditing** - Trace internal calls for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockRlp` | `DATA` | Yes | RLP-encoded block data | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); // Use debug_traceBlockByNumber instead (more practical) const traces = await provider.send('debug_traceBlockByNumber', ['latest', {}]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by block number - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by block hash --- ## debug_traceBlockByHash - Flow EVM RPC Method # debug_traceBlockByHash Traces all transactions in a block on Flow EVM Gateway by block hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0xee0158dc7a2e89b3de711f135d5d39f2bf5fa407233501c4b58a065bfe7089b8", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0xee0158dc7a2e89b3de711f135d5d39f2bf5fa407233501c4b58a065bfe7089b8", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0xee0158dc7a2e89b3de711f135d5d39f2bf5fa407233501c4b58a065bfe7089b8'; const traces = await provider.send('debug_traceBlockByHash', [blockHash, { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by number - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceBlockByNumber - Flow EVM RPC Method # debug_traceBlockByNumber Traces all transactions in a block on Flow EVM Gateway by block number. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('debug_traceBlockByNumber', ['latest', { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by hash - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceCall - Flow EVM RPC Method # debug_traceCall Traces a call without creating a transaction on Flow EVM Gateway. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction simulation** - Debug before sending - **Gas analysis** - Analyze gas usage per opcode - **Contract debugging** - Step through execution for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `call` | `Object` | Yes | Call object (same as eth_call) | | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ { "to": "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "data": "0x70a08231000000000000000000000000d3bF53DAC106A0290B0483EcBC89d40FcC961f3e" }, "latest", {} ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ {"to": "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "data": "0x70a08231000000000000000000000000d3bF53DAC106A0290B0483EcBC89d40FcC961f3e"}, "latest", {"tracer": "callTracer"} ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const trace = await provider.send('debug_traceCall', [ { to: '0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e', data: '0x70a08231000000000000000000000000d3bF53DAC106A0290B0483EcBC89d40FcC961f3e' }, 'latest', { tracer: 'callTracer' } ]); console.log('Trace:', trace); ``` ## Related Methods - [`eth_call`](./eth_call) - Execute call without trace - [`debug_traceTransaction`](./debug_traceTransaction) - Trace actual transaction --- ## debug_traceTransaction - Flow EVM RPC Method # debug_traceTransaction Traces a transaction execution on Flow EVM Gateway by transaction hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Understand exactly what happened - **Failure analysis** - Find where and why a transaction reverted - **Gas optimization** - Analyze gas usage for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Tracer Options - `{}` - Default opcode tracer (verbose) - `{ tracer: "callTracer" }` - Call tree tracer - `{ tracer: "prestateTracer" }` - Pre-state tracer ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0xac905cb8672fe39508dab7199529d77b32d459242ad9d3f6799e4e427d6003f8", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0xac905cb8672fe39508dab7199529d77b32d459242ad9d3f6799e4e427d6003f8", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const txHash = '0xac905cb8672fe39508dab7199529d77b32d459242ad9d3f6799e4e427d6003f8'; // Call tracer - shows internal calls const callTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'callTracer' } ]); console.log('Type:', callTrace.type); console.log('From:', callTrace.from); console.log('To:', callTrace.to); console.log('Gas used:', parseInt(callTrace.gasUsed, 16)); // Prestate tracer - shows state before execution const prestateTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'prestateTracer' } ]); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0xac905cb8672fe39508dab7199529d77b32d459242ad9d3f6799e4e427d6003f8' # Call tracer trace = w3.provider.make_request('debug_traceTransaction', [ tx_hash, {'tracer': 'callTracer'} ]) print(f'Trace type: {trace["result"]["type"]}') print(f'Gas used: {int(trace["result"]["gasUsed"], 16)}') ``` ## Related Methods - [`debug_traceCall`](./debug_traceCall) - Trace without executing - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace entire block --- ## eth_accounts - Flow EVM RPC Method # eth_accounts Returns a list of addresses owned by the client on Flow EVM Gateway. > **Why Flow EVM?** Build on the EVM-equivalent layer on Flow blockchain enabling Cadence+Solidity composability with full EVM equivalence on Flow, atomic multi-operation transactions, 40% lower gas fees, and 473% contract growth in 2025. ## Important Note On public RPC endpoints like Dwellir, `eth_accounts` returns an empty array because the node does not hold any private keys. This method is primarily useful for: - Local development nodes (Ganache, Hardhat, Anvil) - Private nodes with managed accounts - Wallet provider connections (MetaMask injects accounts) ## When to Use This Method `eth_accounts` is relevant for NFT developers, gaming studios, and Solidity devs seeking Cadence interoperability in specific scenarios: - **Development Testing** — Retrieve test accounts from local nodes - **Wallet Detection** — Check if a wallet provider has connected accounts - **Client Verification** — Confirm node account access capabilities ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `Array` | List of 20-byte account addresses owned by the client | **Return format**: Array of `0x` prefixed hexadecimal addresses (typically empty for public nodes) ## Request ```json { "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 } ``` ## Response ### Successful Response (Public Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [] } ``` ### Successful Response (Local Development Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [ "0x407d73d8a49eeb85d32cf465507dd71d507100c1", "0x85d32cf465507dd71d507100c1407d73d8a49eeb" ] } ``` ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_accounts', params: [], id: 1 }) }); const { result } = await response.json(); console.log('Accounts:', result); // Using ethers.js const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const accounts = await provider.listAccounts(); console.log('Accounts:', accounts); ``` ```python def get_accounts(): response = requests.post( 'https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_accounts', 'params': [], 'id': 1 } ) return response.json()['result'] accounts = get_accounts() print(f'Accounts: {accounts}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) print(f'Accounts: {w3.eth.accounts}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/rpc" ) func main() { client, err := rpc.Dial("https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } var accounts []string err = client.CallContext(context.Background(), &accounts, "eth_accounts") if err != nil { log.Fatal(err) } fmt.Printf("Accounts: %v\n", accounts) } ``` ## Common Use Cases ### 1. Development Environment Detection Check if running against a development node with test accounts: ```javascript async function isDevEnvironment(provider) { const accounts = await provider.listAccounts(); return accounts.length > 0; } const isDev = await isDevEnvironment(provider); if (isDev) { console.log('Development environment detected'); } ``` ### 2. Wallet Connection Check Verify wallet provider has connected accounts: ```javascript async function checkWalletConnection() { if (typeof window.ethereum === 'undefined') { return { connected: false, reason: 'No wallet detected' }; } const accounts = await window.ethereum.request({ method: 'eth_accounts' }); return { connected: accounts.length > 0, accounts: accounts }; } ``` ### 3. Fallback Account Selection Use first available account or request connection: ```javascript async function getActiveAccount() { // Check existing connections let accounts = await window.ethereum.request({ method: 'eth_accounts' }); // Request connection if no accounts if (accounts.length === 0) { accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); } return accounts[0] || null; } ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32601 | Method not found | Node may not support this method | | -32603 | Internal error | Retry with exponential backoff | ```javascript async function safeGetAccounts(provider) { try { const accounts = await provider.listAccounts(); return { success: true, accounts }; } catch (error) { if (error.code === -32601) { console.warn('eth_accounts not supported on this node'); return { success: false, accounts: [], reason: 'unsupported' }; } throw error; } } ``` ## Related Methods - [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102) — Request wallet connection (browser wallets) - [`eth_getBalance`](./eth_getBalance) — Get account balance - [`eth_getTransactionCount`](./eth_getTransactionCount) — Get account nonce --- ## eth_blockNumber - Flow EVM RPC Method # eth_blockNumber Returns the number of the most recent block on Flow EVM Gateway. > **Why Flow EVM?** Build on the EVM-equivalent layer on Flow blockchain enabling Cadence+Solidity composability with full EVM equivalence on Flow, atomic multi-operation transactions, 40% lower gas fees, and 473% contract growth in 2025. ## When to Use This Method `eth_blockNumber` is fundamental for NFT developers, gaming studios, and Solidity devs seeking Cadence interoperability: - **Syncing Applications** — Keep your dApp in sync with the latest Flow EVM blockchain state - **Transaction Monitoring** — Verify confirmations by comparing block numbers - **Event Filtering** — Set the correct block range for querying logs on consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications - **Health Checks** — Monitor node connectivity and sync status ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `QUANTITY` | Hexadecimal string representing the current block number | **Return format**: `0x` prefixed hexadecimal (e.g., `0x5BAD55` = 6,008,149 in decimal) ## Request ```json { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } ``` ## Response ### Successful Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5BAD55" } ``` ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error" } } ``` ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }) }); const { result } = await response.json(); const blockNumber = parseInt(result, 16); console.log('Flow EVM block:', blockNumber); // Using ethers.js const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const blockNumber = await provider.getBlockNumber(); console.log('Flow EVM block:', blockNumber); ``` ```python def get_block_number(): response = requests.post( 'https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_blockNumber', 'params': [], 'id': 1 } ) result = response.json()['result'] return int(result, 16) block_number = get_block_number() print(f'Flow EVM block: {block_number}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) print(f'Flow EVM block: {w3.eth.block_number}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockNumber, err := client.BlockNumber(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Flow EVM block: %d\n", blockNumber) } ``` ## Common Use Cases ### 1. Block Confirmation Counter Monitor transaction confirmations on Flow EVM: ```javascript async function getConfirmations(provider, txHash) { const tx = await provider.getTransaction(txHash); if (!tx || !tx.blockNumber) return 0; const currentBlock = await provider.getBlockNumber(); return currentBlock - tx.blockNumber + 1; } // Wait for specific confirmations async function waitForConfirmations(provider, txHash, confirmations = 6) { let currentConfirmations = 0; while (currentConfirmations < confirmations) { currentConfirmations = await getConfirmations(provider, txHash); console.log(`Confirmations: ${currentConfirmations}/${confirmations}`); await new Promise(r => setTimeout(r, 2000)); } return true; } ``` ### 2. Event Log Filtering Query events from recent blocks on Flow EVM: ```javascript async function getRecentEvents(provider, contract, eventName, blockRange = 100) { const currentBlock = await provider.getBlockNumber(); const fromBlock = currentBlock - blockRange; const filter = contract.filters[eventName](); const events = await contract.queryFilter(filter, fromBlock, currentBlock); return events; } ``` ### 3. Node Health Monitoring Check if your Flow EVM node is synced: ```javascript async function checkNodeHealth(provider) { try { const blockNumber = await provider.getBlockNumber(); const block = await provider.getBlock(blockNumber); const now = Date.now() / 1000; const blockAge = now - block.timestamp; if (blockAge > 60) { console.warn(`Node may be behind. Last block was ${blockAge}s ago`); return false; } console.log(`Node healthy. Latest block: ${blockNumber}`); return true; } catch (error) { console.error('Node unreachable:', error); return false; } } ``` ## Performance Optimization ### Caching Strategy Cache block numbers to reduce API calls: ```javascript class BlockNumberCache { constructor(ttl = 2000) { this.cache = null; this.timestamp = 0; this.ttl = ttl; } async get(provider) { const now = Date.now(); if (this.cache && (now - this.timestamp) < this.ttl) { return this.cache; } this.cache = await provider.getBlockNumber(); this.timestamp = now; return this.cache; } invalidate() { this.cache = null; this.timestamp = 0; } } const blockCache = new BlockNumberCache(); ``` ### Batch Requests Combine with other calls for efficiency: ```javascript const batch = [ { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }, { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 }, { jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 } ]; const response = await fetch('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await response.json(); ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32603 | Internal error | Retry with exponential backoff | | -32005 | Rate limit exceeded | Implement rate limiting client-side | | -32000 | Execution reverted | Check node sync status | ```javascript async function safeGetBlockNumber(provider, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await provider.getBlockNumber(); } catch (error) { if (error.code === -32005) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } else if (i === maxRetries - 1) { throw error; } } } } ``` ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) — Get full block details by number - [`eth_getBlockByHash`](./eth_getBlockByHash) — Get block details by hash - [`eth_syncing`](./eth_syncing) — Check if node is still syncing --- ## eth_call - Flow EVM RPC Method # eth_call Executes a new message call immediately without creating a transaction on Flow EVM Gateway. Used for reading smart contract state. > **Why Flow EVM?** Build on the EVM-equivalent layer on Flow blockchain enabling Cadence+Solidity composability with full EVM equivalence on Flow, atomic multi-operation transactions, 40% lower gas fees, and 473% contract growth in 2025. ## Use Cases The `eth_call` method is essential for: - **Reading contract state** - Query view/pure functions - **Simulating transactions** - Test execution without gas costs - **DeFi integrations** - Check prices, balances, allowances for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications - **Complex queries** - Execute multi-step contract logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | 20-byte address executing the call | | `to` | `DATA` | Yes | 20-byte contract address | | `gas` | `QUANTITY` | No | Gas limit for the call | | `gasPrice` | `QUANTITY` | No | Gas price in wei | | `value` | `QUANTITY` | No | Value to send in wei | | `data` | `DATA` | Yes | Encoded function call data | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_call", "params": [ { "to": "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "data": "0x70a08231000000000000000000000000d3bF53DAC106A0290B0483EcBC89d40FcC961f3e" }, "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | The return value of the executed contract function | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000" } ``` ## Code Examples ```bash # Call ERC20 balanceOf function curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{ "to": "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "data": "0x70a08231000000000000000000000000d3bF53DAC106A0290B0483EcBC89d40FcC961f3e" }, "latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); // ERC20 ABI for common functions const ERC20_ABI = [ "function balanceOf(address owner) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function totalSupply() view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)" ]; // Read ERC20 token balance async function getTokenBalance(tokenAddress, walletAddress) { const contract = new Contract(tokenAddress, ERC20_ABI, provider); const balance = await contract.balanceOf(walletAddress); const decimals = await contract.decimals(); const symbol = await contract.symbol(); return { raw: balance.toString(), formatted: (Number(balance) / Math.pow(10, decimals)).toFixed(4), symbol: symbol }; } // Direct eth_call async function directCall(to, data) { const result = await provider.call({ to, data }); return result; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) def get_erc20_balance(token_address, wallet_address): # balanceOf(address) selector function_signature = "balanceOf(address)" function_selector = w3.keccak(text=function_signature)[:4].hex() # Encode address parameter encoded_address = wallet_address[2:].lower().zfill(64) data = function_selector + encoded_address # Make the call result = w3.eth.call({ 'to': token_address, 'data': data }) return int(result.hex(), 16) balance = get_erc20_balance( '0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e', '0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e' ) print(f'Balance: {balance}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e") data := common.FromHex("0x70a08231000000000000000000000000d3bF53DAC106A0290B0483EcBC89d40FcC961f3e") msg := ethereum.CallMsg{ To: &contractAddress, Data: data, } result, err := client.CallContract(context.Background(), msg, nil) if err != nil { log.Fatal(err) } fmt.Printf("Result: 0x%x\n", result) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Contract function reverted | | -32602 | Invalid parameters | Invalid data encoding | | -32015 | VM execution error | Contract logic error | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas for transaction - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send actual transaction --- ## eth_chainId - Flow EVM RPC Method # eth_chainId Returns the chain ID used for transaction signing on Flow EVM Gateway. > **Why Flow EVM?** Build on the EVM-equivalent layer on Flow blockchain enabling Cadence+Solidity composability with full EVM equivalence on Flow, atomic multi-operation transactions, 40% lower gas fees, and 473% contract growth in 2025. ## Use Cases The `eth_chainId` method is essential for: - **Transaction signing** - Ensure transactions are signed for the correct network - **Network verification** - Confirm connection to the expected chain - **Multi-chain apps** - Handle different networks programmatically - **Wallet integration** - Validate network before transactions ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Chain ID in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1" } ``` ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const network = await provider.getNetwork(); console.log('Chain ID:', network.chainId); // Verify network before transaction async function verifyNetwork(expectedChainId) { const network = await provider.getNetwork(); if (network.chainId !== BigInt(expectedChainId)) { throw new Error(`Wrong network. Expected ${expectedChainId}, got ${network.chainId}`); } return true; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) chain_id = w3.eth.chain_id print(f'Chain ID: {chain_id}') # Verify network def verify_network(expected_chain_id): chain_id = w3.eth.chain_id if chain_id != expected_chain_id: raise ValueError(f'Wrong network. Expected {expected_chain_id}, got {chain_id}') return True ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } chainID, err := client.ChainID(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Chain ID: %d\n", chainID) } ``` ## Related Methods - [`net_version`](./net_version) - Get network version - [`eth_syncing`](./eth_syncing) - Check sync status --- ## eth_coinbase - Get coinbase address(Flow-evm-gateway) # eth_coinbase Get coinbase address on the Flow EVM network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_coinbase](https://ethereum.org/developers/docs/apis/json-rpc/#eth_coinbase) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_coinbase", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_coinbase', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Flow EVM documentation](/docs/base).* --- ## eth_estimateGas - Flow EVM RPC Method # eth_estimateGas Estimates the gas necessary to execute a transaction on Flow EVM Gateway. > **Why Flow EVM?** Build on the EVM-equivalent layer on Flow blockchain enabling Cadence+Solidity composability with full EVM equivalence on Flow, atomic multi-operation transactions, 40% lower gas fees, and 473% contract growth in 2025. ## Use Cases The `eth_estimateGas` method is essential for: - **Transaction preparation** - Set appropriate gas limits - **Cost estimation** - Calculate transaction costs before sending - **Error detection** - Identify reverts before spending gas - **DeFi operations** - Estimate costs for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | Sender address | | `to` | `DATA` | No | Recipient address | | `gas` | `QUANTITY` | No | Gas limit | | `gasPrice` | `QUANTITY` | No | Gas price | | `value` | `QUANTITY` | No | Value in wei | | `data` | `DATA` | No | Transaction data | ## Request ```json { "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "to": "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "value": "0x1" }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Estimated gas amount in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5208" } ``` **Note**: `0x5208` = 21000 gas (standard ETH transfer) ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "to": "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "value": "0x1" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); // Estimate simple transfer async function estimateTransfer(to, value) { const gasEstimate = await provider.estimateGas({ to: to, value: parseEther(value) }); console.log('Estimated gas:', gasEstimate.toString()); return gasEstimate; } // Estimate contract call async function estimateContractCall(contract, method, args) { const gasEstimate = await contract[method].estimateGas(...args); console.log('Estimated gas:', gasEstimate.toString()); // Add 20% buffer for safety return gasEstimate * 120n / 100n; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) def estimate_transfer(to, value_in_ether): gas_estimate = w3.eth.estimate_gas({ 'to': to, 'value': w3.to_wei(value_in_ether, 'ether') }) print(f'Estimated gas: {gas_estimate}') return gas_estimate def estimate_contract_call(contract, method, args): func = getattr(contract.functions, method) gas_estimate = func(*args).estimate_gas() # Add 20% buffer return int(gas_estimate * 1.2) # Estimate simple transfer gas = estimate_transfer('0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e', 0.1) ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } toAddress := common.HexToAddress("0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e") msg := ethereum.CallMsg{ To: &toAddress, Value: big.NewInt(1000000000000000000), } gasLimit, err := client.EstimateGas(context.Background(), msg) if err != nil { log.Fatal(err) } fmt.Printf("Estimated gas: %d\n", gasLimit) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Transaction would fail | | -32602 | Invalid params | Invalid transaction parameters | **Tip**: If estimation fails, the transaction would likely revert if sent. ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_feeHistory - Flow EVM RPC Method # eth_feeHistory Returns historical gas information on Flow EVM Gateway for fee estimation. ## Use Cases - **Fee prediction** - Estimate future gas prices based on history - **Gas analytics** - Analyze fee trends over time - **Optimal timing** - Find best times for transactions on consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockCount` | `QUANTITY` | Yes | Number of blocks in the range | | `newestBlock` | `QUANTITY\|TAG` | Yes | Highest block of the range | | `rewardPercentiles` | `Array` | Yes | Percentiles to sample for priority fees | ## Request ```json { "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const feeHistory = await provider.send('eth_feeHistory', ['0xa', 'latest', [25, 50, 75]]); console.log('Base fees:', feeHistory.baseFeePerGas.map(f => formatUnits(f, 'gwei'))); console.log('Reward (25th percentile):', feeHistory.reward.map(r => formatUnits(r[0], 'gwei'))); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) fee_history = w3.eth.fee_history(10, 'latest', [25, 50, 75]) print(f'Base fees: {[w3.from_wei(f, "gwei") for f in fee_history["baseFeePerGas"]]}') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee --- ## eth_gasPrice - Flow EVM RPC Method # eth_gasPrice Returns the current gas price on Flow EVM Gateway in wei. > **Why Flow EVM?** Build on the EVM-equivalent layer on Flow blockchain enabling Cadence+Solidity composability with full EVM equivalence on Flow, atomic multi-operation transactions, 40% lower gas fees, and 473% contract growth in 2025. ## Use Cases The `eth_gasPrice` method is essential for: - **Transaction pricing** - Set appropriate gas prices - **Cost estimation** - Calculate transaction costs before sending - **Gas monitoring** - Track network congestion - **DeFi operations** - Optimize costs for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Current gas price in wei (hexadecimal) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x3b9aca00" } ``` **Note**: `0x3b9aca00` = 1 Gwei (1,000,000,000 wei) ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); const gasPrice = feeData.gasPrice; console.log('Gas Price:', formatUnits(gasPrice, 'gwei'), 'Gwei'); // Calculate transaction cost async function estimateTransactionCost(gasLimit) { const feeData = await provider.getFeeData(); const cost = feeData.gasPrice * BigInt(gasLimit); return formatUnits(cost, 'ether'); } const cost = await estimateTransactionCost(21000); console.log('Transfer cost:', cost, 'ETH'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) gas_price = w3.eth.gas_price print(f'Gas Price: {w3.from_wei(gas_price, "gwei")} Gwei') # Calculate transaction cost def estimate_transaction_cost(gas_limit): gas_price = w3.eth.gas_price cost = gas_price * gas_limit return w3.from_wei(cost, 'ether') cost = estimate_transaction_cost(21000) print(f'Transfer cost: {cost} ETH') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } gasPrice, err := client.SuggestGasPrice(context.Background()) if err != nil { log.Fatal(err) } // Convert to Gwei gwei := new(big.Float).Quo( new(big.Float).SetInt(gasPrice), big.NewFloat(1e9), ) fmt.Printf("Gas Price: %f Gwei\n", gwei) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32603 | Internal error | Node error | ## Related Methods - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee (EIP-1559) - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas needed --- ## eth_getBalance - Flow EVM RPC Method # eth_getBalance Returns the balance of a given address on Flow EVM Gateway. > **Why Flow EVM?** Build on the EVM-equivalent layer on Flow blockchain enabling Cadence+Solidity composability with full EVM equivalence on Flow, atomic multi-operation transactions, 40% lower gas fees, and 473% contract growth in 2025. ## Use Cases The `eth_getBalance` method is essential for: - **Wallet applications** - Display user balances - **Transaction validation** - Check if account has sufficient funds - **DeFi applications** - Monitor collateral and liquidity for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications - **Account monitoring** - Track balance changes over time ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address to check balance for | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Integer of the current balance in wei (hexadecimal) | **Note**: 1 native token = 10^18 wei. Convert using `balance / 10^18`. ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1a055690d9db80000" } ``` ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e'; const balanceWei = await provider.getBalance(address); const balance = formatEther(balanceWei); console.log(`Balance: ${balance}`); // Get balance at specific block const historicalBalance = await provider.getBalance(address, 1000000); console.log(`Historical balance: ${formatEther(historicalBalance)}`); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e' balance_wei = w3.eth.get_balance(address) balance = w3.from_wei(balance_wei, 'ether') print(f'Balance: {balance}') # Get balance at specific block historical_balance = w3.eth.get_balance(address, block_identifier=1000000) print(f'Historical balance: {w3.from_wei(historical_balance, "ether")}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e") balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } // Convert to ether fbalance := new(big.Float).SetInt(balance) ethValue := new(big.Float).Quo(fbalance, big.NewFloat(1e18)) fmt.Printf("Balance: %f\n", ethValue) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid address format or block parameter | | -32000 | Execution error | Node execution error | ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_getTransactionCount`](./eth_getTransactionCount) - Get account nonce --- ## eth_getBlockByHash - Flow EVM RPC Method # eth_getBlockByHash Returns information about a block by hash on Flow EVM Gateway. > **Why Flow EVM?** Build on the EVM-equivalent layer on Flow blockchain enabling Cadence+Solidity composability with full EVM equivalence on Flow, atomic multi-operation transactions, 40% lower gas fees, and 473% contract growth in 2025. ## Use Cases The `eth_getBlockByHash` method is essential for: - **Block verification** - Verify block data using its unique hash - **Chain reorganization handling** - Track blocks during reorgs - **Cross-chain bridges** - Verify block finality for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications - **Deterministic queries** - Get consistent block data regardless of chain state ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0xee0158dc7a2e89b3de711f135d5d39f2bf5fa407233501c4b58a065bfe7089b8", false ], "id": 1 } ``` ## Returns Returns the same block object as `eth_getBlockByNumber`, or `null` if no block is found. | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used | | `transactions` | `Array` | Transaction objects or hashes | ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0xee0158dc7a2e89b3de711f135d5d39f2bf5fa407233501c4b58a065bfe7089b8", false ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0xee0158dc7a2e89b3de711f135d5d39f2bf5fa407233501c4b58a065bfe7089b8'; const block = await provider.getBlock(blockHash); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) block_hash = '0xee0158dc7a2e89b3de711f135d5d39f2bf5fa407233501c4b58a065bfe7089b8' block = w3.eth.get_block(block_hash) print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockHash := common.HexToHash("0xee0158dc7a2e89b3de711f135d5d39f2bf5fa407233501c4b58a065bfe7089b8") block, err := client.BlockByHash(context.Background(), blockHash) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block hash format | | -32000 | Block not found | Block with this hash does not exist | ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) - Get block by number - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number --- ## eth_getBlockByNumber - Flow EVM RPC Method # eth_getBlockByNumber Returns information about a block by block number on Flow EVM Gateway. > **Why Flow EVM?** Build on the EVM-equivalent layer on Flow blockchain enabling Cadence+Solidity composability with full EVM equivalence on Flow, atomic multi-operation transactions, 40% lower gas fees, and 473% contract growth in 2025. ## Use Cases The `eth_getBlockByNumber` method is essential for: - **Block explorers** - Display complete block information - **Transaction indexers** - Process all transactions in a block - **Analytics platforms** - Analyze blockchain data for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications - **Timestamp verification** - Get block timestamps for time-based logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used by all transactions | | `gasLimit` | `QUANTITY` | Maximum gas allowed in block | | `transactions` | `Array` | Array of transaction objects or hashes | | `baseFeePerGas` | `QUANTITY` | Base fee per gas (EIP-1559) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": { "number": "0x5BAD55", "hash": "0xee0158dc7a2e89b3de711f135d5d39f2bf5fa407233501c4b58a065bfe7089b8", "parentHash": "0x...", "timestamp": "0x64d8f6d0", "gasUsed": "0x1234", "gasLimit": "0x1c9c380", "transactions": [], "baseFeePerGas": "0x5f5e100" } } ``` ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); // Get latest block const block = await provider.getBlock('latest'); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); console.log('Transactions:', block.transactions.length); // Get block with full transactions const blockWithTxs = await provider.getBlock('latest', true); for (const tx of blockWithTxs.prefetchedTransactions) { console.log('Transaction:', tx.hash); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) # Get latest block block = w3.eth.get_block('latest') print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') print(f'Transactions: {len(block.transactions)}') # Get block with full transactions block_full = w3.eth.get_block('latest', full_transactions=True) for tx in block_full.transactions: print(f'Transaction: {tx.hash.hex()}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } // Get latest block block, err := client.BlockByNumber(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) fmt.Printf("Timestamp: %d\n", block.Time()) fmt.Printf("Transactions: %d\n", len(block.Transactions())) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block number or parameter format | | -32000 | Block not found | Block does not exist | ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number - [`eth_getBlockByHash`](./eth_getBlockByHash) - Get block by hash - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_getCode - Flow EVM RPC Method # eth_getCode Returns the bytecode at a given address on Flow EVM Gateway. > **Why Flow EVM?** Build on the EVM-equivalent layer on Flow blockchain enabling Cadence+Solidity composability with full EVM equivalence on Flow, atomic multi-operation transactions, 40% lower gas fees, and 473% contract growth in 2025. ## Use Cases The `eth_getCode` method is essential for: - **Contract verification** - Check if address is a contract - **Security analysis** - Verify deployed bytecode matches expected - **DeFi integrations** - Validate contracts before interactions - **Protocol analysis** - Analyze contract deployments for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Contract bytecode or `0x` if EOA | ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e'; const code = await provider.getCode(address); if (code === '0x') { console.log('Address is an EOA (externally owned account)'); } else { console.log('Address is a contract'); console.log('Bytecode length:', code.length); } // Check if address is a contract async function isContract(address) { const code = await provider.getCode(address); return code !== '0x'; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e' code = w3.eth.get_code(address) if code == b'': print('Address is an EOA') else: print('Address is a contract') print(f'Bytecode length: {len(code.hex())}') # Check if address is a contract def is_contract(address): code = w3.eth.get_code(address) return code != b'' ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e") code, err := client.CodeAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } if len(code) == 0 { fmt.Println("Address is an EOA") } else { fmt.Printf("Contract bytecode length: %d\n", len(code)) } } ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_getStorageAt`](./eth_getStorageAt) - Get contract storage --- ## eth_getFilterChanges - Flow EVM RPC Method # eth_getFilterChanges Polling method for a filter on Flow EVM Gateway, returns an array of logs since last poll. ## Use Cases - **Event streaming** - Get new events incrementally - **Real-time monitoring** - Track contract activity for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications - **Efficient indexing** - Process only new events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); // Poll loop async function pollFilter(filterId, interval = 2000) { while (true) { const changes = await provider.send('eth_getFilterChanges', [filterId]); if (changes.length > 0) { console.log('New events:', changes); } await new Promise(r => setTimeout(r, interval)); } } ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter --- ## eth_getFilterLogs - Flow EVM RPC Method # eth_getFilterLogs Returns an array of all logs matching filter with given ID on Flow EVM Gateway. ## Use Cases - **Historical queries** - Get all matching logs for a filter - **Full event history** - Retrieve complete event data for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const logs = await provider.send('eth_getFilterLogs', [filterId]); console.log('All matching logs:', logs.length); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_getLogs - Flow EVM RPC Method # eth_getLogs Returns an array of all logs matching a given filter object on Flow EVM Gateway. > **Why Flow EVM?** Build on the EVM-equivalent layer on Flow blockchain enabling Cadence+Solidity composability with full EVM equivalence on Flow, atomic multi-operation transactions, 40% lower gas fees, and 473% contract growth in 2025. ## Use Cases The `eth_getLogs` method is essential for: - **Event indexing** - Track contract events for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications - **Token transfers** - Monitor ERC20/ERC721 transfers - **DeFi analytics** - Track swaps, liquidity events, and more - **Notification systems** - Alert on specific on-chain events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block (default: `"latest"`) | | `toBlock` | `QUANTITY\|TAG` | No | Ending block (default: `"latest"`) | | `address` | `DATA\|Array` | No | Contract address(es) to filter | | `topics` | `Array` | No | Array of topic filters | | `blockHash` | `DATA` | No | Filter single block by hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns Array of log objects: | Field | Type | Description | |-------|------|-------------| | `address` | `DATA` | Contract that emitted the log | | `topics` | `Array` | Array of indexed topics | | `data` | `DATA` | Non-indexed log data | | `blockNumber` | `QUANTITY` | Block number | | `transactionHash` | `DATA` | Transaction hash | | `logIndex` | `QUANTITY` | Log index in block | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": [{ "address": "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."], "data": "0x...", "blockNumber": "0x5BAD55", "transactionHash": "0x...", "logIndex": "0x0" }] } ``` ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); // Get Transfer events const TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'; async function getTransferEvents(tokenAddress, fromBlock, toBlock) { const logs = await provider.getLogs({ address: tokenAddress, topics: [TRANSFER_TOPIC], fromBlock: fromBlock, toBlock: toBlock }); return logs.map(log => ({ from: '0x' + log.topics[1].slice(26), to: '0x' + log.topics[2].slice(26), blockNumber: log.blockNumber, transactionHash: log.transactionHash })); } const events = await getTransferEvents( '0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e', 'latest', 'latest' ); console.log('Transfer events:', events); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' def get_transfer_events(token_address, from_block, to_block): logs = w3.eth.get_logs({ 'address': token_address, 'topics': [TRANSFER_TOPIC], 'fromBlock': from_block, 'toBlock': to_block }) events = [] for log in logs: events.append({ 'from': '0x' + log['topics'][1].hex()[26:], 'to': '0x' + log['topics'][2].hex()[26:], 'block': log['blockNumber'], 'tx': log['transactionHash'].hex() }) return events events = get_transfer_events( '0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e', 'latest', 'latest' ) print(f'Found {len(events)} transfer events') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e") transferTopic := common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef") query := ethereum.FilterQuery{ FromBlock: big.NewInt(0), ToBlock: nil, Addresses: []common.Address{contractAddress}, Topics: [][]common.Hash, } logs, err := client.FilterLogs(context.Background(), query) if err != nil { log.Fatal(err) } fmt.Printf("Found %d events\n", len(logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32005 | Query returned more than 10000 results | Reduce block range | | -32602 | Invalid params | Invalid filter parameters | ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create a filter for logs - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for new logs --- ## eth_getStorageAt - Flow EVM RPC Method # eth_getStorageAt Returns the value from a storage position at a given address on Flow EVM Gateway. ## Use Cases - **Contract analysis** - Read raw storage values - **State verification** - Verify contract state - **Security auditing** - Analyze storage layout for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications - **Protocol monitoring** - Track state changes ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte contract address | | `position` | `QUANTITY` | Yes | Storage slot position | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "0x0", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "0x0", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e'; const slot = 0; const storage = await provider.getStorage(address, slot); console.log('Storage at slot 0:', storage); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e' storage = w3.eth.get_storage_at(address, 0) print(f'Storage at slot 0: {storage.hex()}') ``` ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_call`](./eth_call) - Call contract functions --- ## eth_getTransactionByHash - Flow EVM RPC Method # eth_getTransactionByHash Returns the information about a transaction by transaction hash on Flow EVM Gateway. > **Why Flow EVM?** Build on the EVM-equivalent layer on Flow blockchain enabling Cadence+Solidity composability with full EVM equivalence on Flow, atomic multi-operation transactions, 40% lower gas fees, and 473% contract growth in 2025. ## Use Cases The `eth_getTransactionByHash` method is essential for: - **Transaction tracking** - Get details of pending or confirmed transactions - **Payment verification** - Verify transaction parameters - **Debugging** - Analyze transaction data for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications - **Block explorers** - Display transaction information ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0xac905cb8672fe39508dab7199529d77b32d459242ad9d3f6799e4e427d6003f8"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `hash` | `DATA` | Transaction hash | | `from` | `DATA` | Sender address | | `to` | `DATA` | Recipient address | | `value` | `QUANTITY` | Value in wei | | `gas` | `QUANTITY` | Gas provided | | `gasPrice` | `QUANTITY` | Gas price in wei | | `input` | `DATA` | Transaction input data | | `nonce` | `QUANTITY` | Sender's nonce | | `blockHash` | `DATA` | Block hash (null if pending) | | `blockNumber` | `QUANTITY` | Block number (null if pending) | ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0xac905cb8672fe39508dab7199529d77b32d459242ad9d3f6799e4e427d6003f8"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const txHash = '0xac905cb8672fe39508dab7199529d77b32d459242ad9d3f6799e4e427d6003f8'; const tx = await provider.getTransaction(txHash); if (tx) { console.log('From:', tx.from); console.log('To:', tx.to); console.log('Value:', formatEther(tx.value)); console.log('Block:', tx.blockNumber); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0xac905cb8672fe39508dab7199529d77b32d459242ad9d3f6799e4e427d6003f8' tx = w3.eth.get_transaction(tx_hash) if tx: print(f'From: {tx["from"]}') print(f'To: {tx["to"]}') print(f'Value: {w3.from_wei(tx["value"], "ether")}') print(f'Block: {tx["blockNumber"]}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0xac905cb8672fe39508dab7199529d77b32d459242ad9d3f6799e4e427d6003f8") tx, isPending, err := client.TransactionByHash(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Pending: %v\n", isPending) fmt.Printf("Value: %s\n", tx.Value().String()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash format | ## Related Methods - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction receipt - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionCount - Flow EVM RPC Method # eth_getTransactionCount Returns the number of transactions sent from an address on Flow EVM Gateway (the nonce). ## Use Cases - **Transaction building** - Get correct nonce for new transactions - **Account analysis** - Count total outgoing transactions - **Nonce management** - Handle pending transaction queues - **Wallet operations** - Prepare transactions for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag (`pending` for next nonce) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e'; const nonce = await provider.getTransactionCount(address); console.log('Nonce:', nonce); // Get pending nonce for new transaction const pendingNonce = await provider.getTransactionCount(address, 'pending'); console.log('Next nonce:', pendingNonce); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e' nonce = w3.eth.get_transaction_count(address) print(f'Nonce: {nonce}') # Get pending nonce pending_nonce = w3.eth.get_transaction_count(address, 'pending') print(f'Next nonce: {pending_nonce}') ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionReceipt - Flow EVM RPC Method # eth_getTransactionReceipt Returns the receipt of a transaction by transaction hash on Flow EVM Gateway. Receipt is only available for mined transactions. > **Why Flow EVM?** Build on the EVM-equivalent layer on Flow blockchain enabling Cadence+Solidity composability with full EVM equivalence on Flow, atomic multi-operation transactions, 40% lower gas fees, and 473% contract growth in 2025. ## Use Cases The `eth_getTransactionReceipt` method is essential for: - **Transaction confirmation** - Verify transaction was mined successfully - **Gas analysis** - Check actual gas used vs estimated - **Event parsing** - Read emitted events from logs - **Status verification** - Confirm success/failure for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0xac905cb8672fe39508dab7199529d77b32d459242ad9d3f6799e4e427d6003f8"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `status` | `QUANTITY` | `1` (success) or `0` (failure) | | `transactionHash` | `DATA` | Transaction hash | | `blockHash` | `DATA` | Block hash | | `blockNumber` | `QUANTITY` | Block number | | `gasUsed` | `QUANTITY` | Gas used by this transaction | | `cumulativeGasUsed` | `QUANTITY` | Total gas used in block up to this tx | | `logs` | `Array` | Array of log objects | | `contractAddress` | `DATA` | Created contract address (if deployment) | ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0xac905cb8672fe39508dab7199529d77b32d459242ad9d3f6799e4e427d6003f8"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const txHash = '0xac905cb8672fe39508dab7199529d77b32d459242ad9d3f6799e4e427d6003f8'; const receipt = await provider.getTransactionReceipt(txHash); if (receipt) { console.log('Status:', receipt.status === 1 ? 'Success' : 'Failed'); console.log('Gas Used:', receipt.gasUsed.toString()); console.log('Block:', receipt.blockNumber); console.log('Logs:', receipt.logs.length); // Parse specific events for (const log of receipt.logs) { console.log('Event from:', log.address); } } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0xac905cb8672fe39508dab7199529d77b32d459242ad9d3f6799e4e427d6003f8' receipt = w3.eth.get_transaction_receipt(tx_hash) if receipt: status = 'Success' if receipt['status'] == 1 else 'Failed' print(f'Status: {status}') print(f'Gas Used: {receipt["gasUsed"]}') print(f'Block: {receipt["blockNumber"]}') print(f'Logs: {len(receipt["logs"])}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0xac905cb8672fe39508dab7199529d77b32d459242ad9d3f6799e4e427d6003f8") receipt, err := client.TransactionReceipt(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Status: %d\n", receipt.Status) fmt.Printf("Gas Used: %d\n", receipt.GasUsed) fmt.Printf("Logs: %d\n", len(receipt.Logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash | **Note**: Returns `null` if transaction is not yet mined. ## Related Methods - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details - [`eth_getLogs`](./eth_getLogs) - Query logs by filter --- ## eth_hashrate - Get node hashrate(Flow-evm-gateway) # eth_hashrate Get node hashrate on the Flow EVM network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_hashrate](https://ethereum.org/developers/docs/apis/json-rpc/#eth_hashrate) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_hashrate", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_hashrate', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Flow EVM documentation](/docs/base).* --- ## eth_maxPriorityFeePerGas - Flow EVM RPC Method # eth_maxPriorityFeePerGas Returns the current recommended priority fee per gas on Flow EVM Gateway for EIP-1559 transactions. ## Use Cases - **EIP-1559 transactions** - Set appropriate priority fees - **Transaction acceleration** - Calculate tips for faster inclusion - **Gas optimization** - Balance speed vs cost for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); console.log('Max Priority Fee:', formatUnits(feeData.maxPriorityFeePerGas, 'gwei'), 'Gwei'); console.log('Max Fee Per Gas:', formatUnits(feeData.maxFeePerGas, 'gwei'), 'Gwei'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) priority_fee = w3.eth.max_priority_fee print(f'Max Priority Fee: {w3.from_wei(priority_fee, "gwei")} Gwei') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get legacy gas price - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data --- ## eth_mining - Check if node is mining(Flow-evm-gateway) # eth_mining Check if node is mining on the Flow EVM network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_mining](https://ethereum.org/developers/docs/apis/json-rpc/#eth_mining) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_mining', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Flow EVM documentation](/docs/base).* --- ## eth_newBlockFilter - Flow EVM RPC Method # eth_newBlockFilter Creates a filter on Flow EVM Gateway to notify when a new block arrives. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newBlockFilter', []); // Poll for new blocks const newBlocks = await provider.send('eth_getFilterChanges', [filterId]); console.log('New block hashes:', newBlocks); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_blockNumber`](./eth_blockNumber) - Get current block --- ## eth_newFilter - Flow EVM RPC Method # eth_newFilter Creates a filter object on Flow EVM Gateway to notify when state changes (logs). ## Use Cases - **Event monitoring** - Subscribe to contract events - **Real-time updates** - Track events for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications - **Indexing** - Build event indexes incrementally ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block | | `toBlock` | `QUANTITY\|TAG` | No | Ending block | | `address` | `DATA\|Array` | No | Contract address(es) | | `topics` | `Array` | No | Topic filters | ## Request ```json { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); // Create filter const filterId = await provider.send('eth_newFilter', [{ fromBlock: 'latest', address: '0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e', topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'] }]); // Poll for changes const changes = await provider.send('eth_getFilterChanges', [filterId]); console.log('New events:', changes); // Cleanup await provider.send('eth_uninstallFilter', [filterId]); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for changes - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_newPendingTransactionFilter - Flow EVM RPC Method # eth_newPendingTransactionFilter Creates a filter on Flow EVM Gateway to notify when new pending transactions arrive. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newPendingTransactionFilter', []); // Poll for pending transactions const pendingTxs = await provider.send('eth_getFilterChanges', [filterId]); console.log('Pending transaction hashes:', pendingTxs); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_protocolVersion - Get protocol version(Flow-evm-gateway) # eth_protocolVersion Get protocol version on the Flow EVM network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_protocolVersion](https://ethereum.org/developers/docs/apis/json-rpc/#eth_protocolversion) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_protocolVersion", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_protocolVersion', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Flow EVM documentation](/docs/base).* --- ## eth_sendRawTransaction - Flow EVM RPC Method # eth_sendRawTransaction Submits a pre-signed transaction for broadcast to Flow EVM Gateway. > **Why Flow EVM?** Build on the EVM-equivalent layer on Flow blockchain enabling Cadence+Solidity composability with full EVM equivalence on Flow, atomic multi-operation transactions, 40% lower gas fees, and 473% contract growth in 2025. ## Use Cases The `eth_sendRawTransaction` method is essential for: - **Broadcasting transactions** - Submit signed transactions to the network - **Wallet operations** - Send native tokens and interact with contracts - **DeFi operations** - Execute swaps, provide liquidity for consumer NFTs (NBA Top Shot, Disney Pinnacle), gaming dApps, and hybrid Cadence-EVM applications - **Batch operations** - Submit multiple transactions efficiently ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `signedTransactionData` | `DATA` | Yes | The signed transaction data (RLP encoded) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | 32-byte transaction hash | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c808504a817c80082520894..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const wallet = new Wallet('YOUR_PRIVATE_KEY', provider); // Send native tokens async function sendTransaction(to, value) { const tx = await wallet.sendTransaction({ to: to, value: parseEther(value) }); console.log('Transaction hash:', tx.hash); // Wait for confirmation const receipt = await tx.wait(); console.log('Confirmed in block:', receipt.blockNumber); return receipt; } // Send to contract async function sendContractTransaction(contract, method, args, value = '0') { const tx = await contract[method](...args, { value: parseEther(value) }); return await tx.wait(); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY')) def send_transaction(private_key, to, value_in_ether): account = w3.eth.account.from_key(private_key) # Build transaction tx = { 'nonce': w3.eth.get_transaction_count(account.address), 'to': to, 'value': w3.to_wei(value_in_ether, 'ether'), 'gas': 21000, 'gasPrice': w3.eth.gas_price, 'chainId': w3.eth.chain_id } # Sign transaction signed_tx = account.sign_transaction(tx) # Send transaction tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) print(f'Transaction hash: {tx_hash.hex()}') # Wait for confirmation receipt = w3.eth.wait_for_transaction_receipt(tx_hash) print(f'Confirmed in block: {receipt["blockNumber"]}') return receipt ``` ```go package main "context" "crypto/ecdsa" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY") if err != nil { log.Fatal(err) } publicKey := privateKey.Public() publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey) fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA) nonce, _ := client.PendingNonceAt(context.Background(), fromAddress) value := big.NewInt(1000000000000000000) gasLimit := uint64(21000) gasPrice, _ := client.SuggestGasPrice(context.Background()) toAddress := common.HexToAddress("0xd3bF53DAC106A0290B0483EcBC89d40FcC961f3e") tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil) chainID, _ := client.NetworkID(context.Background()) signedTx, _ := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey) err = client.SendTransaction(context.Background(), signedTx) if err != nil { log.Fatal(err) } fmt.Printf("Transaction hash: %s\n", signedTx.Hash().Hex()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Nonce too low | Transaction nonce already used | | -32000 | Insufficient funds | Account has insufficient balance | | -32000 | Gas too low | Gas limit insufficient | | -32000 | Replacement underpriced | Gas price too low for replacement | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas required - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction result --- ## eth_sendTransaction - Send transaction (wal...(Flow-evm-gateway) # eth_sendTransaction > **Important**: Dwellir's shared Flow EVM endpoints do not manage user private keys. JSON-RPC nodes cannot unlock your account, so `eth_sendTransaction` calls will fail. Sign transactions client-side and broadcast them with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Why this method is disabled on shared nodes - [`eth_sendTransaction` requires the node to hold and unlock the `from` account's private key](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction). - Managed infrastructure providers disable it for security reasons rather than storing customer keys on shared servers (for example, [Infura explicitly blocks the method on shared endpoints](https://docs.infura.io/api/networks/ethereum/json-rpc-methods/eth_sendtransaction)). ## Recommended workflow 1. Build the raw transaction locally with your wallet or SDK. 2. Sign the payload client-side (hardware wallet, custodial service, or library). 3. Submit the signed hex string with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Example response from the shared endpoint ```bash curl -s -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"0x0000000000000000000000000000000000000000"}],"id":1}' ``` ```json {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"unknown account"}} ``` Need help? Contact our [support team](mailto:support@dwellir.com) or use the dedicated [`eth_sendRawTransaction`](./eth_sendRawTransaction) guide. --- ## eth_signTransaction - Sign transaction (rar...(Flow-evm-gateway) # eth_signTransaction Signs a transaction using an unlocked account on the node. **Important**: Most RPC providers don't support this method for security reasons, as it requires private keys to be stored on the server. ## Security Considerations - This method requires an unlocked account on the node - Private keys must be available to the RPC server - Most production RPC providers disable this method - Use client-side signing libraries instead for better security ## Parameters 1. `Object` - The transaction object: - `from`: `DATA`, 20 Bytes - The address the transaction is sent from - `to`: `DATA`, 20 Bytes - (optional) The address the transaction is directed to - `gas`: `QUANTITY` - (optional) Integer of the gas provided for the transaction execution - `gasPrice`: `QUANTITY` - (optional) Integer of the gasPrice used for each paid gas - `value`: `QUANTITY` - (optional) Integer of the value sent with this transaction - `data`: `DATA` - (optional) The compiled code of a contract OR the hash of the invoked method signature and encoded parameters ## Returns `DATA` - The signed transaction data, ready for transmission via `eth_sendRawTransaction`. ## Implementation Example ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_signTransaction", "params": [{ "from": "0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a" }], "id": 1 }' ``` ```javascript const response = await fetch('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_signTransaction', params: [{ from: '0x9b2055d370f73ec7d8a03e965129118dc8f5bf83', to: '0xd46e8dd67c5d32be8058bb8eb970870f07244567', gas: '0x76c0', gasPrice: '0x9184e72a000', value: '0x9184e72a' }], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0xf86c808504a817c8008276c094d46e8dd67c5d32be8058bb8eb970870f072445675849184e72a8001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804" } ``` **Note**: This method is typically not available on hosted RPC providers for security reasons. The response shows a signed transaction ready for broadcast. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Flow EVM documentation](/docs/base).* --- ## eth_syncing - Flow EVM RPC Method # eth_syncing Returns syncing status of Flow EVM Gateway node. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 } ``` ## Returns Returns `false` if not syncing, or an object with sync status. ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const syncing = await provider.send('eth_syncing', []); if (syncing === false) { console.log('Node is fully synced'); } else { console.log('Syncing:', syncing); } ``` ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get current block - [`net_peerCount`](./net_peerCount) - Get peer count --- ## eth_uninstallFilter - Flow EVM RPC Method # eth_uninstallFilter Uninstalls a filter on Flow EVM Gateway. Should be called when no longer needed. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID to uninstall | ## Request ```json { "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if filter was found and uninstalled | ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const success = await provider.send('eth_uninstallFilter', [filterId]); console.log('Filter removed:', success); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter --- ## Flow EVM RPC with Dwellir # Flow EVM – Build on the EVM on Flow ## Why Build on Flow EVM? Flow EVM brings Ethereum compatibility to the Flow ecosystem so you can reuse your Solidity code, tools, and workflows with minimal changes. - EVM JSON-RPC compatible: works with ethers, viem, web3.js, and web3.py - Common frameworks: Hardhat, Foundry, and Truffle supported - Familiar UX: MetaMask and other EVM wallets connect seamlessly - Dwellir infra: global anycast, Archive/Trace/Debug/WebSocket support, and 99.99% uptime SLA ## Quick Start with Flow EVM Connect to Flow EVM in seconds with Dwellir's optimized endpoints: ### Installation & Setup ```javascript // Connect to Flow EVM mainnet const provider = new JsonRpcProvider( 'https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY' ); // Get the latest block const block = await provider.getBlock('latest'); console.log('Latest block:', block.number); // Query account balance const balance = await provider.getBalance('0x...'); console.log('Balance:', balance.toString()); ``` ```javascript const Web3 = require('web3'); // Connect to Flow EVM mainnet const web3 = new Web3( 'https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY' ); // Get chain ID to verify connection const chainId = await web3.eth.getChainId(); console.log('Connected to Flow EVM:', chainId === 747); // Get gas price for optimal transaction pricing const gasPrice = await web3.eth.getGasPrice(); console.log('Current gas price:', gasPrice); ``` ```typescript // Create Flow EVM client const client = createPublicClient({ transport: http('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'), }); // Read contract data const data = await client.readContract({ address: '0x...', abi: contractAbi, functionName: 'balanceOf', args: ['0x...'], }); ``` ```python from web3 import Web3 # Connect to Flow EVM mainnet web3 = Web3(Web3.HTTPProvider( 'https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY' )) # Verify connection print('Connected:', web3.is_connected()) print('Chain ID:', web3.eth.chain_id) # Get latest block latest_block = web3.eth.get_block('latest') print(f'Latest block: {latest_block.number}') ``` ## Network Information Mainnet Chain ID 747 (0x2eb) Flow EVM Mainnet Testnet Chain ID 545 (0x221) Flow EVM Testnet RPC Standard Ethereum JSON-RPC 2.0 EVM-compatible ## JSON-RPC API Reference Flow EVM supports the full [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/). ## Common Integration Patterns ### 🔄 Transaction Monitoring Monitor pending and confirmed transactions efficiently: ```javascript // Watch for transaction confirmation async function waitForTransaction(txHash, confirmations = 1) { return provider.waitForTransaction(txHash, confirmations); } ``` ### 💰 Gas Optimization Optimize gas costs on Flow EVM: ```javascript // Get current fee data (EIP-1559) const feeData = await provider.getFeeData(); // Estimate gas for transaction const gasEstimate = await provider.estimateGas(tx); // Calculate total cost (approx.) const totalCost = gasEstimate * (feeData.gasPrice ?? 0n); console.log('Estimated cost:', totalCost); ``` ### 🔍 Event Filtering Efficiently query contract events: ```javascript // Query events with automatic retry and pagination async function getEvents(contract, eventName, fromBlock = 0) { const filter = contract.filters[eventName](); const events = []; const batchSize = 2000; // Recommended batch size for (let i = fromBlock; i <= currentBlock; i += batchSize) { const batch = await contract.queryFilter( filter, i, Math.min(i + batchSize - 1, currentBlock) ); events.push(...batch); } return events; } ``` ## Performance Best Practices ### 1. **Batch Requests** Combine multiple RPC calls for optimal performance: ```javascript const batch = [ { method: 'eth_blockNumber', params: [] }, { method: 'eth_gasPrice', params: [] }, { method: 'eth_getBalance', params: [address, 'latest'] } ]; const results = await provider.send(batch); ``` ### 2. **Connection Pooling** Reuse provider instances to minimize connection overhead: ```javascript class FlowProvider { static instance = null; static getInstance() { if (!this.instance) { this.instance = new JsonRpcProvider( 'https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY' ); } return this.instance; } } ``` ### 3. **Smart Caching** Cache immutable data to reduce API calls: ```javascript const cache = new Map(); async function getCachedBlockData(blockNumber) { const key = `block_${blockNumber}`; if (!cache.has(key)) { const block = await provider.getBlock(blockNumber); cache.set(key, block); } return cache.get(key); } ``` ## Troubleshooting Common Issues ### Error: "Transaction underpriced" Flow EVM uses EIP-1559 pricing. Always use dynamic gas pricing: ```javascript // Get current fee data const feeData = await provider.getFeeData(); const tx = { to: recipient, value: amount, maxFeePerGas: feeData.maxFeePerGas, maxPriorityFeePerGas: feeData.maxPriorityFeePerGas, gasLimit: 21000n }; ``` ### Error: "Rate limit exceeded" Implement exponential backoff for resilient applications: ```javascript async function callWithRetry(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error.code === 429 && i < maxRetries - 1) { await new Promise(r => setTimeout(r, 2 ** i * 1000)); } else { throw error; } } } } ``` ## Migration Guide ### From Ethereum Mainnet Moving from Ethereum to Flow EVM requires minimal changes: ```javascript // Before (Ethereum) const provider = new JsonRpcProvider('https://eth-rpc.example.com'); // After (Flow EVM) const provider = new JsonRpcProvider( 'https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY' ); // ✅ Smart contracts work identically // ✅ Same tooling and libraries // ⚠️ Different chain ID (747) // ⚠️ Separate block numbers ``` ## Resources & Tools ### Need Help? - 📧 **Email**: support@dwellir.com - 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com) - 🔑 **Get Access**: [Get your API key →](https://dashboard.dwellir.com/register) --- ## net_listening - Flow EVM RPC Method # net_listening Returns `true` if client is actively listening for network connections on Flow EVM Gateway. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if listening | ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const listening = await provider.send('net_listening', []); console.log('Node listening:', listening); ``` ## Related Methods - [`net_peerCount`](./net_peerCount) - Get peer count --- ## net_peerCount - Flow EVM RPC Method # net_peerCount Returns number of peers currently connected to Flow EVM Gateway client. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Number of connected peers (hexadecimal) | ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const peerCount = await provider.send('net_peerCount', []); console.log('Peer count:', parseInt(peerCount, 16)); ``` ## Related Methods - [`net_listening`](./net_listening) - Check if listening --- ## net_version - Flow EVM RPC Method # net_version Returns the current network ID on Flow EVM Gateway. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Network ID as a string | ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const networkId = await provider.send('net_version', []); console.log('Network ID:', networkId); ``` ## Related Methods - [`eth_chainId`](./eth_chainId) - Get chain ID --- ## web3_clientVersion - Flow EVM RPC Method # web3_clientVersion Returns the current client version on Flow EVM Gateway. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Client version string | ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); const version = await provider.send('web3_clientVersion', []); console.log('Client version:', version); ``` --- ## web3_sha3 - Flow EVM RPC Method # web3_sha3 Returns Keccak-256 (not standard SHA3-256) of the given data on Flow EVM Gateway. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `data` | `DATA` | Yes | Data to hash | ## Request ```json { "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Keccak-256 hash of the data | ## Code Examples ```bash curl -X POST https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-flow-evm-gateway-mainnet.n.dwellir.com/YOUR_API_KEY'); // Using RPC const hash = await provider.send('web3_sha3', ['0x68656c6c6f']); console.log('Hash:', hash); // Using ethers directly (faster) const localHash = keccak256(toUtf8Bytes('hello')); console.log('Local hash:', localHash); ``` --- ## Pricing The fairest pricing in the industry! 1 RPC Response = 1 API Credit. No compute units to calculate! Add unlimited team members and use trace and debug methods on all of our paid plans. ## Plans Overview | Feature | Free | Developer | Growth | Scale | Enterprise | |---------|---------|-----------|--------|-------|------------| | **Price** | **Free** | **$49**/month | **$299**/month | **$999**/month | **Custom** | | **Best For** | Getting started | Individual developers | Growing teams | High-traffic apps | Enterprise scale | | **Rate Limit** | 20 responses/sec | 100 responses/sec | 500 responses/sec | 2000 responses/sec | Custom | | **API Credits** | 500K daily limit | 25M/month | 150M/month | 500M/month | Custom | | **Blockchains** | 140+ | 140+ | 140+ | 140+ | 140+ | | **HTTP API** | ✅ | ✅ | ✅ | ✅ | ✅ | | **WebSocket API** | ✅ | ✅ | ✅ | ✅ | ✅ | | **Trace APIs** | ❌ | ✅ | ✅ | ✅ | ✅ | | **Debug APIs** | ❌ | ✅ | ✅ | ✅ | ✅ | | **Autoscaling** | ❌ | ✅ | ✅ | ✅ | ✅ | | **Support** | Community | Chat | Dedicated Manager | Dedicated Manager | Priority | | **Pay in Crypto** | ❌ | ❌ | ❌ | ✅ | ✅ | | **Extra Credits** | N/A | $5 per million | $3 per million | $2 per million | Volume discounts | | **Custom SLA** | ❌ | ❌ | ❌ | ❌ | ✅ | | **Dedicated Infrastructure** | ❌ | ❌ | ❌ | ❌ | ✅ | [Contact Sales](https://www.dwellir.com/contact) for Enterprise custom pricing. ## What Makes Our Pricing Fair? ### No Compute Units We dislike compute units as much as you do. At Dwellir: - **1 RPC response = 1 API credit** - Even for expensive trace and debug methods - No surprise bills at the end of the month - Simple, predictable pricing ### WebSocket Pricing WebSocket connections are billed the same way as HTTP requests - simple and transparent: - **1 WebSocket response = 1 API credit** - You are only charged for responses you receive, not for maintaining the connection - Real-time subscriptions (like new block headers or pending transactions) count each notification as one response - Same pricing applies whether you use HTTP or WebSocket APIs - No additional fees or compute unit multipliers for WebSocket connections ### Transparent Billing - No hidden fees - All costs clearly outlined - Set usage limits per API key to avoid overages - Real-time usage tracking in dashboard ### Flexible Plans - Upgrade or downgrade anytime - Changes take effect at the next billing cycle - Monthly billing for all paid plans - Extra credits billed at end of month at per-unit rate ## Burst Protection All plans include burst protection using the token bucket algorithm: - Exceed your rate limit for short periods - Automatic burst capacity included - Helps handle legitimate traffic spikes - No additional charges for burst usage ## Included in All Paid Plans - ✅ Access to 140+ blockchain networks - ✅ Unlimited team members - ✅ Trace and debug methods - ✅ WebSocket connections - ✅ Archive node access (select networks) - ✅ Real-time analytics dashboard - ✅ API key management - ✅ Usage alerts ## Billing FAQ ### How does billing work? We bill monthly for your chosen plan. Any extra credits used beyond your plan's allocation are billed at the end of the month at the per-unit rate specific to your plan. ### Can I set spending limits? Yes! You can set usage limits for each API key to avoid unexpected charges. Once a key reaches its limit, requests will be blocked until you increase the limit or the next billing cycle begins. ### What payment methods do you accept? - Credit/debit cards (all major providers) - Bank transfers (Enterprise plans) - Cryptocurrency (Scale and Enterprise plans) ### Is there a free trial? Start with our Free plan to test our infrastructure. ## Ready to Get Started? [Create an Account](https://dashboard.dwellir.com/register) and get your API key in minutes! --- ## Rate Limits Rate limits ensure fair usage and optimal performance for all users. Understanding and managing your rate limits is crucial for building reliable applications. ## Rate Limits by Plan | Features | Free | Developer | Growth | Scale | |----------|---------|-----------|--------|-------| | **Price** | Free | $49/mo | $299/mo | $999/mo | | **Overages** | ✗ | $5/million | $3/million | $2/million | | **Responses per second** | 20 | 100 | 500 | 2,000 | | **Responses per second (burst)** | ✗ | 500 | 2,500 | 10,000 | ## Token Bucket Algorithm Dwellir uses the **token bucket algorithm** for rate limiting, providing flexible and fair request handling with burst protection. ### How It Works The token bucket algorithm works like a bucket that: 1. **Holds tokens** - Each token represents permission to make one request 2. **Has a maximum capacity** - The bucket can hold up to your burst limit 3. **Refills at a constant rate** - Tokens are added at your plan's responses/second rate 4. **Consumes tokens per request** - Each API call removes one token ``` ┌─────────────────────────┐ │ Token Bucket │ │ │ │ Capacity: 500 tokens │ ← Burst capacity │ Current: 350 tokens │ │ Refill: 100 tokens/s │ ← Your plan's rate │ │ └─────────────────────────┘ ↓ API Response (consumes 1 token) ``` ### Benefits of Token Bucket 1. **Burst Handling** - Handle traffic spikes gracefully 2. **Smooth Rate Limiting** - No hard cutoffs at exact intervals 3. **Fair Usage** - Unused capacity accumulates for later use 4. **Predictable Behavior** - Easy to understand and plan for ### Example Scenarios #### Scenario 1: Steady Traffic - Plan: Developer (100 responses/s) - Usage: 80 responses/s consistently - Result: ✅ All requests succeed, 20 tokens/s accumulate up to burst limit #### Scenario 2: Traffic Burst - Plan: Developer (100 responses/s, 500 burst capacity) - Usage: 300 responses/s for 1 second - Result: ✅ All requests succeed using burst tokens - Recovery: Need to stay under 100 responses/s to refill #### Scenario 3: Sustained Overuse - Plan: Developer (100 responses/s) - Usage: 150 responses/s sustained - Result: ⚠️ After burst depletes, 50 responses/s are rate limited ## Request Counting ### What Counts as a Response? Each of the following counts as **1 API response**: - Standard JSON-RPC calls (`eth_getBalance`, `eth_call`, etc.) - Batch requests count as the number of calls in the batch - WebSocket messages (both sent and received) - **Even trace and debug methods** (no compute unit multipliers!) ## Handling Rate Limit Errors When you exceed your rate limit, you'll receive a 429 HTTP status code with the following response: ```json { "jsonrpc": "2.0", "error": { "code": -32005, "message": "Rate limit exceeded" }, "id": 1 } ``` ## Setting Usage Limits Protect yourself from unexpected charges by setting limits per API key: 1. Go to [dashboard.dwellir.com/api-keys](https://dashboard.dwellir.com/api-keys) 2. Click the edit icon (✏️) next to your API key 3. Set daily or monthly quotas 4. Click "Update API Key" to save When a quota is reached, the API will return a 429 error until the quota resets. ## Monitoring Your Usage ### Dashboard Analytics Track your usage in real-time at [dashboard.dwellir.com/usage](https://dashboard.dwellir.com/usage): - Current responses/second - Daily and monthly usage - Per-method breakdown - Geographic distribution ### API Access For programmatic access to usage data, please [contact our team](https://www.dwellir.com/contact). ## Need Higher Limits? If you need higher rate limits: 1. **Upgrade Your Plan** - Check if a higher tier meets your needs 2. **Contact Support** - Request custom limits within your current plan 3. **Enterprise Solutions** - Get custom infrastructure and limits When requesting increases, provide: - Current usage patterns - Expected growth timeline - Peak traffic requirements - Use case description [Contact our team](https://www.dwellir.com/contact) for custom rate limits. --- ## Supported Chains Dwellir provides access to 140+ blockchain networks through a unified API platform. All networks are accessible with a single API key. ## Complete Network List | Chain | Network | Archive | |-------|---------|---------| | **Acala** | Mainnet | Yes | | **Acurast** | Mainnet | Yes | | **Aleph Zero** | Mainnet, Testnet | Yes | | **Aleph Zero EVM** | Mainnet | Yes | | **Amplitude** | Mainnet | Yes | | **Aptos** | Mainnet, Testnet | Yes | | **Arbitrum** | One, Nova, Sepolia | Yes | | **Asset Hub** | Polkadot, Kusama, Westend | Yes | | **Astar** | Mainnet, Shiden, Shibuya | Yes | | **Avalanche** | C-Chain, Fuji | Yes | | **Aventus** | Mainnet | Yes | | **BalanceAI** | Mainnet | Yes | | **[Base](/base)** | Mainnet, Sepolia | No | | **Basilisk** | Mainnet | Yes | | **Berachain** | Testnet | Yes | | **Bifrost** | Polkadot, Kusama | Yes | | **Binance Smart Chain** | Mainnet, Testnet | No | | **Bittensor** | Mainnet | Yes | | **Blast** | Mainnet, Sepolia | Yes | | **Bridge Hub** | Polkadot, Kusama | Yes | | **Celestia** | Mainnet | Yes | | **Celo** | Mainnet, Alfajores | Yes | | **Centrifuge** | Mainnet | Yes | | **ChainFlip** | Mainnet | Yes | | **Chiliz** | Mainnet, Spicy Testnet | Yes | | **Collectives** | Polkadot | Yes | | **Coretime** | Polkadot, Kusama | Yes | | **Cronos** | Mainnet, Testnet | Yes | | **Crust Network** | Mainnet | Yes | | **Darwinia** | Mainnet, Crab | Yes | | **Energy Web X** | Mainnet | Yes | | **Enjin** | Matrixchain, Relaychain | Yes | | **Ethereum** | Mainnet, Sepolia, Holesky | Yes | | **Fantom** | Opera, Testnet | Yes | | **Filecoin** | Mainnet, Calibration | Yes | | **Flow EVM Gateway** | Mainnet, Testnet | Yes | | **Frequency** | Mainnet | Yes | | **Gnosis** | Mainnet, Chiado | Yes | | **Gravity Alpha** | Mainnet | Yes | | **Heima** | Mainnet | Yes | | **Humanode** | Mainnet | Yes | | **Hydration** | Mainnet | Yes | | **Hyper Liquid** | Mainnet | Yes | | **Hyperbridge Nexus** | Mainnet | Yes | | **Immutable** | Mainnet, Testnet | Yes | | **Integritee** | Mainnet | Yes | | **Interlay** | Mainnet, Kintsugi | Yes | | **InvArch** | Mainnet, Tinkernet | Yes | | **Joystream** | Mainnet | Yes | | **Karura** | Mainnet | Yes | | **Kilt** | Mainnet | Yes | | **Krest** | Mainnet | Yes | | **Kusama** | Relay Chain | Yes | | **Liberland** | Mainnet | Yes | | **Linea** | Mainnet, Sepolia | Yes | | **LISK** | Mainnet, Sepolia | Yes | | **Manta Atlantic** | Mainnet | Yes | | **Manta Pacific** | Mainnet, Sepolia | Yes | | **Mantle** | Mainnet, Sepolia | Yes | | **Moonbase Alpha** | Testnet | Yes | | **Moonbeam** | Mainnet | Yes | | **Moonriver** | Mainnet | Yes | | **Movement** | Testnet | No | | **Mythos** | Mainnet | Yes | | **Neuroweb** | Mainnet | Yes | | **Nodle** | Mainnet | Yes | | **opBNB** | Mainnet, Testnet | Yes | | **Optimism** | Mainnet, Sepolia | Yes | | **Parallel** | Mainnet | Yes | | **Paseo** | Testnet | Yes | | **Peaq** | Mainnet, Testnet | Yes | | **Pendulum** | Mainnet | Yes | | **People Kusama** | Mainnet | Yes | | **People Polkadot** | Mainnet | Yes | | **People Westend** | Testnet | Yes | | **Phala** | Mainnet, Khala | Yes | | **Polimec** | Mainnet | Yes | | **Polkadex** | Mainnet | Yes | | **Polkadot** | Relay Chain, Westend | Yes | | **Polygon** | Mainnet, Mumbai | No | | **Polygon zkEVM** | Mainnet, Cardona | Yes | | **Pulsechain** | Mainnet, Testnet | Yes | | **Robonomics** | Mainnet | Yes | | **Ronin** | Mainnet, Saigon | Yes | | **Scroll** | Mainnet, Sepolia | Yes | | **Shiden** | Mainnet | Yes | | **Sonic** | Testnet | Yes | | **Sora** | Mainnet | Yes | | **Starknet** | Mainnet, Sepolia | Yes | | **Subsocial** | Mainnet | Yes | | **Sui** | Mainnet, Testnet, Devnet | No | | **Tangle** | Mainnet, Testnet | No | | **TON** | Mainnet, Testnet | Yes | | **TRON** | Mainnet, Nile, Shasta | No | | **Turing Network** | Mainnet | Yes | | **Unichain** | Sepolia Testnet | Yes | | **Viction** | Mainnet, Testnet | Yes | | **Waves** | Mainnet, Testnet | Yes | | **XDC Network** | Mainnet, Apothem | Yes | | **XX Network** | Mainnet | Yes | | **Zeitgeist** | Mainnet | Yes | | **Zetachain** | Mainnet, Athens | Yes | | **zkSync Era** | Mainnet, Sepolia | No | | **Zora** | Mainnet, Sepolia | Yes | ## Archive Node Information ### What is an Archive Node? Archive nodes store the complete historical state of the blockchain from genesis block to the present. This includes: - All historical blocks - All historical transactions - All historical state changes - Complete contract storage history ### Archive Availability - **Yes**: Full archive node with complete historical data from genesis - **No**: Recent blocks only (typically last 128-256 blocks for state data) Networks marked with "No" for archive still provide: - Recent block and transaction data - Current state queries - Standard RPC methods - Real-time data subscriptions ### Networks Without Archive The following networks have limited historical data: - **Binance Smart Chain** - Recent blocks only - **Movement** - Recent blocks only - **Polygon** - Recent blocks only - **Polygon zkEVM** - Recent blocks only - **Sui** - Recent blocks only - **Tangle** - Recent blocks only - **TRON** - Recent blocks only - **zkSync Era** - Recent blocks only For these networks, if you need historical data beyond the recent blocks, please [contact our support team](https://www.dwellir.com/contact) for custom solutions. ## Connection Format ### HTTPS Endpoints ``` https://api-{network}-{variant}.dwellir.com/YOUR_API_KEY ``` ### WebSocket Endpoints ``` wss://api-{network}-{variant}.dwellir.com/YOUR_API_KEY ``` ### Examples **Ethereum Mainnet:** ``` https://api-ethereum-mainnet.dwellir.com/YOUR_API_KEY wss://api-ethereum-mainnet.dwellir.com/YOUR_API_KEY ``` **Polkadot:** ``` https://api-polkadot.dwellir.com/YOUR_API_KEY wss://api-polkadot.dwellir.com/YOUR_API_KEY ``` **Base Mainnet:** ``` https://api-base-mainnet.dwellir.com/YOUR_API_KEY wss://api-base-mainnet.dwellir.com/YOUR_API_KEY ``` ## Network Categories ### EVM Compatible All Ethereum Virtual Machine compatible networks support standard JSON-RPC methods including: - eth_* methods - web3_* methods - net_* methods - debug_* methods (with archive) - trace_* methods (with archive) ### Substrate Based Polkadot ecosystem networks support: - Substrate JSON-RPC - Custom runtime methods - chain_* methods - state_* methods - author_* methods ### Move Based Sui and Aptos networks support: - Move-specific methods - Object queries - Transaction simulation ### Other Networks with custom protocols: - TRON - TronWeb compatible - TON - TON-specific methods - Celestia - Data availability methods - Flow - Flow-specific methods ## Rate Limits All networks share your plan's rate limits: - **Free**: 20 req/s - **Developer**: 100 req/s - **Growth**: 500 req/s - **Scale**: 2,000 req/s - **Enterprise**: Custom ## Get Started 1. [Create an account](https://dashboard.dwellir.com/register) 2. Generate your API key 3. Choose your network from the table above 4. Connect using the standard endpoint format Need a specific network configuration or have questions? [Contact our support team](https://www.dwellir.com/contact). --- ## Tracing Transaction tracing allows you to inspect the internal operations of smart contract executions, debug failed transactions, and analyze gas consumption patterns. ## Overview Tracing APIs provide detailed information about: - EVM execution steps - Internal transactions - State changes - Gas consumption - Opcode execution - Storage modifications ## Available Tracing Methods ### debug_traceTransaction Trace a single transaction by hash. > **Example data:** The curl commands below use Ethereum block `0x166eaba` and transaction `0xad5b9400c749bd5d6ca2bb026bd23e83d6ff71d52a0fb379e85ae2020a0ed198` captured on 2025-10-06. Replace them with your own values when tracing different operations. ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": [ "0xad5b9400c749bd5d6ca2bb026bd23e83d6ff71d52a0fb379e85ae2020a0ed198", { "tracer": "callTracer", "tracerConfig": { "onlyTopCall": false } } ], "id": 1 }' ``` ### debug_traceBlockByNumber Trace all transactions in a block. ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["0x166eaba", {"tracer": "callTracer"}], "id": 1 }' ``` ### trace_transaction Get trace information for a transaction (Parity/OpenEthereum style). ```bash curl -X POST https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_transaction", "params": ["0xad5b9400c749bd5d6ca2bb026bd23e83d6ff71d52a0fb379e85ae2020a0ed198"], "id": 1 }' ``` ## Tracer Types ### 1. Call Tracer Captures all calls made during transaction execution. ```javascript { "tracer": "callTracer", "tracerConfig": { "onlyTopCall": false, "withLog": true } } ``` **Output includes:** - Call type (CALL, DELEGATECALL, STATICCALL, CREATE) - From/to addresses - Input/output data - Gas used - Error messages ### 2. Prestate Tracer Shows state before transaction execution. ```javascript { "tracer": "prestateTracer", "tracerConfig": { "diffMode": true } } ``` **Output includes:** - Account balances - Contract code - Storage values - Nonce values ### 3. 4byte Tracer Identifies function signatures in the transaction. ```javascript { "tracer": "4byteTracer" } ``` **Output:** - Map of 4-byte signatures to call counts ### 4. Custom JavaScript Tracer Create custom tracers for specific analysis. ```javascript { "tracer": "{data: [], step: function(log) { this.data.push(log.op.toString()); }, result: function() { return this.data; }}" } ``` ## Practical Examples ### Debugging Failed Transactions ```javascript async function debugFailedTransaction(txHash) { const trace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'callTracer' } ]); // Find the exact failure point function findError(call) { if (call.error) { return { address: call.to, error: call.error, input: call.input }; } if (call.calls) { for (const subcall of call.calls) { const error = findError(subcall); if (error) return error; } } return null; } return findError(trace); } ``` ### Analyzing Gas Usage ```javascript async function analyzeGasUsage(txHash) { const trace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'callTracer' } ]); function calculateGas(call, depth = 0) { const gasInfo = { address: call.to, gasUsed: parseInt(call.gasUsed, 16), depth: depth, calls: [] }; if (call.calls) { for (const subcall of call.calls) { gasInfo.calls.push(calculateGas(subcall, depth + 1)); } } return gasInfo; } return calculateGas(trace); } ``` ### Internal Transactions ```javascript async function getInternalTransactions(txHash) { const trace = await provider.send('trace_transaction', [txHash]); return trace .filter(t => t.type === 'call' && t.action.value !== '0x0') .map(t => ({ from: t.action.from, to: t.action.to, value: t.action.value, success: t.result !== null })); } ``` ## Performance Considerations ### Archive Node Requirements Tracing requires archive nodes for historical data: - Full state at every block - Complete transaction history - Higher infrastructure costs ### Request Optimization 1. **Cache Trace Results** ```javascript const traceCache = new Map(); async function getCachedTrace(txHash) { if (traceCache.has(txHash)) { return traceCache.get(txHash); } const trace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'callTracer' } ]); traceCache.set(txHash, trace); return trace; } ``` 2. **Batch Trace Requests** ```javascript async function batchTraceTransactions(txHashes) { const requests = txHashes.map((hash, index) => ({ jsonrpc: '2.0', method: 'debug_traceTransaction', params: [hash, { tracer: 'callTracer' }], id: index })); return await provider.send(requests); } ``` 3. **Use Appropriate Tracers** - `callTracer` for debugging - `prestateTracer` for state analysis - `4byteTracer` for function identification - Custom tracers for specific needs ## Error Handling Common tracing errors and solutions: ### Missing State ```json { "error": { "code": -32000, "message": "missing trie node" } } ``` **Solution**: Use an archive node or request more recent data. ### Timeout ```json { "error": { "code": -32000, "message": "execution timeout" } } ``` **Solution**: Simplify tracer or reduce block range. ### Invalid Tracer ```json { "error": { "code": -32602, "message": "invalid tracer" } } ``` **Solution**: Check tracer syntax and supported tracers for the network. ## Security Considerations When using tracing: 1. **Validate Input**: Sanitize transaction hashes and parameters 2. **Rate Limit**: Implement client-side rate limiting 3. **Access Control**: Restrict tracing access in production 4. **Data Privacy**: Traced data may contain sensitive information ## Tools and Libraries ### Web3.js ```javascript const trace = await web3.currentProvider.send({ method: 'debug_traceTransaction', params: [txHash, { tracer: 'callTracer' }] }); ``` ### Ethers.js ```javascript const trace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'callTracer' } ]); ``` ### Cast (Foundry) ```bash cast run --trace 0xhash --rpc-url https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY ``` Need help with tracing? [Contact our support team](https://www.dwellir.com/contact). --- ## Getting Started This guide helps you create an API key and make your first request in minutes. ## 1. Sign Up and Get Your API Key 1. Go to [dashboard.dwellir.com](https://dashboard.dwellir.com) and sign up 2. Your first API key is created automatically -- find it in the API Keys section 3. Copy your API key (format: `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`) Need additional keys? Create them from the dashboard or the [Dwellir CLI](/cli): ```bash curl -fsSL https://raw.githubusercontent.com/dwellir-public/cli/main/scripts/install.sh | sh dwellir auth login dwellir keys create --name my-key ``` ## 2. Choose a Network Select from 140+ supported networks. Popular choices include: - **Ethereum**: `ethereum-mainnet` - **Base**: `base-mainnet` - **Arbitrum**: `arbitrum-one` - **Polygon**: `polygon-mainnet` - **Polkadot**: `polkadot` See the full list in [Supported Chains](/getting-started/supported-chains), or use the CLI to browse all endpoints: ```bash dwellir endpoints search ethereum dwellir endpoints list --ecosystem evm --network mainnet ``` ## 3. Make Your First Request The API key goes directly in the URL. No Authorization header needed. ### Using cURL ```bash curl -X POST \ -H "Content-Type: application/json" \ https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -d '{ "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 }' ``` ### Endpoint URL Format ``` https://api-{network}.n.dwellir.com/{YOUR_API_KEY} wss://api-{network}.n.dwellir.com/{YOUR_API_KEY} ``` For example, to query Ethereum mainnet: ```bash curl -X POST \ -H "Content-Type: application/json" \ https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY \ -d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' ``` ## 4. Use an SDK ### Web3.js ```javascript const Web3 = require('web3'); // API key is in the URL, no auth header needed const web3 = new Web3('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); // Make requests const blockNumber = await web3.eth.getBlockNumber(); console.log('Latest block:', blockNumber); // Get balance const balance = await web3.eth.getBalance('0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb'); console.log('Balance:', web3.utils.fromWei(balance, 'ether'), 'ETH'); ``` ### Ethers.js ```javascript // API key is in the URL, no auth header needed const provider = new JsonRpcProvider( 'https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY' ); // Make requests const blockNumber = await provider.getBlockNumber(); console.log('Latest block:', blockNumber); // Get balance const balance = await provider.getBalance('0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb'); console.log('Balance:', ethers.formatEther(balance), 'ETH'); ``` ### WebSocket Connection ```javascript const WebSocket = require('ws'); const ws = new WebSocket('wss://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'); ws.on('open', () => { // Subscribe to new blocks ws.send(JSON.stringify({ jsonrpc: '2.0', method: 'eth_subscribe', params: ['newHeads'], id: 1 })); }); ws.on('message', (data) => { const response = JSON.parse(data); console.log('New block:', response); }); ``` ## 5. Configure API Quotas Protect yourself from unexpected usage by setting quotas on your API keys: 1. Go to [dashboard.dwellir.com/api-keys](https://dashboard.dwellir.com/api-keys) 2. Click the edit icon next to your API key 3. In the Edit API key dialog: - **Name**: Give your key a descriptive name - **Daily quota**: Toggle and set daily request limit - **Monthly quota**: Toggle and set monthly request limit 4. Click "Update API Key" to save changes Or set quotas from the CLI: ```bash dwellir keys create --name production --daily-quota 100000 --monthly-quota 3000000 ``` When a quota is reached, the API returns a 429 error until the quota resets. ## 6. Monitor Your Usage Track your API usage in real-time: 1. Go to [dashboard.dwellir.com/usage](https://dashboard.dwellir.com/usage) 2. View metrics: total requests, requests by method/network, response times, and error rates Or use the CLI for programmatic access: ```bash dwellir usage summary dwellir usage history --interval day dwellir logs errors --status-code 429 ``` ## 7. Best Practices ### Error Handling ```javascript async function makeRequest() { try { const blockNumber = await web3.eth.getBlockNumber(); return blockNumber; } catch (error) { if (error.code === 429) { console.log('Rate limit exceeded, retry after delay'); // Implement exponential backoff } else { console.error('Request failed:', error); } } } ``` ### Connection Pooling ```javascript // Reuse provider instances const providers = { ethereum: new Web3('https://api-ethereum-mainnet.n.dwellir.com/YOUR_API_KEY'), polygon: new Web3('https://api-polygon-mainnet.n.dwellir.com/YOUR_API_KEY'), arbitrum: new Web3('https://api-arbitrum-one.n.dwellir.com/YOUR_API_KEY') }; // Use the same provider for multiple requests async function getMultiChainData() { const ethBlock = await providers.ethereum.eth.getBlockNumber(); const polyBlock = await providers.polygon.eth.getBlockNumber(); const arbBlock = await providers.arbitrum.eth.getBlockNumber(); return { ethBlock, polyBlock, arbBlock }; } ``` ### Batch Requests ```javascript // Batch multiple calls into one request const batch = new web3.BatchRequest(); batch.add(web3.eth.getBlockNumber.request((err, res) => { console.log('Block number:', res); })); batch.add(web3.eth.getGasPrice.request((err, res) => { console.log('Gas price:', res); })); batch.execute(); ``` ## Migrating from Another Provider Switching from Alchemy, Infura, QuickNode, or another RPC provider? Use the migration prompt below with your AI coding agent to automate the process. It scans your codebase for existing RPC endpoints, matches them against Dwellir's catalog, and replaces the URLs.
View and copy the migration prompt ````text Migrate this project's blockchain RPC endpoints to Dwellir. Follow the phases below in order. Use subagents and background processes to parallelize work wherever your tooling supports it. ## Phase 1 — Environment & Endpoint Discovery 1. Check whether the Dwellir CLI is installed by running `dwellir --version`. If the command is not found, suggest the user install it: curl -fsSL https://raw.githubusercontent.com/dwellir-public/cli/main/scripts/install.sh | sh 2. Obtain the full list of Dwellir-supported chains, networks, and node types (full vs archive). Try one of these approaches in order until one succeeds: a. **CLI** (preferred): Run `dwellir endpoints list` to get the complete endpoint catalog. b. **Documentation**: If the CLI is unavailable or the user declines to install it, fetch https://www.dwellir.com/docs.md or https://www.dwellir.com/networks.md for the supported endpoint list. c. **Dashboard export**: As a last resort, ask the user to go to dashboard.dwellir.com/endpoints and press the Export button (top-left) to export all endpoints as CSV, Markdown, or JSON, then share the file with you. 3. Check whether the project uses separate configurations per environment (production, staging, development, etc.). If it does, ask the user to provide a Dwellir API key for each environment. If there is only one environment, ask for a single key. ## Phase 2 — Codebase Discovery Scan the entire codebase in parallel where possible: 1. Find every RPC endpoint URL (look for domains like infura.io, alchemy.com, quicknode.com, chainstack.com, ankr.com, blast.io, drpc.org, and any other known RPC providers, as well as raw IP/port patterns and chain-specific gateway URLs). 2. Identify each endpoint's chain, network, and authentication method (API key in URL path, header, query param, or none). 3. Determine whether the code requires an archive node or a full node for each endpoint (look for calls to historical state such as eth_getBalance at old block heights, debug_*/trace_* namespaces, or large block-range log filters). 4. Check if the codebase interacts with Hyperliquid. If it does, suggest that the user install Dwellir's Hyperliquid Skills: npx skills add https://github.com/dwellir-public/hyperliquid-skills ## Phase 3 — Compatibility Matching For each discovered endpoint: 1. Compare the chain + network against the Dwellir endpoints list from Phase 1. Note that some providers (especially for EVM chains) use chain ID-based naming in their URLs rather than chain + network names — resolve any ambiguity by calling the endpoint's RPC method for chain ID (e.g., eth_chainId) and comparing the result against the chain ID returned by the corresponding Dwellir endpoint to confirm they serve the same network. 2. If the code requires an archive node and Dwellir only offers a full node for that chain, mark the endpoint as unsupported and do NOT migrate it. 3. For EVM chains, check whether the codebase depends on client-specific response shapes (e.g., Geth/Erigon trace formats vs Reth, differences in debug_traceTransaction output, or Parity-style trace_* responses). Use web search if needed to understand current client-level differences. Flag any potential incompatibilities. ## Phase 4 — Migration 1. Create a new branch (e.g., chore/migrate-to-dwellir) — NEVER commit directly to main. 2. For each supported endpoint, replace the provider URL with the equivalent Dwellir endpoint URL and update the authentication to use the correct Dwellir API key for each environment. Preserve the existing configuration pattern (env var, config file, etc.). 3. If any endpoints, chains, or networks in the codebase are NOT supported by Dwellir, do not touch them. ## Phase 5 — Summary Present a clear summary with: - Migrated: list of endpoints successfully switched to Dwellir (chain, network, full/archive). - Flagged: any EVM client compatibility concerns the user should verify. - Not supported: list of endpoints/chains/networks Dwellir does not currently support, along with whether each requires a full or archive node and the estimated monthly request volume if determinable from the code. Ask the user to reach out to support@dwellir.com or the team on https://t.me/dwellir with this list so Dwellir can evaluate adding support. If there are any questions about supported RPC methods or Dwellir services, consult https://www.dwellir.com/docs/llms.txt and https://www.dwellir.com/docs.md for authoritative reference. Commit the changes and ask the user whether you should push the branch to origin and open a pull request. ````
See [Agent Tooling](/agents) for more tools and documentation endpoints built for AI coding agents. ## Quick Reference ### Endpoint Format ``` https://api-{network}.n.dwellir.com/{YOUR_API_KEY} wss://api-{network}.n.dwellir.com/{YOUR_API_KEY} ``` ### Common Networks - Ethereum: `api-ethereum-mainnet` - Base: `api-base-mainnet` - Arbitrum: `api-arbitrum-one` - Optimism: `api-optimism-mainnet` - Polygon: `api-polygon-mainnet` - BSC: `api-bsc-mainnet` - Avalanche: `api-avalanche-c-chain` ### Useful Links - [Dashboard](https://dashboard.dwellir.com) - [API Keys](https://dashboard.dwellir.com/api-keys) - [Usage Monitor](https://dashboard.dwellir.com/usage) - [Dwellir CLI](/cli) - [Supported Chains](/getting-started/supported-chains) - [Rate Limits](/getting-started/rate-limits) - [Pricing](/getting-started/pricing) ## Need Help? - Check the [documentation](/getting-started/supported-chains) for network-specific details - Contact [support@dwellir.com](mailto:support@dwellir.com) for technical assistance Ready to scale? [Upgrade your plan](/getting-started/pricing) for higher rate limits and additional features. --- ## debug_traceBlock - Gnosis RPC Method # debug_traceBlock Traces all transactions in a block on Gnosis by block RLP. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Analyze transaction execution step-by-step - **Smart contract analysis** - Debug contract interactions - **Security auditing** - Trace internal calls for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockRlp` | `DATA` | Yes | RLP-encoded block data | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); // Use debug_traceBlockByNumber instead (more practical) const traces = await provider.send('debug_traceBlockByNumber', ['latest', {}]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by block number - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by block hash --- ## debug_traceBlockByHash - Gnosis RPC Method # debug_traceBlockByHash Traces all transactions in a block on Gnosis by block hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0xb7d40246868f4037c9d681df4f45634e7b378187531f3ca53b56f97350b622a1", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0xb7d40246868f4037c9d681df4f45634e7b378187531f3ca53b56f97350b622a1", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0xb7d40246868f4037c9d681df4f45634e7b378187531f3ca53b56f97350b622a1'; const traces = await provider.send('debug_traceBlockByHash', [blockHash, { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by number - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceBlockByNumber - Gnosis RPC Method # debug_traceBlockByNumber Traces all transactions in a block on Gnosis by block number. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('debug_traceBlockByNumber', ['latest', { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by hash - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceCall - Gnosis RPC Method # debug_traceCall Traces a call without creating a transaction on Gnosis. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction simulation** - Debug before sending - **Gas analysis** - Analyze gas usage per opcode - **Contract debugging** - Step through execution for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `call` | `Object` | Yes | Call object (same as eth_call) | | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ { "to": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "data": "0x70a08231000000000000000000000000e91D153E0b41518A2Ce8Dd3D7944Fa863463a97d" }, "latest", {} ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ {"to": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "data": "0x70a08231000000000000000000000000e91D153E0b41518A2Ce8Dd3D7944Fa863463a97d"}, "latest", {"tracer": "callTracer"} ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const trace = await provider.send('debug_traceCall', [ { to: '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d', data: '0x70a08231000000000000000000000000e91D153E0b41518A2Ce8Dd3D7944Fa863463a97d' }, 'latest', { tracer: 'callTracer' } ]); console.log('Trace:', trace); ``` ## Related Methods - [`eth_call`](./eth_call) - Execute call without trace - [`debug_traceTransaction`](./debug_traceTransaction) - Trace actual transaction --- ## debug_traceTransaction - Gnosis RPC Method # debug_traceTransaction Traces a transaction execution on Gnosis by transaction hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Understand exactly what happened - **Failure analysis** - Find where and why a transaction reverted - **Gas optimization** - Analyze gas usage for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Tracer Options - `{}` - Default opcode tracer (verbose) - `{ tracer: "callTracer" }` - Call tree tracer - `{ tracer: "prestateTracer" }` - Pre-state tracer ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814'; // Call tracer - shows internal calls const callTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'callTracer' } ]); console.log('Type:', callTrace.type); console.log('From:', callTrace.from); console.log('To:', callTrace.to); console.log('Gas used:', parseInt(callTrace.gasUsed, 16)); // Prestate tracer - shows state before execution const prestateTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'prestateTracer' } ]); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814' # Call tracer trace = w3.provider.make_request('debug_traceTransaction', [ tx_hash, {'tracer': 'callTracer'} ]) print(f'Trace type: {trace["result"]["type"]}') print(f'Gas used: {int(trace["result"]["gasUsed"], 16)}') ``` ## Related Methods - [`debug_traceCall`](./debug_traceCall) - Trace without executing - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace entire block --- ## eth_accounts - Gnosis RPC Method # eth_accounts Returns a list of addresses owned by the client on Gnosis. > **Why Gnosis?** Build on the prediction market pioneer with $260M+ TVL and xDAI stablecoin-based gas fees with stablecoin gas fees for predictable costs, Shutter MEV protection, 150K+ Safe wallets, and Circles decentralized UBI protocol. ## Important Note On public RPC endpoints like Dwellir, `eth_accounts` returns an empty array because the node does not hold any private keys. This method is primarily useful for: - Local development nodes (Ganache, Hardhat, Anvil) - Private nodes with managed accounts - Wallet provider connections (MetaMask injects accounts) ## When to Use This Method `eth_accounts` is relevant for prediction market builders, DAO tooling developers, and teams building MEV-protected applications in specific scenarios: - **Development Testing** — Retrieve test accounts from local nodes - **Wallet Detection** — Check if a wallet provider has connected accounts - **Client Verification** — Confirm node account access capabilities ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `Array` | List of 20-byte account addresses owned by the client | **Return format**: Array of `0x` prefixed hexadecimal addresses (typically empty for public nodes) ## Request ```json { "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 } ``` ## Response ### Successful Response (Public Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [] } ``` ### Successful Response (Local Development Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [ "0x407d73d8a49eeb85d32cf465507dd71d507100c1", "0x85d32cf465507dd71d507100c1407d73d8a49eeb" ] } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_accounts', params: [], id: 1 }) }); const { result } = await response.json(); console.log('Accounts:', result); // Using ethers.js const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const accounts = await provider.listAccounts(); console.log('Accounts:', accounts); ``` ```python def get_accounts(): response = requests.post( 'https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_accounts', 'params': [], 'id': 1 } ) return response.json()['result'] accounts = get_accounts() print(f'Accounts: {accounts}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) print(f'Accounts: {w3.eth.accounts}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/rpc" ) func main() { client, err := rpc.Dial("https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } var accounts []string err = client.CallContext(context.Background(), &accounts, "eth_accounts") if err != nil { log.Fatal(err) } fmt.Printf("Accounts: %v\n", accounts) } ``` ## Common Use Cases ### 1. Development Environment Detection Check if running against a development node with test accounts: ```javascript async function isDevEnvironment(provider) { const accounts = await provider.listAccounts(); return accounts.length > 0; } const isDev = await isDevEnvironment(provider); if (isDev) { console.log('Development environment detected'); } ``` ### 2. Wallet Connection Check Verify wallet provider has connected accounts: ```javascript async function checkWalletConnection() { if (typeof window.ethereum === 'undefined') { return { connected: false, reason: 'No wallet detected' }; } const accounts = await window.ethereum.request({ method: 'eth_accounts' }); return { connected: accounts.length > 0, accounts: accounts }; } ``` ### 3. Fallback Account Selection Use first available account or request connection: ```javascript async function getActiveAccount() { // Check existing connections let accounts = await window.ethereum.request({ method: 'eth_accounts' }); // Request connection if no accounts if (accounts.length === 0) { accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); } return accounts[0] || null; } ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32601 | Method not found | Node may not support this method | | -32603 | Internal error | Retry with exponential backoff | ```javascript async function safeGetAccounts(provider) { try { const accounts = await provider.listAccounts(); return { success: true, accounts }; } catch (error) { if (error.code === -32601) { console.warn('eth_accounts not supported on this node'); return { success: false, accounts: [], reason: 'unsupported' }; } throw error; } } ``` ## Related Methods - [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102) — Request wallet connection (browser wallets) - [`eth_getBalance`](./eth_getBalance) — Get account balance - [`eth_getTransactionCount`](./eth_getTransactionCount) — Get account nonce --- ## eth_blockNumber - Gnosis RPC Method # eth_blockNumber Returns the number of the most recent block on Gnosis. > **Why Gnosis?** Build on the prediction market pioneer with $260M+ TVL and xDAI stablecoin-based gas fees with stablecoin gas fees for predictable costs, Shutter MEV protection, 150K+ Safe wallets, and Circles decentralized UBI protocol. ## When to Use This Method `eth_blockNumber` is fundamental for prediction market builders, DAO tooling developers, and teams building MEV-protected applications: - **Syncing Applications** — Keep your dApp in sync with the latest Gnosis blockchain state - **Transaction Monitoring** — Verify confirmations by comparing block numbers - **Event Filtering** — Set the correct block range for querying logs on prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration - **Health Checks** — Monitor node connectivity and sync status ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `QUANTITY` | Hexadecimal string representing the current block number | **Return format**: `0x` prefixed hexadecimal (e.g., `0x5BAD55` = 6,008,149 in decimal) ## Request ```json { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } ``` ## Response ### Successful Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5BAD55" } ``` ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error" } } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }) }); const { result } = await response.json(); const blockNumber = parseInt(result, 16); console.log('Gnosis block:', blockNumber); // Using ethers.js const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const blockNumber = await provider.getBlockNumber(); console.log('Gnosis block:', blockNumber); ``` ```python def get_block_number(): response = requests.post( 'https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_blockNumber', 'params': [], 'id': 1 } ) result = response.json()['result'] return int(result, 16) block_number = get_block_number() print(f'Gnosis block: {block_number}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) print(f'Gnosis block: {w3.eth.block_number}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockNumber, err := client.BlockNumber(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Gnosis block: %d\n", blockNumber) } ``` ## Common Use Cases ### 1. Block Confirmation Counter Monitor transaction confirmations on Gnosis: ```javascript async function getConfirmations(provider, txHash) { const tx = await provider.getTransaction(txHash); if (!tx || !tx.blockNumber) return 0; const currentBlock = await provider.getBlockNumber(); return currentBlock - tx.blockNumber + 1; } // Wait for specific confirmations async function waitForConfirmations(provider, txHash, confirmations = 6) { let currentConfirmations = 0; while (currentConfirmations < confirmations) { currentConfirmations = await getConfirmations(provider, txHash); console.log(`Confirmations: ${currentConfirmations}/${confirmations}`); await new Promise(r => setTimeout(r, 2000)); } return true; } ``` ### 2. Event Log Filtering Query events from recent blocks on Gnosis: ```javascript async function getRecentEvents(provider, contract, eventName, blockRange = 100) { const currentBlock = await provider.getBlockNumber(); const fromBlock = currentBlock - blockRange; const filter = contract.filters[eventName](); const events = await contract.queryFilter(filter, fromBlock, currentBlock); return events; } ``` ### 3. Node Health Monitoring Check if your Gnosis node is synced: ```javascript async function checkNodeHealth(provider) { try { const blockNumber = await provider.getBlockNumber(); const block = await provider.getBlock(blockNumber); const now = Date.now() / 1000; const blockAge = now - block.timestamp; if (blockAge > 60) { console.warn(`Node may be behind. Last block was ${blockAge}s ago`); return false; } console.log(`Node healthy. Latest block: ${blockNumber}`); return true; } catch (error) { console.error('Node unreachable:', error); return false; } } ``` ## Performance Optimization ### Caching Strategy Cache block numbers to reduce API calls: ```javascript class BlockNumberCache { constructor(ttl = 2000) { this.cache = null; this.timestamp = 0; this.ttl = ttl; } async get(provider) { const now = Date.now(); if (this.cache && (now - this.timestamp) < this.ttl) { return this.cache; } this.cache = await provider.getBlockNumber(); this.timestamp = now; return this.cache; } invalidate() { this.cache = null; this.timestamp = 0; } } const blockCache = new BlockNumberCache(); ``` ### Batch Requests Combine with other calls for efficiency: ```javascript const batch = [ { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }, { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 }, { jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 } ]; const response = await fetch('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await response.json(); ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32603 | Internal error | Retry with exponential backoff | | -32005 | Rate limit exceeded | Implement rate limiting client-side | | -32000 | Execution reverted | Check node sync status | ```javascript async function safeGetBlockNumber(provider, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await provider.getBlockNumber(); } catch (error) { if (error.code === -32005) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } else if (i === maxRetries - 1) { throw error; } } } } ``` ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) — Get full block details by number - [`eth_getBlockByHash`](./eth_getBlockByHash) — Get block details by hash - [`eth_syncing`](./eth_syncing) — Check if node is still syncing --- ## eth_call - Gnosis RPC Method # eth_call Executes a new message call immediately without creating a transaction on Gnosis. Used for reading smart contract state. > **Why Gnosis?** Build on the prediction market pioneer with $260M+ TVL and xDAI stablecoin-based gas fees with stablecoin gas fees for predictable costs, Shutter MEV protection, 150K+ Safe wallets, and Circles decentralized UBI protocol. ## Use Cases The `eth_call` method is essential for: - **Reading contract state** - Query view/pure functions - **Simulating transactions** - Test execution without gas costs - **DeFi integrations** - Check prices, balances, allowances for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration - **Complex queries** - Execute multi-step contract logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | 20-byte address executing the call | | `to` | `DATA` | Yes | 20-byte contract address | | `gas` | `QUANTITY` | No | Gas limit for the call | | `gasPrice` | `QUANTITY` | No | Gas price in wei | | `value` | `QUANTITY` | No | Value to send in wei | | `data` | `DATA` | Yes | Encoded function call data | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_call", "params": [ { "to": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "data": "0x70a08231000000000000000000000000e91D153E0b41518A2Ce8Dd3D7944Fa863463a97d" }, "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | The return value of the executed contract function | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000" } ``` ## Code Examples ```bash # Call ERC20 balanceOf function curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{ "to": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "data": "0x70a08231000000000000000000000000e91D153E0b41518A2Ce8Dd3D7944Fa863463a97d" }, "latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); // ERC20 ABI for common functions const ERC20_ABI = [ "function balanceOf(address owner) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function totalSupply() view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)" ]; // Read ERC20 token balance async function getTokenBalance(tokenAddress, walletAddress) { const contract = new Contract(tokenAddress, ERC20_ABI, provider); const balance = await contract.balanceOf(walletAddress); const decimals = await contract.decimals(); const symbol = await contract.symbol(); return { raw: balance.toString(), formatted: (Number(balance) / Math.pow(10, decimals)).toFixed(4), symbol: symbol }; } // Direct eth_call async function directCall(to, data) { const result = await provider.call({ to, data }); return result; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) def get_erc20_balance(token_address, wallet_address): # balanceOf(address) selector function_signature = "balanceOf(address)" function_selector = w3.keccak(text=function_signature)[:4].hex() # Encode address parameter encoded_address = wallet_address[2:].lower().zfill(64) data = function_selector + encoded_address # Make the call result = w3.eth.call({ 'to': token_address, 'data': data }) return int(result.hex(), 16) balance = get_erc20_balance( '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d', '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d' ) print(f'Balance: {balance}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d") data := common.FromHex("0x70a08231000000000000000000000000e91D153E0b41518A2Ce8Dd3D7944Fa863463a97d") msg := ethereum.CallMsg{ To: &contractAddress, Data: data, } result, err := client.CallContract(context.Background(), msg, nil) if err != nil { log.Fatal(err) } fmt.Printf("Result: 0x%x\n", result) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Contract function reverted | | -32602 | Invalid parameters | Invalid data encoding | | -32015 | VM execution error | Contract logic error | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas for transaction - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send actual transaction --- ## eth_chainId - Gnosis RPC Method # eth_chainId Returns the chain ID used for transaction signing on Gnosis. > **Why Gnosis?** Build on the prediction market pioneer with $260M+ TVL and xDAI stablecoin-based gas fees with stablecoin gas fees for predictable costs, Shutter MEV protection, 150K+ Safe wallets, and Circles decentralized UBI protocol. ## Use Cases The `eth_chainId` method is essential for: - **Transaction signing** - Ensure transactions are signed for the correct network - **Network verification** - Confirm connection to the expected chain - **Multi-chain apps** - Handle different networks programmatically - **Wallet integration** - Validate network before transactions ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Chain ID in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1" } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const network = await provider.getNetwork(); console.log('Chain ID:', network.chainId); // Verify network before transaction async function verifyNetwork(expectedChainId) { const network = await provider.getNetwork(); if (network.chainId !== BigInt(expectedChainId)) { throw new Error(`Wrong network. Expected ${expectedChainId}, got ${network.chainId}`); } return true; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) chain_id = w3.eth.chain_id print(f'Chain ID: {chain_id}') # Verify network def verify_network(expected_chain_id): chain_id = w3.eth.chain_id if chain_id != expected_chain_id: raise ValueError(f'Wrong network. Expected {expected_chain_id}, got {chain_id}') return True ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } chainID, err := client.ChainID(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Chain ID: %d\n", chainID) } ``` ## Related Methods - [`net_version`](./net_version) - Get network version - [`eth_syncing`](./eth_syncing) - Check sync status --- ## eth_coinbase - Get coinbase address(Gnosis) # eth_coinbase Get coinbase address on the Gnosis Chain network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_coinbase](https://ethereum.org/developers/docs/apis/json-rpc/#eth_coinbase) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_coinbase", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_coinbase', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Gnosis documentation](https://docs.gnosischain.com/).* --- ## eth_estimateGas - Gnosis RPC Method # eth_estimateGas Estimates the gas necessary to execute a transaction on Gnosis. > **Why Gnosis?** Build on the prediction market pioneer with $260M+ TVL and xDAI stablecoin-based gas fees with stablecoin gas fees for predictable costs, Shutter MEV protection, 150K+ Safe wallets, and Circles decentralized UBI protocol. ## Use Cases The `eth_estimateGas` method is essential for: - **Transaction preparation** - Set appropriate gas limits - **Cost estimation** - Calculate transaction costs before sending - **Error detection** - Identify reverts before spending gas - **DeFi operations** - Estimate costs for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | Sender address | | `to` | `DATA` | No | Recipient address | | `gas` | `QUANTITY` | No | Gas limit | | `gasPrice` | `QUANTITY` | No | Gas price | | `value` | `QUANTITY` | No | Value in wei | | `data` | `DATA` | No | Transaction data | ## Request ```json { "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "to": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "value": "0x1" }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Estimated gas amount in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5208" } ``` **Note**: `0x5208` = 21000 gas (standard ETH transfer) ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "to": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "value": "0x1" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); // Estimate simple transfer async function estimateTransfer(to, value) { const gasEstimate = await provider.estimateGas({ to: to, value: parseEther(value) }); console.log('Estimated gas:', gasEstimate.toString()); return gasEstimate; } // Estimate contract call async function estimateContractCall(contract, method, args) { const gasEstimate = await contract[method].estimateGas(...args); console.log('Estimated gas:', gasEstimate.toString()); // Add 20% buffer for safety return gasEstimate * 120n / 100n; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) def estimate_transfer(to, value_in_ether): gas_estimate = w3.eth.estimate_gas({ 'to': to, 'value': w3.to_wei(value_in_ether, 'ether') }) print(f'Estimated gas: {gas_estimate}') return gas_estimate def estimate_contract_call(contract, method, args): func = getattr(contract.functions, method) gas_estimate = func(*args).estimate_gas() # Add 20% buffer return int(gas_estimate * 1.2) # Estimate simple transfer gas = estimate_transfer('0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d', 0.1) ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } toAddress := common.HexToAddress("0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d") msg := ethereum.CallMsg{ To: &toAddress, Value: big.NewInt(1000000000000000000), } gasLimit, err := client.EstimateGas(context.Background(), msg) if err != nil { log.Fatal(err) } fmt.Printf("Estimated gas: %d\n", gasLimit) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Transaction would fail | | -32602 | Invalid params | Invalid transaction parameters | **Tip**: If estimation fails, the transaction would likely revert if sent. ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_feeHistory - Gnosis RPC Method # eth_feeHistory Returns historical gas information on Gnosis for fee estimation. ## Use Cases - **Fee prediction** - Estimate future gas prices based on history - **Gas analytics** - Analyze fee trends over time - **Optimal timing** - Find best times for transactions on prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockCount` | `QUANTITY` | Yes | Number of blocks in the range | | `newestBlock` | `QUANTITY\|TAG` | Yes | Highest block of the range | | `rewardPercentiles` | `Array` | Yes | Percentiles to sample for priority fees | ## Request ```json { "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const feeHistory = await provider.send('eth_feeHistory', ['0xa', 'latest', [25, 50, 75]]); console.log('Base fees:', feeHistory.baseFeePerGas.map(f => formatUnits(f, 'gwei'))); console.log('Reward (25th percentile):', feeHistory.reward.map(r => formatUnits(r[0], 'gwei'))); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) fee_history = w3.eth.fee_history(10, 'latest', [25, 50, 75]) print(f'Base fees: {[w3.from_wei(f, "gwei") for f in fee_history["baseFeePerGas"]]}') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee --- ## eth_gasPrice - Gnosis RPC Method # eth_gasPrice Returns the current gas price on Gnosis in wei. > **Why Gnosis?** Build on the prediction market pioneer with $260M+ TVL and xDAI stablecoin-based gas fees with stablecoin gas fees for predictable costs, Shutter MEV protection, 150K+ Safe wallets, and Circles decentralized UBI protocol. ## Use Cases The `eth_gasPrice` method is essential for: - **Transaction pricing** - Set appropriate gas prices - **Cost estimation** - Calculate transaction costs before sending - **Gas monitoring** - Track network congestion - **DeFi operations** - Optimize costs for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Current gas price in wei (hexadecimal) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x3b9aca00" } ``` **Note**: `0x3b9aca00` = 1 Gwei (1,000,000,000 wei) ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); const gasPrice = feeData.gasPrice; console.log('Gas Price:', formatUnits(gasPrice, 'gwei'), 'Gwei'); // Calculate transaction cost async function estimateTransactionCost(gasLimit) { const feeData = await provider.getFeeData(); const cost = feeData.gasPrice * BigInt(gasLimit); return formatUnits(cost, 'ether'); } const cost = await estimateTransactionCost(21000); console.log('Transfer cost:', cost, 'ETH'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) gas_price = w3.eth.gas_price print(f'Gas Price: {w3.from_wei(gas_price, "gwei")} Gwei') # Calculate transaction cost def estimate_transaction_cost(gas_limit): gas_price = w3.eth.gas_price cost = gas_price * gas_limit return w3.from_wei(cost, 'ether') cost = estimate_transaction_cost(21000) print(f'Transfer cost: {cost} ETH') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } gasPrice, err := client.SuggestGasPrice(context.Background()) if err != nil { log.Fatal(err) } // Convert to Gwei gwei := new(big.Float).Quo( new(big.Float).SetInt(gasPrice), big.NewFloat(1e9), ) fmt.Printf("Gas Price: %f Gwei\n", gwei) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32603 | Internal error | Node error | ## Related Methods - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee (EIP-1559) - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas needed --- ## eth_getBalance - Gnosis RPC Method # eth_getBalance Returns the balance of a given address on Gnosis. > **Why Gnosis?** Build on the prediction market pioneer with $260M+ TVL and xDAI stablecoin-based gas fees with stablecoin gas fees for predictable costs, Shutter MEV protection, 150K+ Safe wallets, and Circles decentralized UBI protocol. ## Use Cases The `eth_getBalance` method is essential for: - **Wallet applications** - Display user balances - **Transaction validation** - Check if account has sufficient funds - **DeFi applications** - Monitor collateral and liquidity for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration - **Account monitoring** - Track balance changes over time ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address to check balance for | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Integer of the current balance in wei (hexadecimal) | **Note**: 1 native token = 10^18 wei. Convert using `balance / 10^18`. ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1a055690d9db80000" } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d'; const balanceWei = await provider.getBalance(address); const balance = formatEther(balanceWei); console.log(`Balance: ${balance}`); // Get balance at specific block const historicalBalance = await provider.getBalance(address, 1000000); console.log(`Historical balance: ${formatEther(historicalBalance)}`); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d' balance_wei = w3.eth.get_balance(address) balance = w3.from_wei(balance_wei, 'ether') print(f'Balance: {balance}') # Get balance at specific block historical_balance = w3.eth.get_balance(address, block_identifier=1000000) print(f'Historical balance: {w3.from_wei(historical_balance, "ether")}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d") balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } // Convert to ether fbalance := new(big.Float).SetInt(balance) ethValue := new(big.Float).Quo(fbalance, big.NewFloat(1e18)) fmt.Printf("Balance: %f\n", ethValue) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid address format or block parameter | | -32000 | Execution error | Node execution error | ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_getTransactionCount`](./eth_getTransactionCount) - Get account nonce --- ## eth_getBlockByHash - Gnosis RPC Method # eth_getBlockByHash Returns information about a block by hash on Gnosis. > **Why Gnosis?** Build on the prediction market pioneer with $260M+ TVL and xDAI stablecoin-based gas fees with stablecoin gas fees for predictable costs, Shutter MEV protection, 150K+ Safe wallets, and Circles decentralized UBI protocol. ## Use Cases The `eth_getBlockByHash` method is essential for: - **Block verification** - Verify block data using its unique hash - **Chain reorganization handling** - Track blocks during reorgs - **Cross-chain bridges** - Verify block finality for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration - **Deterministic queries** - Get consistent block data regardless of chain state ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0xb7d40246868f4037c9d681df4f45634e7b378187531f3ca53b56f97350b622a1", false ], "id": 1 } ``` ## Returns Returns the same block object as `eth_getBlockByNumber`, or `null` if no block is found. | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used | | `transactions` | `Array` | Transaction objects or hashes | ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0xb7d40246868f4037c9d681df4f45634e7b378187531f3ca53b56f97350b622a1", false ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0xb7d40246868f4037c9d681df4f45634e7b378187531f3ca53b56f97350b622a1'; const block = await provider.getBlock(blockHash); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) block_hash = '0xb7d40246868f4037c9d681df4f45634e7b378187531f3ca53b56f97350b622a1' block = w3.eth.get_block(block_hash) print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockHash := common.HexToHash("0xb7d40246868f4037c9d681df4f45634e7b378187531f3ca53b56f97350b622a1") block, err := client.BlockByHash(context.Background(), blockHash) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block hash format | | -32000 | Block not found | Block with this hash does not exist | ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) - Get block by number - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number --- ## eth_getBlockByNumber - Gnosis RPC Method # eth_getBlockByNumber Returns information about a block by block number on Gnosis. > **Why Gnosis?** Build on the prediction market pioneer with $260M+ TVL and xDAI stablecoin-based gas fees with stablecoin gas fees for predictable costs, Shutter MEV protection, 150K+ Safe wallets, and Circles decentralized UBI protocol. ## Use Cases The `eth_getBlockByNumber` method is essential for: - **Block explorers** - Display complete block information - **Transaction indexers** - Process all transactions in a block - **Analytics platforms** - Analyze blockchain data for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration - **Timestamp verification** - Get block timestamps for time-based logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used by all transactions | | `gasLimit` | `QUANTITY` | Maximum gas allowed in block | | `transactions` | `Array` | Array of transaction objects or hashes | | `baseFeePerGas` | `QUANTITY` | Base fee per gas (EIP-1559) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": { "number": "0x5BAD55", "hash": "0xb7d40246868f4037c9d681df4f45634e7b378187531f3ca53b56f97350b622a1", "parentHash": "0x...", "timestamp": "0x64d8f6d0", "gasUsed": "0x1234", "gasLimit": "0x1c9c380", "transactions": [], "baseFeePerGas": "0x5f5e100" } } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); // Get latest block const block = await provider.getBlock('latest'); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); console.log('Transactions:', block.transactions.length); // Get block with full transactions const blockWithTxs = await provider.getBlock('latest', true); for (const tx of blockWithTxs.prefetchedTransactions) { console.log('Transaction:', tx.hash); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) # Get latest block block = w3.eth.get_block('latest') print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') print(f'Transactions: {len(block.transactions)}') # Get block with full transactions block_full = w3.eth.get_block('latest', full_transactions=True) for tx in block_full.transactions: print(f'Transaction: {tx.hash.hex()}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } // Get latest block block, err := client.BlockByNumber(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) fmt.Printf("Timestamp: %d\n", block.Time()) fmt.Printf("Transactions: %d\n", len(block.Transactions())) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block number or parameter format | | -32000 | Block not found | Block does not exist | ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number - [`eth_getBlockByHash`](./eth_getBlockByHash) - Get block by hash - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_getCode - Gnosis RPC Method # eth_getCode Returns the bytecode at a given address on Gnosis. > **Why Gnosis?** Build on the prediction market pioneer with $260M+ TVL and xDAI stablecoin-based gas fees with stablecoin gas fees for predictable costs, Shutter MEV protection, 150K+ Safe wallets, and Circles decentralized UBI protocol. ## Use Cases The `eth_getCode` method is essential for: - **Contract verification** - Check if address is a contract - **Security analysis** - Verify deployed bytecode matches expected - **DeFi integrations** - Validate contracts before interactions - **Protocol analysis** - Analyze contract deployments for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Contract bytecode or `0x` if EOA | ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d'; const code = await provider.getCode(address); if (code === '0x') { console.log('Address is an EOA (externally owned account)'); } else { console.log('Address is a contract'); console.log('Bytecode length:', code.length); } // Check if address is a contract async function isContract(address) { const code = await provider.getCode(address); return code !== '0x'; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d' code = w3.eth.get_code(address) if code == b'': print('Address is an EOA') else: print('Address is a contract') print(f'Bytecode length: {len(code.hex())}') # Check if address is a contract def is_contract(address): code = w3.eth.get_code(address) return code != b'' ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d") code, err := client.CodeAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } if len(code) == 0 { fmt.Println("Address is an EOA") } else { fmt.Printf("Contract bytecode length: %d\n", len(code)) } } ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_getStorageAt`](./eth_getStorageAt) - Get contract storage --- ## eth_getFilterChanges - Gnosis RPC Method # eth_getFilterChanges Polling method for a filter on Gnosis, returns an array of logs since last poll. ## Use Cases - **Event streaming** - Get new events incrementally - **Real-time monitoring** - Track contract activity for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration - **Efficient indexing** - Process only new events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); // Poll loop async function pollFilter(filterId, interval = 2000) { while (true) { const changes = await provider.send('eth_getFilterChanges', [filterId]); if (changes.length > 0) { console.log('New events:', changes); } await new Promise(r => setTimeout(r, interval)); } } ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter --- ## eth_getFilterLogs - Gnosis RPC Method # eth_getFilterLogs Returns an array of all logs matching filter with given ID on Gnosis. ## Use Cases - **Historical queries** - Get all matching logs for a filter - **Full event history** - Retrieve complete event data for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const logs = await provider.send('eth_getFilterLogs', [filterId]); console.log('All matching logs:', logs.length); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_getLogs - Gnosis RPC Method # eth_getLogs Returns an array of all logs matching a given filter object on Gnosis. > **Why Gnosis?** Build on the prediction market pioneer with $260M+ TVL and xDAI stablecoin-based gas fees with stablecoin gas fees for predictable costs, Shutter MEV protection, 150K+ Safe wallets, and Circles decentralized UBI protocol. ## Use Cases The `eth_getLogs` method is essential for: - **Event indexing** - Track contract events for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration - **Token transfers** - Monitor ERC20/ERC721 transfers - **DeFi analytics** - Track swaps, liquidity events, and more - **Notification systems** - Alert on specific on-chain events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block (default: `"latest"`) | | `toBlock` | `QUANTITY\|TAG` | No | Ending block (default: `"latest"`) | | `address` | `DATA\|Array` | No | Contract address(es) to filter | | `topics` | `Array` | No | Array of topic filters | | `blockHash` | `DATA` | No | Filter single block by hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns Array of log objects: | Field | Type | Description | |-------|------|-------------| | `address` | `DATA` | Contract that emitted the log | | `topics` | `Array` | Array of indexed topics | | `data` | `DATA` | Non-indexed log data | | `blockNumber` | `QUANTITY` | Block number | | `transactionHash` | `DATA` | Transaction hash | | `logIndex` | `QUANTITY` | Log index in block | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": [{ "address": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."], "data": "0x...", "blockNumber": "0x5BAD55", "transactionHash": "0x...", "logIndex": "0x0" }] } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); // Get Transfer events const TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'; async function getTransferEvents(tokenAddress, fromBlock, toBlock) { const logs = await provider.getLogs({ address: tokenAddress, topics: [TRANSFER_TOPIC], fromBlock: fromBlock, toBlock: toBlock }); return logs.map(log => ({ from: '0x' + log.topics[1].slice(26), to: '0x' + log.topics[2].slice(26), blockNumber: log.blockNumber, transactionHash: log.transactionHash })); } const events = await getTransferEvents( '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d', 'latest', 'latest' ); console.log('Transfer events:', events); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' def get_transfer_events(token_address, from_block, to_block): logs = w3.eth.get_logs({ 'address': token_address, 'topics': [TRANSFER_TOPIC], 'fromBlock': from_block, 'toBlock': to_block }) events = [] for log in logs: events.append({ 'from': '0x' + log['topics'][1].hex()[26:], 'to': '0x' + log['topics'][2].hex()[26:], 'block': log['blockNumber'], 'tx': log['transactionHash'].hex() }) return events events = get_transfer_events( '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d', 'latest', 'latest' ) print(f'Found {len(events)} transfer events') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d") transferTopic := common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef") query := ethereum.FilterQuery{ FromBlock: big.NewInt(0), ToBlock: nil, Addresses: []common.Address{contractAddress}, Topics: [][]common.Hash, } logs, err := client.FilterLogs(context.Background(), query) if err != nil { log.Fatal(err) } fmt.Printf("Found %d events\n", len(logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32005 | Query returned more than 10000 results | Reduce block range | | -32602 | Invalid params | Invalid filter parameters | ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create a filter for logs - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for new logs --- ## eth_getStorageAt - Gnosis RPC Method # eth_getStorageAt Returns the value from a storage position at a given address on Gnosis. ## Use Cases - **Contract analysis** - Read raw storage values - **State verification** - Verify contract state - **Security auditing** - Analyze storage layout for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration - **Protocol monitoring** - Track state changes ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte contract address | | `position` | `QUANTITY` | Yes | Storage slot position | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "0x0", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "0x0", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d'; const slot = 0; const storage = await provider.getStorage(address, slot); console.log('Storage at slot 0:', storage); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d' storage = w3.eth.get_storage_at(address, 0) print(f'Storage at slot 0: {storage.hex()}') ``` ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_call`](./eth_call) - Call contract functions --- ## eth_getTransactionByHash - Gnosis RPC Method # eth_getTransactionByHash Returns the information about a transaction by transaction hash on Gnosis. > **Why Gnosis?** Build on the prediction market pioneer with $260M+ TVL and xDAI stablecoin-based gas fees with stablecoin gas fees for predictable costs, Shutter MEV protection, 150K+ Safe wallets, and Circles decentralized UBI protocol. ## Use Cases The `eth_getTransactionByHash` method is essential for: - **Transaction tracking** - Get details of pending or confirmed transactions - **Payment verification** - Verify transaction parameters - **Debugging** - Analyze transaction data for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration - **Block explorers** - Display transaction information ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `hash` | `DATA` | Transaction hash | | `from` | `DATA` | Sender address | | `to` | `DATA` | Recipient address | | `value` | `QUANTITY` | Value in wei | | `gas` | `QUANTITY` | Gas provided | | `gasPrice` | `QUANTITY` | Gas price in wei | | `input` | `DATA` | Transaction input data | | `nonce` | `QUANTITY` | Sender's nonce | | `blockHash` | `DATA` | Block hash (null if pending) | | `blockNumber` | `QUANTITY` | Block number (null if pending) | ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814'; const tx = await provider.getTransaction(txHash); if (tx) { console.log('From:', tx.from); console.log('To:', tx.to); console.log('Value:', formatEther(tx.value)); console.log('Block:', tx.blockNumber); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814' tx = w3.eth.get_transaction(tx_hash) if tx: print(f'From: {tx["from"]}') print(f'To: {tx["to"]}') print(f'Value: {w3.from_wei(tx["value"], "ether")}') print(f'Block: {tx["blockNumber"]}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814") tx, isPending, err := client.TransactionByHash(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Pending: %v\n", isPending) fmt.Printf("Value: %s\n", tx.Value().String()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash format | ## Related Methods - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction receipt - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionCount - Gnosis RPC Method # eth_getTransactionCount Returns the number of transactions sent from an address on Gnosis (the nonce). ## Use Cases - **Transaction building** - Get correct nonce for new transactions - **Account analysis** - Count total outgoing transactions - **Nonce management** - Handle pending transaction queues - **Wallet operations** - Prepare transactions for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag (`pending` for next nonce) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const address = '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d'; const nonce = await provider.getTransactionCount(address); console.log('Nonce:', nonce); // Get pending nonce for new transaction const pendingNonce = await provider.getTransactionCount(address, 'pending'); console.log('Next nonce:', pendingNonce); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) address = '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d' nonce = w3.eth.get_transaction_count(address) print(f'Nonce: {nonce}') # Get pending nonce pending_nonce = w3.eth.get_transaction_count(address, 'pending') print(f'Next nonce: {pending_nonce}') ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionReceipt - Gnosis RPC Method # eth_getTransactionReceipt Returns the receipt of a transaction by transaction hash on Gnosis. Receipt is only available for mined transactions. > **Why Gnosis?** Build on the prediction market pioneer with $260M+ TVL and xDAI stablecoin-based gas fees with stablecoin gas fees for predictable costs, Shutter MEV protection, 150K+ Safe wallets, and Circles decentralized UBI protocol. ## Use Cases The `eth_getTransactionReceipt` method is essential for: - **Transaction confirmation** - Verify transaction was mined successfully - **Gas analysis** - Check actual gas used vs estimated - **Event parsing** - Read emitted events from logs - **Status verification** - Confirm success/failure for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `status` | `QUANTITY` | `1` (success) or `0` (failure) | | `transactionHash` | `DATA` | Transaction hash | | `blockHash` | `DATA` | Block hash | | `blockNumber` | `QUANTITY` | Block number | | `gasUsed` | `QUANTITY` | Gas used by this transaction | | `cumulativeGasUsed` | `QUANTITY` | Total gas used in block up to this tx | | `logs` | `Array` | Array of log objects | | `contractAddress` | `DATA` | Created contract address (if deployment) | ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814'; const receipt = await provider.getTransactionReceipt(txHash); if (receipt) { console.log('Status:', receipt.status === 1 ? 'Success' : 'Failed'); console.log('Gas Used:', receipt.gasUsed.toString()); console.log('Block:', receipt.blockNumber); console.log('Logs:', receipt.logs.length); // Parse specific events for (const log of receipt.logs) { console.log('Event from:', log.address); } } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814' receipt = w3.eth.get_transaction_receipt(tx_hash) if receipt: status = 'Success' if receipt['status'] == 1 else 'Failed' print(f'Status: {status}') print(f'Gas Used: {receipt["gasUsed"]}') print(f'Block: {receipt["blockNumber"]}') print(f'Logs: {len(receipt["logs"])}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814") receipt, err := client.TransactionReceipt(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Status: %d\n", receipt.Status) fmt.Printf("Gas Used: %d\n", receipt.GasUsed) fmt.Printf("Logs: %d\n", len(receipt.Logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash | **Note**: Returns `null` if transaction is not yet mined. ## Related Methods - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details - [`eth_getLogs`](./eth_getLogs) - Query logs by filter --- ## eth_hashrate - Get node hashrate(Gnosis) # eth_hashrate Get node hashrate on the Gnosis Chain network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_hashrate](https://ethereum.org/developers/docs/apis/json-rpc/#eth_hashrate) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_hashrate", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_hashrate', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Gnosis documentation](https://docs.gnosischain.com/).* --- ## eth_maxPriorityFeePerGas - Gnosis RPC Method # eth_maxPriorityFeePerGas Returns the current recommended priority fee per gas on Gnosis for EIP-1559 transactions. ## Use Cases - **EIP-1559 transactions** - Set appropriate priority fees - **Transaction acceleration** - Calculate tips for faster inclusion - **Gas optimization** - Balance speed vs cost for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); console.log('Max Priority Fee:', formatUnits(feeData.maxPriorityFeePerGas, 'gwei'), 'Gwei'); console.log('Max Fee Per Gas:', formatUnits(feeData.maxFeePerGas, 'gwei'), 'Gwei'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) priority_fee = w3.eth.max_priority_fee print(f'Max Priority Fee: {w3.from_wei(priority_fee, "gwei")} Gwei') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get legacy gas price - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data --- ## eth_mining - Check if node is mining(Gnosis) # eth_mining Check if node is mining on the Gnosis Chain network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_mining](https://ethereum.org/developers/docs/apis/json-rpc/#eth_mining) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_mining', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Gnosis documentation](https://docs.gnosischain.com/).* --- ## eth_newBlockFilter - Gnosis RPC Method # eth_newBlockFilter Creates a filter on Gnosis to notify when a new block arrives. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newBlockFilter', []); // Poll for new blocks const newBlocks = await provider.send('eth_getFilterChanges', [filterId]); console.log('New block hashes:', newBlocks); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_blockNumber`](./eth_blockNumber) - Get current block --- ## eth_newFilter - Gnosis RPC Method # eth_newFilter Creates a filter object on Gnosis to notify when state changes (logs). ## Use Cases - **Event monitoring** - Subscribe to contract events - **Real-time updates** - Track events for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration - **Indexing** - Build event indexes incrementally ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block | | `toBlock` | `QUANTITY\|TAG` | No | Ending block | | `address` | `DATA\|Array` | No | Contract address(es) | | `topics` | `Array` | No | Topic filters | ## Request ```json { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); // Create filter const filterId = await provider.send('eth_newFilter', [{ fromBlock: 'latest', address: '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d', topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'] }]); // Poll for changes const changes = await provider.send('eth_getFilterChanges', [filterId]); console.log('New events:', changes); // Cleanup await provider.send('eth_uninstallFilter', [filterId]); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for changes - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_newPendingTransactionFilter - Gnosis RPC Method # eth_newPendingTransactionFilter Creates a filter on Gnosis to notify when new pending transactions arrive. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newPendingTransactionFilter', []); // Poll for pending transactions const pendingTxs = await provider.send('eth_getFilterChanges', [filterId]); console.log('Pending transaction hashes:', pendingTxs); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_protocolVersion - Get protocol version(Gnosis) # eth_protocolVersion Get protocol version on the Gnosis Chain network. ## Parameters Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_protocolVersion](https://ethereum.org/developers/docs/apis/json-rpc/#eth_protocolversion) documentation for detailed parameter information. ## Returns The return value depends on the specific method being called. ## Implementation Example ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_protocolVersion", "params": [], "id": 1 }' ``` ```javascript const response = await fetch('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_protocolVersion', params: [], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Gnosis documentation](https://docs.gnosischain.com/).* --- ## eth_sendRawTransaction - Gnosis RPC Method # eth_sendRawTransaction Submits a pre-signed transaction for broadcast to Gnosis. > **Why Gnosis?** Build on the prediction market pioneer with $260M+ TVL and xDAI stablecoin-based gas fees with stablecoin gas fees for predictable costs, Shutter MEV protection, 150K+ Safe wallets, and Circles decentralized UBI protocol. ## Use Cases The `eth_sendRawTransaction` method is essential for: - **Broadcasting transactions** - Submit signed transactions to the network - **Wallet operations** - Send native tokens and interact with contracts - **DeFi operations** - Execute swaps, provide liquidity for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration - **Batch operations** - Submit multiple transactions efficiently ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `signedTransactionData` | `DATA` | Yes | The signed transaction data (RLP encoded) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | 32-byte transaction hash | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c808504a817c80082520894..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const wallet = new Wallet('YOUR_PRIVATE_KEY', provider); // Send native tokens async function sendTransaction(to, value) { const tx = await wallet.sendTransaction({ to: to, value: parseEther(value) }); console.log('Transaction hash:', tx.hash); // Wait for confirmation const receipt = await tx.wait(); console.log('Confirmed in block:', receipt.blockNumber); return receipt; } // Send to contract async function sendContractTransaction(contract, method, args, value = '0') { const tx = await contract[method](...args, { value: parseEther(value) }); return await tx.wait(); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) def send_transaction(private_key, to, value_in_ether): account = w3.eth.account.from_key(private_key) # Build transaction tx = { 'nonce': w3.eth.get_transaction_count(account.address), 'to': to, 'value': w3.to_wei(value_in_ether, 'ether'), 'gas': 21000, 'gasPrice': w3.eth.gas_price, 'chainId': w3.eth.chain_id } # Sign transaction signed_tx = account.sign_transaction(tx) # Send transaction tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) print(f'Transaction hash: {tx_hash.hex()}') # Wait for confirmation receipt = w3.eth.wait_for_transaction_receipt(tx_hash) print(f'Confirmed in block: {receipt["blockNumber"]}') return receipt ``` ```go package main "context" "crypto/ecdsa" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY") if err != nil { log.Fatal(err) } publicKey := privateKey.Public() publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey) fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA) nonce, _ := client.PendingNonceAt(context.Background(), fromAddress) value := big.NewInt(1000000000000000000) gasLimit := uint64(21000) gasPrice, _ := client.SuggestGasPrice(context.Background()) toAddress := common.HexToAddress("0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d") tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil) chainID, _ := client.NetworkID(context.Background()) signedTx, _ := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey) err = client.SendTransaction(context.Background(), signedTx) if err != nil { log.Fatal(err) } fmt.Printf("Transaction hash: %s\n", signedTx.Hash().Hex()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Nonce too low | Transaction nonce already used | | -32000 | Insufficient funds | Account has insufficient balance | | -32000 | Gas too low | Gas limit insufficient | | -32000 | Replacement underpriced | Gas price too low for replacement | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas required - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction result --- ## eth_sendTransaction - Send transaction (walle...(Gnosis) # eth_sendTransaction > **Important**: Dwellir's shared Gnosis endpoints do not manage user private keys. JSON-RPC nodes cannot unlock your account, so `eth_sendTransaction` calls will fail. Sign transactions client-side and broadcast them with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Why this method is disabled on shared nodes - [`eth_sendTransaction` requires the node to hold and unlock the `from` account's private key](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sendtransaction). - Managed infrastructure providers disable it for security reasons rather than storing customer keys on shared servers (for example, [Infura explicitly blocks the method on shared endpoints](https://docs.infura.io/api/networks/ethereum/json-rpc-methods/eth_sendtransaction)). ## Recommended workflow 1. Build the raw transaction locally with your wallet or SDK. 2. Sign the payload client-side (hardware wallet, custodial service, or library). 3. Submit the signed hex string with [`eth_sendRawTransaction`](./eth_sendRawTransaction). ## Example response from the shared endpoint ```bash curl -s -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","method":"eth_sendTransaction","params":[{"from":"0x0000000000000000000000000000000000000000"}],"id":1}' ``` ```json {"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"unknown account"}} ``` Need help? Contact our [support team](mailto:support@dwellir.com) or use the dedicated [`eth_sendRawTransaction`](./eth_sendRawTransaction) guide. --- ## eth_signTransaction - Sign transaction (rarel...(Gnosis) # eth_signTransaction Signs a transaction using an unlocked account on the node. **Important**: Most RPC providers don't support this method for security reasons, as it requires private keys to be stored on the server. ## Security Considerations - This method requires an unlocked account on the node - Private keys must be available to the RPC server - Most production RPC providers disable this method - Use client-side signing libraries instead for better security ## Parameters 1. `Object` - The transaction object: - `from`: `DATA`, 20 Bytes - The address the transaction is sent from - `to`: `DATA`, 20 Bytes - (optional) The address the transaction is directed to - `gas`: `QUANTITY` - (optional) Integer of the gas provided for the transaction execution - `gasPrice`: `QUANTITY` - (optional) Integer of the gasPrice used for each paid gas - `value`: `QUANTITY` - (optional) Integer of the value sent with this transaction - `data`: `DATA` - (optional) The compiled code of a contract OR the hash of the invoked method signature and encoded parameters ## Returns `DATA` - The signed transaction data, ready for transmission via `eth_sendRawTransaction`. ## Implementation Example ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_signTransaction", "params": [{ "from": "0x9b2055d370f73ec7d8a03e965129118dc8f5bf83", "to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567", "gas": "0x76c0", "gasPrice": "0x9184e72a000", "value": "0x9184e72a" }], "id": 1 }' ``` ```javascript const response = await fetch('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_signTransaction', params: [{ from: '0x9b2055d370f73ec7d8a03e965129118dc8f5bf83', to: '0xd46e8dd67c5d32be8058bb8eb970870f07244567', gas: '0x76c0', gasPrice: '0x9184e72a000', value: '0x9184e72a' }], id: 1 }) }); const data = await response.json(); console.log(data.result); ``` ## Response Example ```json { "jsonrpc": "2.0", "id": 1, "result": "0xf86c808504a817c8008276c094d46e8dd67c5d32be8058bb8eb970870f072445675849184e72a8001ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804" } ``` **Note**: This method is typically not available on hosted RPC providers for security reasons. The response shows a signed transaction ready for broadcast. --- *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Gnosis documentation](https://docs.gnosischain.com/).* --- ## eth_syncing - Gnosis RPC Method # eth_syncing Returns syncing status of Gnosis node. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 } ``` ## Returns Returns `false` if not syncing, or an object with sync status. ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const syncing = await provider.send('eth_syncing', []); if (syncing === false) { console.log('Node is fully synced'); } else { console.log('Syncing:', syncing); } ``` ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get current block - [`net_peerCount`](./net_peerCount) - Get peer count --- ## eth_uninstallFilter - Gnosis RPC Method # eth_uninstallFilter Uninstalls a filter on Gnosis. Should be called when no longer needed. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID to uninstall | ## Request ```json { "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if filter was found and uninstalled | ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const success = await provider.send('eth_uninstallFilter', [filterId]); console.log('Filter removed:', success); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter --- ## Gnosis Chain - Ethereum Sidechain # Gnosis Chain - Build on the Community-Owned Ethereum Sidechain ## Why Build on Gnosis Chain? Gnosis Chain is a community-owned, fully decentralized Ethereum sidechain designed for stable and accessible DeFi. Built and maintained by the Gnosis community, Gnosis Chain offers: ### 🚀 **Predictable Transaction Costs** - **xDAI native token** - USD-pegged stablecoin for stable gas fees - **5-second block times** - Fast and predictable confirmations - **Low-cost transactions** - Typical fees under $0.01 ### 🛡️ **True Decentralization** - **140,000+ validators** - World's most decentralized Proof-of-Stake network - **Community governance** - No single entity controls the chain - **Battle-tested security** - Over 3 years of continuous operation ### 🌍 **Mature Ecosystem** - **$200M+ TVL** - Established DeFi protocols - **EVM compatibility** - Full Ethereum tooling support - **Bridge ecosystem** - Native bridges to Ethereum and other chains ## Quick Start with Gnosis Chain Connect to Gnosis Chain in seconds with Dwellir's optimized endpoints: ### Installation & Setup ```javascript // Connect to Gnosis Chain mainnet const provider = new JsonRpcProvider( 'https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY' ); // Get the latest block const block = await provider.getBlock('latest'); console.log('Latest block:', block.number); // Query account balance (returns xDAI balance) const balance = await provider.getBalance('0x...'); console.log('Balance:', balance.toString(), 'wei (xDAI)'); ``` ```javascript const Web3 = require('web3'); // Connect to Gnosis Chain mainnet const web3 = new Web3( 'https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY' ); // Get chain ID to verify connection const chainId = await web3.eth.getChainId(); console.log('Connected to Gnosis Chain:', chainId === 100); // Get gas price (in xDAI) const gasPrice = await web3.eth.getGasPrice(); console.log('Current gas price:', gasPrice); ``` ```typescript // Create Gnosis Chain client const client = createPublicClient({ chain: gnosis, transport: http('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'), }); // Read contract data const data = await client.readContract({ address: '0x...', abi: contractAbi, functionName: 'balanceOf', args: ['0x...'], }); ``` ## Network Information Chain ID 100 Mainnet Block Time 5 seconds Average Gas Token xDAI USD-pegged RPC Standard Ethereum JSON-RPC 2.0 ## JSON-RPC API Reference Gnosis Chain supports the full [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/) with sidechain-specific optimizations. ## Common Integration Patterns ### 🔄 Transaction Monitoring Monitor pending and confirmed transactions efficiently: ```javascript // Watch for transaction confirmation on Gnosis Chain async function waitForTransaction(txHash) { const receipt = await provider.waitForTransaction(txHash, 1); // Gnosis Chain has 5-second blocks for fast confirmations console.log('Transaction confirmed in ~5 seconds'); return receipt; } ``` ### 💰 Gas Optimization Optimize gas costs on Gnosis Chain: ```javascript // Gas estimation on Gnosis Chain const gasEstimate = await provider.estimateGas(tx); // xDAI has predictable pricing (~$1.00) const gasPrice = await provider.getGasPrice(); const costInXDAI = gasEstimate * gasPrice / BigInt(1e18); console.log(`Transaction cost: ${costInXDAI} xDAI (~$${costInXDAI})`); ``` ### 🔍 Event Filtering Efficiently query contract events: ```javascript // Query events with automatic retry and pagination async function getEvents(contract, eventName, fromBlock = 0) { const filter = contract.filters[eventName](); const events = []; const batchSize = 3000; // Gnosis Chain recommended batch size for (let i = fromBlock; i <= currentBlock; i += batchSize) { const batch = await contract.queryFilter( filter, i, Math.min(i + batchSize - 1, currentBlock) ); events.push(...batch); } return events; } ``` ## Performance Best Practices ### 1. **Batch Requests** Combine multiple RPC calls for optimal performance: ```javascript const batch = [ { method: 'eth_blockNumber', params: [] }, { method: 'eth_gasPrice', params: [] }, { method: 'eth_getBalance', params: [address, 'latest'] } ]; const results = await provider.send(batch); ``` ### 2. **Connection Pooling** Reuse provider instances to minimize connection overhead: ```javascript // Singleton pattern for provider class GnosisProvider { static instance = null; static getInstance() { if (!this.instance) { this.instance = new JsonRpcProvider( 'https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY' ); } return this.instance; } } ``` ### 3. **Smart Caching** Cache immutable data to reduce API calls: ```javascript const cache = new Map(); async function getCachedBlockData(blockNumber) { const key = `block_${blockNumber}`; if (!cache.has(key)) { const block = await provider.getBlock(blockNumber); cache.set(key, block); } return cache.get(key); } ``` ## Troubleshooting Common Issues ### Error: "Insufficient funds" Gnosis Chain transactions require xDAI for gas: ```javascript // Check xDAI balance before transactions const balance = await provider.getBalance(address); const gasEstimate = await provider.estimateGas(tx); const gasPrice = await provider.getGasPrice(); const totalRequired = gasEstimate * gasPrice + tx.value; if (balance < totalRequired) { const shortage = ethers.formatEther(totalRequired - balance); throw new Error(`Need ${shortage} more xDAI`); } ``` ### Error: "Transaction underpriced" Gnosis Chain uses EIP-1559 pricing: ```javascript // Get current fee data const feeData = await provider.getFeeData(); const tx = { to: recipient, value: amount, maxFeePerGas: feeData.maxFeePerGas, maxPriorityFeePerGas: feeData.maxPriorityFeePerGas, gasLimit: 21000n }; ``` ### Error: "Rate limit exceeded" Implement exponential backoff for resilient applications: ```javascript async function callWithRetry(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error.code === 429 && i < maxRetries - 1) { await new Promise(r => setTimeout(r, 2 ** i * 1000)); } else { throw error; } } } } ``` ## Migration Guide ### From Ethereum Mainnet Moving from L1 to Gnosis Chain requires minimal changes: ```javascript // Before (Ethereum) const provider = new JsonRpcProvider('https://eth-rpc.example.com'); // After (Gnosis Chain) const provider = new JsonRpcProvider( 'https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY' ); // ✅ Smart contracts work identically // ✅ Same tooling and libraries // ⚠️ Different chain ID (100) // ⚠️ Native token is xDAI (not ETH) // ⚠️ 5-second block times (faster than Ethereum) ``` ## Resources & Tools ### Official Resources - [Gnosis Chain Documentation](https://docs.gnosischain.com) - [Gnosis Chain Bridge](https://bridge.gnosischain.com) - [Gnosis Chain Block Explorer](https://gnosisscan.io) ### Developer Tools - [Hardhat Config](https://docs.gnosischain.com/tools/hardhat) - [Foundry Setup](https://docs.gnosischain.com/tools/foundry) - [Remix Integration](https://docs.gnosischain.com/tools/remix) ### Need Help? - 📧 **Email**: support@dwellir.com - 📚 **Docs**: You're here! - 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com) --- *Start building on Gnosis Chain with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)* --- ## net_listening - Gnosis RPC Method # net_listening Returns `true` if client is actively listening for network connections on Gnosis. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if listening | ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_listening", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const listening = await provider.send('net_listening', []); console.log('Node listening:', listening); ``` ## Related Methods - [`net_peerCount`](./net_peerCount) - Get peer count --- ## net_peerCount - Gnosis RPC Method # net_peerCount Returns number of peers currently connected to Gnosis client. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Number of connected peers (hexadecimal) | ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const peerCount = await provider.send('net_peerCount', []); console.log('Peer count:', parseInt(peerCount, 16)); ``` ## Related Methods - [`net_listening`](./net_listening) - Check if listening --- ## net_version - Gnosis RPC Method # net_version Returns the current network ID on Gnosis. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Network ID as a string | ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "net_version", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const networkId = await provider.send('net_version', []); console.log('Network ID:', networkId); ``` ## Related Methods - [`eth_chainId`](./eth_chainId) - Get chain ID --- ## trace_block - Gnosis RPC Method # trace_block Returns traces for all transactions in a block on Gnosis. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Block analysis** - Inspect all internal transactions in a block - **MEV research** - Analyze transaction ordering and internal calls - **Indexing** - Build comprehensive transaction indexes for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex or tag (`latest`, `earliest`, `pending`) | ## Request ```json { "jsonrpc": "2.0", "method": "trace_block", "params": ["latest"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_block", "params": ["latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('trace_block', ['latest']); console.log('Traces in block:', traces.length); for (const trace of traces.slice(0, 5)) { console.log(` ${trace.action.from} -> ${trace.action.to} (${trace.type})`); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) traces = w3.provider.make_request('trace_block', ['latest']) for trace in traces['result'][:5]: action = trace['action'] print(f'{action["from"]} -> {action.get("to", "CREATE")} ({trace["type"]})') ``` ## Related Methods - [`trace_filter`](./trace_filter) - Filter traces by address or block range - [`trace_transaction`](./trace_transaction) - Trace a specific transaction - [`trace_get`](./trace_get) - Get a specific trace by index --- ## trace_call - Gnosis RPC Method # trace_call Traces a call without creating a transaction on Gnosis, returning the trace output. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Call simulation** - Preview internal calls before sending a transaction - **Contract interaction analysis** - Understand how contracts interact - **Gas estimation** - Analyze gas usage patterns for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `callObject` | `Object` | Yes | Transaction call object (`from`, `to`, `gas`, `value`, `data`) | | `traceTypes` | `Array` | Yes | Trace types: `["trace"]`, `["vmTrace"]`, `["stateDiff"]`, or combinations | | `blockNumber` | `QUANTITY\|TAG` | No | Block number or tag (default: `latest`) | ## Request ```json { "jsonrpc": "2.0", "method": "trace_call", "params": [ { "to": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "data": "0x70a08231000000000000000000000000e91D153E0b41518A2Ce8Dd3D7944Fa863463a97d" }, ["trace"], "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_call", "params": [ {"to": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "data": "0x70a08231000000000000000000000000e91D153E0b41518A2Ce8Dd3D7944Fa863463a97d"}, ["trace"], "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const result = await provider.send('trace_call', [ { to: '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d', data: '0x70a08231000000000000000000000000e91D153E0b41518A2Ce8Dd3D7944Fa863463a97d' }, ['trace'], 'latest' ]); console.log('Trace output:', result.trace); console.log('VM trace:', result.vmTrace); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) result = w3.provider.make_request('trace_call', [ { 'to': '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d', 'data': '0x70a08231000000000000000000000000e91D153E0b41518A2Ce8Dd3D7944Fa863463a97d' }, ['trace'], 'latest' ]) print(f'Trace: {result["result"]["trace"]}') ``` ## Related Methods - [`trace_filter`](./trace_filter) - Filter traces by criteria - [`eth_call`](./eth_call) - Execute call without trace - [`trace_transaction`](./trace_transaction) - Trace a specific transaction --- ## trace_callMany - Gnosis RPC Method # trace_callMany Traces multiple calls in sequence on Gnosis, where each call can depend on the state changes of the previous one. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Multi-step simulation** - Simulate a sequence of dependent transactions - **Arbitrage analysis** - Test multi-hop swap paths - **Batch operations** - Preview multiple contract interactions for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `calls` | `Array` | Yes | Array of `[callObject, traceTypes]` pairs | | `blockNumber` | `QUANTITY\|TAG` | No | Block number or tag (default: `latest`) | Each element in `calls` is a tuple of: - `callObject` - Transaction call object (`from`, `to`, `gas`, `value`, `data`) - `traceTypes` - Array of trace types: `["trace"]`, `["vmTrace"]`, `["stateDiff"]` ## Request ```json { "jsonrpc": "2.0", "method": "trace_callMany", "params": [ [ [{"to": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "data": "0x70a08231000000000000000000000000e91D153E0b41518A2Ce8Dd3D7944Fa863463a97d"}, ["trace"]], [{"to": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "data": "0x18160ddd"}, ["trace"]] ], "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_callMany", "params": [ [ [{"to": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "data": "0x70a08231000000000000000000000000e91D153E0b41518A2Ce8Dd3D7944Fa863463a97d"}, ["trace"]], [{"to": "0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d", "data": "0x18160ddd"}, ["trace"]] ], "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const results = await provider.send('trace_callMany', [ [ [{ to: '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d', data: '0x70a08231000000000000000000000000e91D153E0b41518A2Ce8Dd3D7944Fa863463a97d' }, ['trace']], [{ to: '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d', data: '0x18160ddd' }, ['trace']] ], 'latest' ]); console.log('Call results:', results.length); for (const result of results) { console.log(' Output:', result.output); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) results = w3.provider.make_request('trace_callMany', [ [ [{'to': '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d', 'data': '0x70a08231000000000000000000000000e91D153E0b41518A2Ce8Dd3D7944Fa863463a97d'}, ['trace']], [{'to': '0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d', 'data': '0x18160ddd'}, ['trace']] ], 'latest' ]) for i, result in enumerate(results['result']): print(f'Call {i}: output={result.get("output", "N/A")}') ``` ## Related Methods - [`trace_call`](./trace_call) - Trace a single call - [`eth_call`](./eth_call) - Execute call without trace --- ## trace_filter - Gnosis RPC Method # trace_filter Returns traces matching a filter on Gnosis. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Address activity** - Find all internal transactions involving an address - **Contract monitoring** - Track calls to specific contracts - **Forensic analysis** - Investigate transaction patterns for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterObject` | `Object` | Yes | Filter criteria (see below) | ### Filter Object Fields | Field | Type | Description | |-------|------|-------------| | `fromBlock` | `QUANTITY\|TAG` | Start block (hex or tag) | | `toBlock` | `QUANTITY\|TAG` | End block (hex or tag) | | `fromAddress` | `Array` | Filter by sender addresses | | `toAddress` | `Array` | Filter by receiver addresses | | `after` | `QUANTITY` | Offset for pagination | | `count` | `QUANTITY` | Max results to return | ## Request ```json { "jsonrpc": "2.0", "method": "trace_filter", "params": [{ "fromBlock": "latest", "toBlock": "latest", "toAddress": ["0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d"], "count": 10 }], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_filter", "params": [{ "fromBlock": "latest", "toBlock": "latest", "toAddress": ["0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d"], "count": 10 }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('trace_filter', [{ fromBlock: 'latest', toBlock: 'latest', toAddress: ['0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d'], count: 10 }]); console.log('Matching traces:', traces.length); for (const trace of traces) { console.log(` Block ${trace.blockNumber}: ${trace.action.from} -> ${trace.action.to}`); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) traces = w3.provider.make_request('trace_filter', [{ 'fromBlock': 'latest', 'toBlock': 'latest', 'toAddress': ['0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d'], 'count': 10 }]) for trace in traces['result']: action = trace['action'] print(f'Block {trace["blockNumber"]}: {action["from"]} -> {action.get("to", "CREATE")}') ``` ## Related Methods - [`trace_block`](./trace_block) - Get all traces in a block - [`trace_transaction`](./trace_transaction) - Get traces for a specific transaction - [`eth_getLogs`](./eth_getLogs) - Filter event logs --- ## trace_get - Gnosis RPC Method # trace_get Returns a trace at a specific position within a transaction on Gnosis. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Specific trace lookup** - Get a single trace by its position index - **Internal call inspection** - Examine a specific internal call - **Targeted debugging** - Investigate particular call depth for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `indices` | `Array` | Yes | Trace index positions (e.g., `["0x0"]` for the first trace) | ## Request ```json { "jsonrpc": "2.0", "method": "trace_get", "params": ["0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814", ["0x0"]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_get", "params": ["0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814", ["0x0"]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const trace = await provider.send('trace_get', [ '0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814', ['0x0'] ]); console.log('Trace type:', trace.type); console.log('From:', trace.action.from); console.log('To:', trace.action.to); console.log('Value:', trace.action.value); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) trace = w3.provider.make_request('trace_get', [ '0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814', ['0x0'] ]) result = trace['result'] print(f'Type: {result["type"]}') print(f'From: {result["action"]["from"]}') print(f'To: {result["action"]["to"]}') ``` ## Related Methods - [`trace_transaction`](./trace_transaction) - Get all traces for a transaction - [`trace_block`](./trace_block) - Get all traces in a block --- ## trace_replayBlockTransactions - Gnosis RPC Method # trace_replayBlockTransactions Replays all transactions in a block on Gnosis and returns the requested traces. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Block replay** - Re-execute all transactions with full trace output - **State diff analysis** - Get state changes for every transaction in a block - **VM trace extraction** - Obtain detailed EVM execution traces for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex or tag | | `traceTypes` | `Array` | Yes | Trace types: `["trace"]`, `["vmTrace"]`, `["stateDiff"]`, or combinations | ## Request ```json { "jsonrpc": "2.0", "method": "trace_replayBlockTransactions", "params": ["latest", ["trace"]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_replayBlockTransactions", "params": ["latest", ["trace"]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const results = await provider.send('trace_replayBlockTransactions', [ 'latest', ['trace'] ]); console.log('Transactions replayed:', results.length); for (const result of results.slice(0, 3)) { console.log(` Tx ${result.transactionHash}: ${result.trace.length} traces`); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) results = w3.provider.make_request('trace_replayBlockTransactions', [ 'latest', ['trace'] ]) for tx in results['result'][:3]: print(f'Tx {tx["transactionHash"]}: {len(tx["trace"])} traces') ``` ## Related Methods - [`trace_replayTransaction`](./trace_replayTransaction) - Replay a single transaction - [`trace_block`](./trace_block) - Get traces without replay - [`trace_filter`](./trace_filter) - Filter traces by criteria --- ## trace_replayTransaction - Gnosis RPC Method # trace_replayTransaction Replays a transaction on Gnosis and returns the requested traces. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction replay** - Re-execute a transaction with full trace output - **State diff extraction** - Get exact state changes from a transaction - **VM trace debugging** - Get opcode-level execution details for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `traceTypes` | `Array` | Yes | Trace types: `["trace"]`, `["vmTrace"]`, `["stateDiff"]`, or combinations | ## Request ```json { "jsonrpc": "2.0", "method": "trace_replayTransaction", "params": ["0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814", ["trace"]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_replayTransaction", "params": ["0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814", ["trace"]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const result = await provider.send('trace_replayTransaction', [ '0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814', ['trace'] ]); console.log('Trace:', result.trace.length, 'entries'); console.log('State diff:', result.stateDiff ? 'present' : 'not requested'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) result = w3.provider.make_request('trace_replayTransaction', [ '0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814', ['trace'] ]) trace = result['result'] print(f'Trace entries: {len(trace["trace"])}') ``` ## Related Methods - [`trace_replayBlockTransactions`](./trace_replayBlockTransactions) - Replay all transactions in a block - [`trace_transaction`](./trace_transaction) - Get traces without replay - [`trace_block`](./trace_block) - Get all traces in a block --- ## trace_transaction - Gnosis RPC Method # trace_transaction Returns all traces for a specific transaction on Gnosis. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction analysis** - See all internal calls made by a transaction - **Token transfer tracking** - Trace value flows through contracts - **Debugging** - Understand execution flow for prediction markets (largest by market cap), Safe wallet infrastructure, CoW Protocol DEX, and Gnosis Pay card integration ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "trace_transaction", "params": ["0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "trace_transaction", "params": ["0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('trace_transaction', [ '0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814' ]); console.log('Traces:', traces.length); for (const trace of traces) { console.log(` ${trace.action.from} -> ${trace.action.to} (${trace.type})`); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY')) traces = w3.provider.make_request('trace_transaction', [ '0x299f6371b38ceebe7468ea5ef8bb50ae739dfe4e0aa3dac121e6707e240c9814' ]) for trace in traces['result']: action = trace['action'] print(f'{action["from"]} -> {action.get("to", "CREATE")} ({trace["type"]})') ``` ## Related Methods - [`trace_get`](./trace_get) - Get a specific trace by index - [`trace_block`](./trace_block) - Get all traces in a block - [`trace_filter`](./trace_filter) - Filter traces by criteria --- ## web3_clientVersion - Gnosis RPC Method # web3_clientVersion Returns the current client version on Gnosis. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Client version string | ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); const version = await provider.send('web3_clientVersion', []); console.log('Client version:', version); ``` --- ## web3_sha3 - Gnosis RPC Method # web3_sha3 Returns Keccak-256 (not standard SHA3-256) of the given data on Gnosis. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `data` | `DATA` | Yes | Data to hash | ## Request ```json { "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Keccak-256 hash of the data | ## Code Examples ```bash curl -X POST https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "web3_sha3", "params": ["0x68656c6c6f"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-gnosis-mainnet.n.dwellir.com/YOUR_API_KEY'); // Using RPC const hash = await provider.send('web3_sha3', ['0x68656c6c6f']); console.log('Hash:', hash); // Using ethers directly (faster) const localHash = keccak256(toUtf8Bytes('hello')); console.log('Local hash:', localHash); ``` --- ## author_pendingExtrinsics - Hydration RPC Method # author_pendingExtrinsics Returns all pending extrinsics in the transaction pool on Hydration. ## Use Cases - **Mempool monitoring** - Track pending transactions - **Transaction status** - Check if your transaction is pending for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Pool analysis** - Monitor network activity ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "author_pendingExtrinsics", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_pendingExtrinsics", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const pending = await api.rpc.author.pendingExtrinsics(); console.log('Pending extrinsics:', pending.length); pending.forEach((ext, idx) => { console.log(`${idx}: ${ext.method.section}.${ext.method.method}`); }); await api.disconnect(); ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction --- ## author_rotateKeys - Hydration RPC Method # author_rotateKeys Generate a new set of session keys on Hydration. This method creates fresh cryptographic keys for validator operations and stores them in the node's keystore. The returned keys must be registered on-chain via `session.setKeys`. ## Use Cases - **Validator setup** - Generate initial session keys for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Key rotation** - Periodically rotate keys for security best practices - **Recovery** - Generate new keys after potential key compromise ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | `Bytes` | Concatenated SCALE-encoded public keys for all session key types | ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_rotateKeys", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Generate new session keys const keys = await api.rpc.author.rotateKeys(); console.log('New session keys:', keys.toHex()); // These keys need to be registered on-chain: // api.tx.session.setKeys(keys, proof) await api.disconnect(); ``` ```python url = 'https://api-hydradx.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'author_rotateKeys', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json() if 'result' in result: session_keys = result['result'] print(f'New session keys: {session_keys}') print('Register these keys using session.setKeys extrinsic') else: print(f"Error: {result.get('error')}") ``` ## Validator Setup Workflow 1. **Generate keys** - Call `author_rotateKeys` on your validator node 2. **Register on-chain** - Submit `session.setKeys(keys, proof)` extrinsic 3. **Wait for session** - Keys become active in the next session 4. **Verify** - Check `session.nextKeys` storage ## Security Considerations - Only call this method on your own validator node - Session keys are stored in the node's keystore - Rotate keys periodically and after any security incident - Never expose this RPC method publicly ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit setKeys transaction - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - View pending transactions --- ## author_submitAndWatchExtrinsic - Hydration RPC Method # author_submitAndWatchExtrinsic Submit a signed extrinsic to and subscribe to status updates. This WebSocket method provides real-time feedback on transaction progress from submission through finalization. ## Use Cases - **Transaction tracking** - Monitor extrinsic lifecycle for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **UI feedback** - Show users real-time transaction status - **Confirmation workflows** - Wait for specific finality level before proceeding ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `Bytes` | Yes | SCALE-encoded signed extrinsic | ## Returns Returns a subscription that emits `ExtrinsicStatus` updates: | Status | Description | |--------|-------------| | `future` | In future queue (nonce too high) | | `ready` | In ready queue, waiting for block | | `broadcast` | Broadcast to peers | | `inBlock` | Included in block (hash provided) | | `retracted` | Block retracted (reorg) | | `finalityTimeout` | Finality timeout | | `finalized` | Finalized in block (hash provided) | | `usurped` | Replaced by another extrinsic | | `dropped` | Dropped from pool | | `invalid` | Invalid extrinsic | ## Code Examples ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const keyring = new Keyring({ type: 'sr25519' }); // Create and sign a transfer const sender = keyring.addFromUri('//Alice'); const transfer = api.tx.balances.transferKeepAlive( '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 1000000000000n ); // Submit and watch const unsub = await transfer.signAndSend(sender, ({ status, events }) => { console.log(`Status: ${status.type}`); if (status.isInBlock) { console.log(`Included in block: ${status.asInBlock.toHex()}`); } if (status.isFinalized) { console.log(`Finalized in block: ${status.asFinalized.toHex()}`); unsub(); } }); ``` ```python async def submit_and_watch(signed_extrinsic_hex): uri = 'wss://api-hydradx.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: # Submit and subscribe await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'author_submitAndWatchExtrinsic', 'params': [signed_extrinsic_hex], 'id': 1 })) # Get subscription ID response = json.loads(await ws.recv()) if 'error' in response: print(f"Error: {response['error']}") return sub_id = response['result'] print(f'Watching with subscription: {sub_id}') # Listen for status updates while True: message = json.loads(await ws.recv()) if 'params' in message: status = message['params']['result'] print(f"Status: {status}") # Check for finalization if isinstance(status, dict) and 'finalized' in status: print(f"Finalized in: {status['finalized']}") break # asyncio.run(submit_and_watch('0x...')) ``` ## Status Flow ``` ready → broadcast → inBlock → finalized ↘ retracted (if reorg) ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit without watching (fire-and-forget) - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - View transaction pool - [`payment_queryInfo`](./payment_queryInfo) - Estimate fees before submission --- ## author_submitExtrinsic - Hydration RPC Method # author_submitExtrinsic Submit a signed extrinsic to Hydration for inclusion in a block. ## Use Cases - **Transaction submission** - Broadcast signed transactions - **dApp interactions** - Execute on-chain operations for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Automated systems** - Submit programmatic transactions ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `String` | Yes | Hex-encoded signed extrinsic | ## Request ```json { "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": ["0x..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `String` | Transaction hash | ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "author_submitExtrinsic", "params": ["0x..."], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const keyring = new Keyring({ type: 'sr25519' }); const sender = keyring.addFromUri('//Alice'); // Build and sign transaction const transfer = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000); const hash = await transfer.signAndSend(sender); console.log('Transaction hash:', hash.toHex()); await api.disconnect(); ``` ## Related Methods - [`author_pendingExtrinsics`](./author_pendingExtrinsics) - Get pending transactions - [`payment_queryInfo`](./payment_queryInfo) - Estimate fees --- ## beefy_getFinalizedHead - Hydration RPC Method # beefy_getFinalizedHead Returns the block hash of the latest BEEFY-finalized block on Hydration. BEEFY (Bridge Efficiency Enabling Finality Yielder) provides additional finality proofs optimized for light clients and bridges. ## Use Cases - **Cross-chain bridges** - Verify finality proofs for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Light clients** - Efficient finality verification without full GRANDPA proofs - **Trustless bridges** - Generate compact finality proofs for external chains ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | `Hash` | Block hash of the latest BEEFY-finalized block | ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "beefy_getFinalizedHead", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get BEEFY finalized head const beefyHead = await api.rpc.beefy.getFinalizedHead(); console.log('BEEFY finalized:', beefyHead.toHex()); // Compare with GRANDPA finalized const grandpaHead = await api.rpc.chain.getFinalizedHead(); console.log('GRANDPA finalized:', grandpaHead.toHex()); await api.disconnect(); ``` ```python url = 'https://api-hydradx.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'beefy_getFinalizedHead', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json() if 'result' in result: print(f"BEEFY finalized: {result['result']}") else: print(f"Error: {result.get('error')}") ``` ## BEEFY vs GRANDPA Finality | Aspect | GRANDPA | BEEFY | |--------|---------|-------| | **Purpose** | Primary finality | Bridge-optimized finality | | **Proof size** | Larger (full validator set) | Compact (aggregated signatures) | | **Latency** | Immediate | Slightly delayed | | **Use case** | On-chain finality | Cross-chain bridges | ## Availability BEEFY is enabled on relay chains and some parachains. If BEEFY is not enabled, this method will return an error. ## Related Methods - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - GRANDPA finalized head - [`grandpa_roundState`](./grandpa_roundState) - GRANDPA consensus state - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks --- ## chain_getBlock - Hydration RPC Method # chain_getBlock Retrieves complete block information from Hydration, including the block header, extrinsics, and justifications. > **Why Hydration?** Build on Polkadot's leading DEX with $200M+ TVL, Omnipool AMM, and native HOLLAR stablecoin with Omnipool with reduced slippage, permissioned listings, 3M DOT DAO allocation, and 200%+ APR farm yields. ## Use Cases The `chain_getBlock` method is essential for: - **Block explorers** - Display complete block information - **Chain analysis** - Analyze block production patterns - **Transaction verification** - Confirm extrinsic inclusion for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Data indexing** - Build historical blockchain databases ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Hex-encoded block hash. If omitted, returns latest block | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getBlock", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `block` | `Object` | Complete block data | | `block.header` | `Object` | Block header information | | `block.header.parentHash` | `String` | Hash of the parent block | | `block.header.number` | `String` | Block number (hex-encoded) | | `block.header.stateRoot` | `String` | Root of the state trie | | `block.header.extrinsicsRoot` | `String` | Root of the extrinsics trie | | `block.extrinsics` | `Array` | Array of extrinsics in the block | | `justifications` | `Array` | Block justifications (if available) | ## Code Examples ```bash # Get latest block curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": [], "id": 1 }' # Get specific block curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlock", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get latest block const latestHash = await api.rpc.chain.getBlockHash(); const latestBlock = await api.rpc.chain.getBlock(latestHash); console.log('Latest block:', { number: latestBlock.block.header.number.toNumber(), hash: latestHash.toHex(), extrinsicsCount: latestBlock.block.extrinsics.length }); // Get specific block const blockHash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'; const block = await api.rpc.chain.getBlock(blockHash); console.log('Block extrinsics:', block.block.extrinsics.length); await api.disconnect(); ``` ```python def get_block(block_hash=None): url = 'https://api-hydradx.dwellir.com/YOUR_API_KEY' params = [block_hash] if block_hash else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getBlock', 'params': params, 'id': 1 } response = requests.post(url, json=payload) data = response.json() if 'error' in data: raise Exception(f"RPC Error: {data['error']}") return data['result'] # Get latest block latest_block = get_block() block_number = int(latest_block['block']['header']['number'], 16) print(f'Latest block number: {block_number}') # Get specific block specific_block = get_block('0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3') print(f"Extrinsics count: {len(specific_block['block']['extrinsics'])}") ``` ## Related Methods - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number - [`chain_getHeader`](./chain_getHeader) - Get block header only - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get finalized block hash --- ## chain_getBlockHash - Hydration RPC Method # chain_getBlockHash Returns the block hash for a given block number on Hydration. ## Use Cases - **Historical queries** - Convert block numbers to hashes - **Block navigation** - Navigate blockchain history for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Data indexing** - Build block number to hash mappings ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `Number` | No | Block number. If omitted, returns latest block hash | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getBlockHash", "params": [1000000], "id": 1 } ``` ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getBlockHash", "params": [1000000], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get hash for specific block number const blockNumber = 1000000; const blockHash = await api.rpc.chain.getBlockHash(blockNumber); console.log(`Block ${blockNumber} hash:`, blockHash.toHex()); await api.disconnect(); ``` ```python def get_block_hash(block_number=None): url = 'https://api-hydradx.dwellir.com/YOUR_API_KEY' params = [block_number] if block_number is not None else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getBlockHash', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] block_hash = get_block_hash(1000000) print(f'Block hash: {block_hash}') ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get block by hash - [`chain_getHeader`](./chain_getHeader) - Get block header --- ## chain_getFinalizedHead - Hydration RPC Method # chain_getFinalizedHead Returns the hash of the last finalized block on Hydration. ## Use Cases - **Confirmed state** - Query state that cannot be reverted - **Transaction confirmation** - Verify transaction finality for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Safe checkpoints** - Use finalized blocks for critical operations ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getFinalizedHead", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const finalizedHash = await api.rpc.chain.getFinalizedHead(); console.log('Finalized block hash:', finalizedHash.toHex()); // Get finalized block details const block = await api.rpc.chain.getBlock(finalizedHash); console.log('Finalized block number:', block.block.header.number.toNumber()); await api.disconnect(); ``` ```python def get_finalized_head(): url = 'https://api-hydradx.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'chain_getFinalizedHead', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] finalized_hash = get_finalized_head() print(f'Finalized block hash: {finalized_hash}') ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get block by hash - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number --- ## chain_getHeader - Hydration RPC Method # chain_getHeader Returns the block header for a given hash on Hydration. ## Use Cases - **Lightweight queries** - Get header without full block data - **Chain synchronization** - Track block production for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Parent chain navigation** - Follow parentHash links ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash. If omitted, returns latest header | ## Request ```json { "jsonrpc": "2.0", "method": "chain_getHeader", "params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"], "id": 1 } ``` ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "chain_getHeader", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get latest header const header = await api.rpc.chain.getHeader(); console.log('Block number:', header.number.toNumber()); console.log('Parent hash:', header.parentHash.toHex()); await api.disconnect(); ``` ```python def get_header(block_hash=None): url = 'https://api-hydradx.dwellir.com/YOUR_API_KEY' params = [block_hash] if block_hash else [] payload = { 'jsonrpc': '2.0', 'method': 'chain_getHeader', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] header = get_header() print(f"Block number: {int(header['number'], 16)}") ``` ## Related Methods - [`chain_getBlock`](./chain_getBlock) - Get full block with extrinsics - [`chain_getBlockHash`](./chain_getBlockHash) - Get block hash by number --- ## chain_subscribeFinalizedHeads - Hydration RPC Method # chain_subscribeFinalizedHeads Subscribe to receive notifications when blocks are finalized on Hydration. Finalized blocks are guaranteed to never be reverted, making this essential for applications requiring strong consistency. ## Use Cases - **Exchange deposits** - Only credit funds after finalization for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Bridge operations** - Wait for finality before cross-chain transfers - **Critical state changes** - Ensure irreversibility for important transactions ## Parameters This method takes no parameters. ## Returns Returns a subscription ID. The subscription emits `Header` objects for each finalized block: | Field | Type | Description | |-------|------|-------------| | `parentHash` | `Hash` | Parent block hash | | `number` | `BlockNumber` | Block number | | `stateRoot` | `Hash` | State trie root hash | | `extrinsicsRoot` | `Hash` | Extrinsics trie root hash | | `digest` | `Digest` | Block digest with consensus logs | ## Code Examples ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Subscribe to finalized heads const unsubscribe = await api.rpc.chain.subscribeFinalizedHeads((header) => { console.log(`Finalized block #${header.number}`); console.log(` Hash: ${header.hash.toHex()}`); // Safe to consider this block permanent processConfirmedBlock(header); }); // Later: unsubscribe() ``` ```python async def subscribe_finalized(): uri = 'wss://api-hydradx.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'chain_subscribeFinalizedHeads', 'params': [], 'id': 1 })) response = json.loads(await ws.recv()) sub_id = response['result'] print(f'Subscribed to finalized heads: {sub_id}') while True: message = json.loads(await ws.recv()) if 'params' in message: header = message['params']['result'] block_num = int(header['number'], 16) print(f"Finalized: #{block_num}") asyncio.run(subscribe_finalized()) ``` ## Finality Lag Finalized blocks typically lag behind the best block by a few blocks due to GRANDPA consensus requirements. This is normal and ensures Byzantine fault tolerance. ## Related Methods - [`chain_subscribeNewHeads`](./chain_subscribeNewHeads) - Subscribe to all new blocks (not just finalized) - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get current finalized block hash - [`grandpa_roundState`](./grandpa_roundState) - Monitor GRANDPA consensus progress --- ## chain_subscribeNewHeads - Hydration RPC Method # chain_subscribeNewHeads Subscribe to receive notifications when new block headers are produced on Hydration. This WebSocket subscription provides real-time updates for each new block. ## Use Cases - **Block monitoring** - Track new blocks in real-time for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Event indexing** - Trigger processing when new blocks arrive - **Chain synchronization** - Keep external systems in sync with the chain ## Parameters This method takes no parameters. ## Returns Returns a subscription ID. The subscription emits `Header` objects for each new block: | Field | Type | Description | |-------|------|-------------| | `parentHash` | `Hash` | Parent block hash | | `number` | `BlockNumber` | Block number | | `stateRoot` | `Hash` | State trie root hash | | `extrinsicsRoot` | `Hash` | Extrinsics trie root hash | | `digest` | `Digest` | Block digest with consensus logs | ## Code Examples ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Subscribe to new heads const unsubscribe = await api.rpc.chain.subscribeNewHeads((header) => { console.log(`New block #${header.number}`); console.log(` Hash: ${header.hash.toHex()}`); console.log(` Parent: ${header.parentHash.toHex()}`); console.log(` State root: ${header.stateRoot.toHex()}`); }); // Later: unsubscribe() ``` ```python async def subscribe_new_heads(): uri = 'wss://api-hydradx.dwellir.com/YOUR_API_KEY' async with websockets.connect(uri) as ws: # Subscribe to new heads await ws.send(json.dumps({ 'jsonrpc': '2.0', 'method': 'chain_subscribeNewHeads', 'params': [], 'id': 1 })) # Get subscription ID response = json.loads(await ws.recv()) sub_id = response['result'] print(f'Subscribed with ID: {sub_id}') # Listen for new headers while True: message = json.loads(await ws.recv()) if 'params' in message: header = message['params']['result'] print(f"Block #{int(header['number'], 16)}") print(f" Hash: {header['parentHash']}") asyncio.run(subscribe_new_heads()) ``` ## Subscription vs Polling | Approach | Latency | Resource Usage | Use Case | |----------|---------|----------------|----------| | `subscribeNewHeads` | Immediate | Low (push-based) | Real-time monitoring | | Polling `getHeader` | Block time + poll interval | Higher (repeated requests) | Simple integrations | ## Related Methods - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks only - [`chain_getHeader`](./chain_getHeader) - Get a specific block header - [`chain_getBlock`](./chain_getBlock) - Get full block with extrinsics --- ## grandpa_roundState - Hydration RPC Method # grandpa_roundState Returns the state of the current GRANDPA finality round on Hydration. GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) is the finality gadget used by Substrate chains. ## Use Cases - **Finality monitoring** - Track consensus progress for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Validator analysis** - Monitor prevote/precommit participation - **Chain health checks** - Detect finality delays or stalls ## Parameters This method takes no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `setId` | `u64` | Current authority set ID | | `best` | `RoundState` | Best round state | | `background` | `Vec` | Background rounds | ### RoundState Structure | Field | Type | Description | |-------|------|-------------| | `round` | `u64` | Round number | | `totalWeight` | `u64` | Total validator weight | | `thresholdWeight` | `u64` | Weight needed for supermajority | | `prevotes` | `Prevotes` | Prevote information | | `precommits` | `Precommits` | Precommit information | ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "grandpa_roundState", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const roundState = await api.rpc.grandpa.roundState(); console.log('Set ID:', roundState.setId.toString()); console.log('Best round:', roundState.best.round.toString()); console.log('Total weight:', roundState.best.totalWeight.toString()); console.log('Threshold:', roundState.best.thresholdWeight.toString()); await api.disconnect(); ``` ```python url = 'https://api-hydradx.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'grandpa_roundState', 'params': [], 'id': 1 } response = requests.post(url, json=payload) result = response.json()['result'] print(f"Set ID: {result['setId']}") print(f"Round: {result['best']['round']}") print(f"Total weight: {result['best']['totalWeight']}") ``` ## Understanding GRANDPA Rounds 1. **Prevote phase** - Validators vote on best block they've seen 2. **Precommit phase** - Validators commit to finalize if supermajority prevoted 3. **Finalization** - Block is finalized when 2/3+ weight precommits ## Related Methods - [`chain_subscribeFinalizedHeads`](./chain_subscribeFinalizedHeads) - Subscribe to finalized blocks - [`chain_getFinalizedHead`](./chain_getFinalizedHead) - Get current finalized hash - [`beefy_getFinalizedHead`](./beefy_getFinalizedHead) - BEEFY finality (if enabled) --- ## Hydration Liquidity Parachain RPC Guide ## Why Build on Hydration? Hydration powers Polkadot's unified liquidity layer, offering deep cross-chain markets through a single omnipool runtime. Teams choose Hydration because it provides: ### 🌊 **Unified Liquidity Router** - Route any XCM-enabled asset through the omnipool without fragmented pairs - Single-sided provisioning with dynamic fee curves tuned for stable markets - Built-in MEV protection via adaptive liquidity routing ### 🔁 **Native Cross-Chain Execution** - Parachain-level integrations with fast finality on the Polkadot Relay Chain - Out-of-the-box XCM channels to leading parachains for trustless settlement - Seamless asset teleportation between Hydration and Kusama's Basilisk network ### 🛠️ **Developer-First Tooling** - Full Substrate JSON-RPC coverage with archive snapshots for historical queries - Rich analytics via Hydration Subscan and on-chain telemetry feeds - Reusable SDK patterns across JavaScript, Rust, and Python ecosystems ## Quick Start with Hydration Connect to Hydration mainnet or Basilisk testnet in seconds using Dwellir-managed infrastructure. :::info Basilisk Test Environment Basilisk mirrors Hydration's runtime for staging releases on Kusama. Use the Basilisk endpoints for pre-production load tests and fee estimation before promoting to Hydration mainnet. ::: ### Installation & Setup ```bash curl https://api-hydration.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "chain_getHeader", "params": [] }' ``` **Expected output (2025-10-01):** ```json { "jsonrpc": "2.0", "result": { "number": "0x904ae4", "hash": "0xd2f7f582eb7170b1a6382641a2ad9625cd46cb292fa0a8a1fc6f2bb6e1ed6b4d", "parentHash": "0x2f58fc2a2d7024520d2062142c4d7788146101d0736c7c952866adb17bb25483" }, "id": 1 } ``` ```typescript async function main() { const provider = new WsProvider('wss://api-hydration.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const [chain, nodeName, version, runtime] = await Promise.all([ api.rpc.system.chain(), api.rpc.system.name(), api.rpc.system.version(), api.rpc.state.getRuntimeVersion() ]); console.log(`Connected to ${chain} via ${nodeName} v${version}`); console.log(`Runtime specVersion=${runtime.specVersion.toString()}, transactionVersion=${runtime.transactionVersion}`); const header = await api.rpc.chain.getHeader(); console.log(`Latest head #${header.number} (${header.hash.toHex()})`); await api.disconnect(); } main().catch(console.error); ``` ```rust use subxt::{config::substrate::SubstrateConfig, OnlineClient}; #[tokio::main] async fn main() -> Result<(), Box> { let api = OnlineClient::::from_url( "wss://api-hydration.n.dwellir.com/YOUR_API_KEY" ).await?; let block_hash = api.rpc().block_hash(None).await?.expect("block hash"); let header = api.rpc().header(Some(block_hash)).await?.expect("header"); println!("Finalized block #{}", header.number); println!("State root {}", header.state_root); Ok(()) } ``` ```python from substrateinterface import SubstrateInterface substrate = SubstrateInterface( url="wss://api-hydration.n.dwellir.com/YOUR_API_KEY", type_registry_preset="substrate-node-template" ) chain = substrate.get_chain_head() print("Latest finalized head:", chain) runtime = substrate.get_runtime_version() print("specVersion:", runtime['specVersion'], "transactionVersion:", runtime['transactionVersion']) account = substrate.query( module='System', storage_function='Account', params=['5FUNjmP7L2nA9dZ1VnoqeY3SFqHZ3MQNrZjSxFv6YWza7yeb'] ) print("Account free balance:", account.value['data']['free']) ``` ## Network Information | Parameter | Hydration Mainnet | Basilisk Testnet | |-----------|-------------------|------------------| | **Relay Chain** | Polkadot | Kusama | | **Parachain ID** | 2034 | 2090 | | **Genesis Hash** | `0xafdc188f45c71dacbaa0b62e16a91f726c7b8699a9748cdf715459de6b7f366d` | `0xa85cfb9b9fd4d622a5b28289a02347af987d8f73fa3108450e2b4a11c1ce5755` | | **Runtime (2025-10-01)** | specVersion `347`, transactionVersion `1` | specVersion `127`, transactionVersion `1` | | **Unit Symbol** | HDX | BSX | | **Decimals** | 12 | 12 | | **SS58 Prefix** | 63 | 10041 | | **Explorer** | hydration.subscan.io | basilisk.subscan.io | Additional properties: - Average block time: 6 seconds with GRANDPA finality - Native liquidity pools: omnipool, LRNA staking, and routing pallets ## Available JSON-RPC Methods Hydration exposes the full Substrate RPC surface for core operations, staking, governance, and liquidity tooling. The tables below point to the dedicated reference pages for each namespace. ### Core Method Groups | Group | Purpose | Key Methods | |-------|---------|-------------| | `system_*` | Node health, networking, chain metadata | [`system_health`](/hydration/system_health), [`system_version`](/hydration/system_version), [`system_properties`](/hydration/system_properties) | | `chain_*` | Blocks, headers, finality tracking | [`chain_getHeader`](/hydration/chain_getHeader), [`chain_getBlock`](/hydration/chain_getBlock), [`chain_subscribeNewHeads`](/hydration/chain_subscribeNewHeads) | | `state_*` | Storage queries, metadata, proofs | [`state_getStorage`](/hydration/state_getStorage), [`state_getKeys`](/hydration/state_getKeys), [`state_getKeysPaged`](/hydration/state_getKeysPaged), [`state_getRuntimeVersion`](/hydration/state_getRuntimeVersion) | | `author_*` | Extrinsic submission pipeline | [`author_submitExtrinsic`](/hydration/author_submitExtrinsic), [`author_pendingExtrinsics`](/hydration/author_pendingExtrinsics) | | `grandpa_*` | Finality gadget insights | [`grandpa_roundState`](/hydration/grandpa_roundState) | | `rpc_methods` | Discover supported RPC namespaces | [`rpc_methods`](/hydration/rpc_methods) | ### Hydration runtime helpers | Helper | Purpose | Key Methods | |--------|---------|-------------| | `state_call` | Invoke Hydration's runtime APIs for omnipool pricing, router insights, and other advanced analytics | [`state_call`](/hydration/state_call) | ## Common Integration Patterns ### Real-Time Block Streaming ```typescript const provider = new WsProvider('wss://api-hydration.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); api.rpc.chain.subscribeNewHeads((header) => { console.log(`New Hydration block #${header.number.toString()} (${header.hash.toHex()})`); }); ``` ### Query Treasury Balances via Raw Storage ```bash curl https://api-hydration.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 42, "method": "state_getStorage", "params": [ "0x26aa394eea5630e07c48ae0c9558cef7b6a7c9a35a95a160cb4cad330558dfa56d6f646c755b98a7afd0913860592153322b957be394a0619f20b32679ac1014" ] }' ``` The key above targets `System.Account` for `5EYCAe5jiUusQ3yAkVAP1YF81oXasuAHt2KG8Xjc433Zbx8A` (Hydration treasury). Decode the SCALE response to obtain the 6,952,142,503,371.701702601733 HDX free balance observed on 2025-10-01. ### Batch Weight and Fee Simulation ```typescript const api = await ApiPromise.create({ provider: new WsProvider('wss://api-hydration.n.dwellir.com/YOUR_API_KEY') }); const tx = api.tx.omnipool.sell( assetInId, assetOutId, amountIn, minimumReceived ); const info = await api.rpc.payment.queryInfo(tx.toHex()); console.log(`Estimated fee: ${info.partialFee.toHuman()}`); console.log(`Weight: ${info.weight.toString()} refTime`); ``` ## Performance Best Practices - Prefer WebSocket endpoints for subscriptions (`chain_subscribeNewHeads`, `grandpa_subscribeJustifications`). - Cache runtime metadata and type registries keyed by `specVersion` (`347` as of 2025-10-01) to avoid repeated handshakes. - Use `state_getKeysPaged` with `pageSize <= 1000` when scanning omnipool storage to prevent heavy RPC loads. - Rate-limit bulk extrinsic submissions and enable exponential backoff on `author_submitExtrinsic` errors. - Pin queries to finalized block hashes whenever you need deterministic historical data. ## Troubleshooting | Symptom | Likely Cause | Resolution | |---------|--------------|------------| | `API key does not exist` | Missing or mis-typed Dwellir key | Re-issue credentials via the Dwellir dashboard and update endpoint URLs | | `1010: Invalid Transaction` | Runtime version drift or outdated nonce | Re-fetch metadata, synchronize account nonce, and rebuild the payload | | Null `state_getStorage` response | Storage key mismatch | Recompute the key with `blake2_128_concat` of the SS58-decoded AccountId | | WebSocket disconnects after idle | Inactive ping/pong | Enable keep-alive heartbeats every 20 seconds and auto-retry with jitter | ## FAQs **Does Hydration support archive queries?** Yes. Dwellir retains full historical state so you can request old block hashes, query omnipool states, and reconstruct trades for compliance. **What SS58 prefix should wallets use?** Hydration uses prefix `63`. Basilisk uses `10041`. Ensure address derivation matches the target environment. **How do I estimate swap slippage programmatically?** Fetch omnipool reserves via `state_call` (custom RPC `OmnipoolApi_quotePrice`) and pair it with `payment_queryInfo` estimates to account for weight-based fees. ## Smoke Tests Run these checks before deploying to production: 1. **Node health** ```bash curl https://api-hydration.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"system_health","params":[]}' ``` Expect peers ≥ 8 and `isSyncing: false`. 2. **Latest header** ```bash curl https://api-hydration.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":2,"method":"chain_getHeader","params":[]}' ``` Confirm block numbers advance roughly every 6 seconds. 3. **Account snapshot** ```bash curl https://api-hydration.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":3,"method":"state_getStorage","params":["0x26aa394eea5630e07c48ae0c9558cef7b6a7c9a35a95a160cb4cad330558dfa56d6f646c755b98a7afd0913860592153322b957be394a0619f20b32679ac1014"]}' ``` Decode the SCALE payload and verify balances. ## Migration Guide (Polkadot → Hydration) - **Update endpoints:** Replace legacy Polkadot URLs with `https://api-hydration.n.dwellir.com/YOUR_API_KEY` or the Basilisk staging endpoint. - **Adjust address encoding:** Switch wallet and service configurations to SS58 prefix `63`. Existing Polkadot addresses (prefix `0`) must be re-derived. - **Refresh metadata:** Download the latest metadata (`specVersion 347`) and update custom type bundles for omnipool-related pallets. - **Re-evaluate fees:** Run `payment_queryInfo` against Hydration extrinsics—weights differ from Polkadot due to liquidity logic. - **Review pallet availability:** Hydration includes omnipool, router, and incentive pallets not present on Polkadot; ensure you check `rpc_methods` for the namespaces you rely on. ## Resources & Tools - [Hydration network status dashboard](https://hydration.subscan.io/network) — uptime, block times, and validator health - [Hydration node releases](https://github.com/galacticcouncil/HydraDX-node/releases) — runtime changelogs and spec version history - [Polkadot.js Apps explorer](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fapi-hydration.n.dwellir.com%2FYOUR_API_KEY#/explorer) — browser-based console - [Runtime configuration JSON](https://raw.githubusercontent.com/galacticcouncil/HydraDX-node/master/node/res/hydradx.json) — chain specification for Hydration - [Dwellir Dashboard](https://dashboard.dwellir.com/register) — Get your API key Ready to launch? Deploy with Hydration's omnipool liquidity and monitor production traffic through Dwellir's analytics. --- ## payment_queryFeeDetails - Hydration RPC Method # payment_queryFeeDetails Returns a detailed breakdown of fees for a given extrinsic on Hydration. Unlike `payment_queryInfo` which returns the total fee, this method separates the fee into its component parts. ## Use Cases - **Fee analysis** - Understand fee composition for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Optimization** - Identify which fee component dominates costs - **Debugging** - Diagnose unexpected fee amounts ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `Bytes` | Yes | SCALE-encoded extrinsic (signed or unsigned) | | `blockHash` | `Hash` | No | Block hash for fee calculation context | ## Returns | Field | Type | Description | |-------|------|-------------| | `inclusionFee` | `Option` | Fee details (null for unsigned extrinsics) | ### InclusionFee Structure | Field | Type | Description | |-------|------|-------------| | `baseFee` | `Balance` | Fixed base fee per extrinsic | | `lenFee` | `Balance` | Fee based on encoded extrinsic length | | `adjustedWeightFee` | `Balance` | Fee based on execution weight | ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "payment_queryFeeDetails", "params": ["0x...encodedExtrinsic"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Create a sample transfer const tx = api.tx.balances.transferKeepAlive( '5FHneW46xGXgs5mUiveU4sbTyGBzmstUspZC92UhjJM694ty', 1000000000000n ); // Get fee details const feeDetails = await api.rpc.payment.queryFeeDetails(tx.toHex()); if (feeDetails.inclusionFee.isSome) { const fee = feeDetails.inclusionFee.unwrap(); console.log('Base fee:', fee.baseFee.toString()); console.log('Length fee:', fee.lenFee.toString()); console.log('Weight fee:', fee.adjustedWeightFee.toString()); } await api.disconnect(); ``` ```python url = 'https://api-hydradx.dwellir.com/YOUR_API_KEY' # Replace with actual encoded extrinsic encoded_extrinsic = '0x...' payload = { 'jsonrpc': '2.0', 'method': 'payment_queryFeeDetails', 'params': [encoded_extrinsic], 'id': 1 } response = requests.post(url, json=payload) result = response.json()['result'] if result['inclusionFee']: fee = result['inclusionFee'] print(f"Base fee: {fee['baseFee']}") print(f"Length fee: {fee['lenFee']}") print(f"Weight fee: {fee['adjustedWeightFee']}") ``` ## Fee Components Explained | Component | Calculation | Optimization | |-----------|-------------|--------------| | **Base fee** | Fixed per extrinsic | Batch calls to share base fee | | **Length fee** | `length * lengthToFee` | Minimize call data size | | **Weight fee** | `weight * weightToFee` | Choose efficient operations | ## Related Methods - [`payment_queryInfo`](./payment_queryInfo) - Get total fee estimate - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction - [`state_call`](./state_call) - Call TransactionPaymentApi directly --- ## payment_queryInfo - Hydration RPC Method # payment_queryInfo Estimates the fee for an extrinsic on Hydration. ## Use Cases - **Fee estimation** - Calculate transaction costs before sending - **UI display** - Show fees to users for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Transaction planning** - Ensure sufficient funds ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `extrinsic` | `String` | Yes | Hex-encoded unsigned extrinsic | | `blockHash` | `String` | No | Block hash for fee calculation | ## Request ```json { "jsonrpc": "2.0", "method": "payment_queryInfo", "params": ["0x..."], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `weight` | `Object` | Transaction weight | | `class` | `String` | Dispatch class | | `partialFee` | `String` | Estimated fee | ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "payment_queryInfo", "params": ["0x..."], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Create transfer (unsigned for estimation) const transfer = api.tx.balances.transfer('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', 1000000000000); const info = await transfer.paymentInfo('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'); console.log('Partial fee:', info.partialFee.toHuman()); await api.disconnect(); ``` ## Related Methods - [`author_submitExtrinsic`](./author_submitExtrinsic) - Submit transaction --- ## rpc_methods - Hydration RPC Method # rpc_methods Returns a list of all RPC methods available on Hydration. ## Use Cases - **API discovery** - List all available methods - **Compatibility checking** - Verify method availability for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Documentation** - Auto-generate method lists ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "rpc_methods", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const methods = await api.rpc.rpc.methods(); console.log('Available methods:', methods.methods.length); await api.disconnect(); ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## state_call - Hydration RPC Method # state_call Calls a runtime API method on Hydration. ## Use Cases - **Runtime computations** - Execute runtime logic without transactions - **Account queries** - Use AccountNonceApi for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Fee estimation** - Use TransactionPaymentApi ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `method` | `String` | Yes | Runtime API method name | | `data` | `String` | Yes | SCALE-encoded call data | | `blockHash` | `String` | No | Block hash for historical call | ## Request ```json { "jsonrpc": "2.0", "method": "state_call", "params": ["AccountNonceApi_account_nonce", "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"], "id": 1 } ``` ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_call", "params": ["AccountNonceApi_account_nonce", "0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d"], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get account nonce via runtime API const account = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const result = await api.call.accountNonceApi.accountNonce(account); console.log('Account nonce:', result.toNumber()); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Query storage - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## state_getKeys - JSON-RPC Method(Hydration) ## Description Returns storage keys that match a given prefix. This JSON-RPC method is useful for discovering all storage entries under a specific module or querying multiple related storage items. Be cautious with broad prefixes as they may return large result sets. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `prefix` | string | Yes | Hex-encoded storage key prefix to match | | `blockHash` | string | No | Block hash to query at. If omitted, uses the latest block | ## Returns | Field | Type | Description | |-------|------|-------------| | `result` | array | Array of hex-encoded storage keys matching the prefix | ## Request Example ```json { "jsonrpc": "2.0", "method": "state_getKeys", "params": [ "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9" ], "id": 1 } ``` ## Response Example ```json { "jsonrpc": "2.0", "result": [ "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9de1e86a9a8c739864cf3cc5ec2bea59fd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d", "0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da94f9aea1afa791265fae359272badc1cf8eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a48" ], "id": 1 } ``` ## Code Examples ```python from substrateinterface import SubstrateInterface def get_storage_keys(prefix, block_hash=None): url = "https://api-hydration.n.dwellir.com/YOUR_API_KEY" headers = { "Content-Type": "application/json" } params = [prefix, block_hash] if block_hash else [prefix] payload = { "jsonrpc": "2.0", "method": "state_getKeys", "params": params, "id": 1 } response = requests.post(url, headers=headers, data=json.dumps(payload)) return response.json()["result"] # Example: Get all validator preferences keys def get_validator_keys(): # Staking.Validators storage prefix prefix = "0x5f3e4907f716ac89b6347d15ececedca9320c2dc4f5d7af5b320b04e2d1a3ff3" keys = get_storage_keys(prefix) print(f"Found {len(keys)} validator preference entries") for key in keys: # Extract validator account from key validator_account = key[-64:] print(f"Validator: 0x{validator_account}") return keys # Example: Query all keys under a module def get_module_keys(module_prefix): keys = get_storage_keys(module_prefix) # Group keys by storage item storage_items = {} for key in keys: # Storage keys typically have a fixed prefix per item item_prefix = key[:66] # First 33 bytes (66 hex chars) if item_prefix not in storage_items: storage_items[item_prefix] = [] storage_items[item_prefix].append(key) return storage_items ``` ```javascript const getStorageKeys = async (prefix, blockHash = null) => { const params = blockHash ? [prefix, blockHash] : [prefix]; const response = await fetch('https://api-hydration.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'state_getKeys', params: params, id: 1 }) }); const data = await response.json(); return data.result; }; // Get all account keys (System.Account storage) const accountPrefix = '0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9'; const accountKeys = await getStorageKeys(accountPrefix); console.log(`Found ${accountKeys.length} accounts`); // Extract account addresses from keys accountKeys.forEach(key => { // The account address is the last 32 bytes of the key const addressHex = key.slice(-64); console.log('Account key:', key); console.log('Address portion:', addressHex); }); ``` ```typescript async function queryStorageKeys() { const provider = new WsProvider('wss://api-hydration.n.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Method 1: Using high-level API to get keys const accountKeys = await api.query.system.account.keys(); console.log('Account addresses:', accountKeys.map(k => k.toHuman())); // Method 2: Using low-level RPC for custom prefixes const prefix = api.query.system.account.keyPrefix(); const keys = await api.rpc.state.getKeys(prefix); console.log(`Found ${keys.length} account storage keys`); // Method 3: Get keys for a specific map entry const validatorKeys = await api.query.staking.validators.keys(); console.log('Active validators:', validatorKeys.length); // Process keys to extract data for (const key of keys) { // Decode the storage key const keyHex = key.toHex(); console.log('Storage key:', keyHex); // Get the value for this key const value = await api.rpc.state.getStorage(key); console.log('Storage value:', value.toHex()); } await api.disconnect(); } // Advanced: Query keys with pagination async function getKeysPagedExample() { const api = await ApiPromise.create({ provider: new WsProvider('wss://api-hydration.n.dwellir.com/YOUR_API_KEY') }); const prefix = api.query.system.account.keyPrefix(); const pageSize = 100; let startKey = prefix; let allKeys = []; while (true) { // Note: state_getKeysPaged is used for pagination const keys = await api.rpc.state.getKeysPaged(prefix, pageSize, startKey); if (keys.length === 0) break; allKeys = allKeys.concat(keys); startKey = keys[keys.length - 1]; console.log(`Fetched ${keys.length} keys, total: ${allKeys.length}`); if (keys.length < pageSize) break; } console.log(`Total keys found: ${allKeys.length}`); await api.disconnect(); } ``` ## Common Storage Prefixes | Module | Storage Item | Prefix (example) | |--------|--------------|------------------| | System | Account | `0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9` | | Balances | TotalIssuance | `0xc2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80` | | Staking | Validators | `0x5f3e4907f716ac89b6347d15ececedca9320c2dc4f5d7af5b320b04e2d1a3ff3` | | Session | NextKeys | `0xcec5070d609dd3497f72bde07fc96ba0e0cdd062e6eaf24295ad4ccfc41d4609` | ## Batch Query Example ```javascript // Efficiently query multiple storage values async function batchQueryStorage(api, keys) { // Get all values in a single call const values = await api.rpc.state.queryStorageAt(keys); const results = {}; keys.forEach((key, index) => { results[key.toString()] = values[index]; }); return results; } // Example usage const keys = await getStorageKeys(accountPrefix); const values = await batchQueryStorage(api, keys.slice(0, 10)); console.log('Batch query results:', values); ``` ## Use Cases 1. **Account Discovery**: Find all accounts with balances 2. **Validator Enumeration**: List all validators in the network 3. **Storage Analysis**: Analyze storage usage by module 4. **Migration Scripts**: Iterate over storage for upgrades 5. **Indexing**: Build indexes of on-chain data ## Notes - Large prefixes may return many keys - use pagination when available - Keys are returned in lexicographical order - The prefix must be hex-encoded - Consider using `state_getKeysPaged` for large datasets - Storage keys include both the storage prefix and the key data ## Related Methods - [`state_getKeysPaged`](/hydration/state_getKeysPaged) - Get keys with pagination - [`state_getStorage`](/hydration/state_getStorage) - Get storage value - [`state_getMetadata`](/hydration/state_getMetadata) - Get metadata to decode keys --- ## state_getKeysPaged - Hydration RPC Method # state_getKeysPaged Returns storage keys with pagination on Hydration. ## Use Cases - **Storage iteration** - Enumerate storage map entries - **Data export** - Bulk export chain data for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Account enumeration** - List all accounts ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `prefix` | `String` | Yes | Storage key prefix | | `count` | `Number` | Yes | Maximum keys to return | | `startKey` | `String` | No | Key to start after | | `blockHash` | `String` | No | Block hash for historical query | ## Request ```json { "jsonrpc": "2.0", "method": "state_getKeysPaged", "params": ["0x...", 100], "id": 1 } ``` ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getKeysPaged", "params": ["0x26aa394eea5630e07c48ae0c9558cef7", 100], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get all accounts (paginated) const keys = await api.rpc.state.getKeysPaged( api.query.system.account.keyPrefix(), 100 ); console.log('Found accounts:', keys.length); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Get storage value - [`state_queryStorageAt`](./state_queryStorageAt) - Batch storage query --- ## state_getMetadata - Hydration RPC Method # state_getMetadata Returns the runtime metadata on Hydration. ## Use Cases - **Runtime introspection** - Discover available pallets and calls - **Extrinsic building** - Get call and type information for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Storage key generation** - Build storage keys from metadata - **Client generation** - Auto-generate typed APIs ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash for historical metadata | ## Request ```json { "jsonrpc": "2.0", "method": "state_getMetadata", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getMetadata", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Get runtime metadata const metadata = await api.rpc.state.getMetadata(); // List available pallets const pallets = metadata.asLatest.pallets.map(p => p.name.toString()); console.log('Available pallets:', pallets); // Get specific pallet info const systemPallet = metadata.asLatest.pallets.find(p => p.name.toString() === 'System'); console.log('System pallet calls:', systemPallet.calls.isSome ? 'Available' : 'None'); await api.disconnect(); ``` ```python def get_metadata(): url = 'https://api-hydradx.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'state_getMetadata', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] metadata_hex = get_metadata() print(f'Metadata length: {len(metadata_hex)} bytes') ``` ## Related Methods - [`state_getRuntimeVersion`](./state_getRuntimeVersion) - Get runtime version - [`state_getStorage`](./state_getStorage) - Query storage --- ## state_getRuntimeVersion - Hydration RPC Method # state_getRuntimeVersion Returns the runtime version on Hydration. ## Use Cases - **Version checking** - Verify runtime compatibility - **Upgrade detection** - Monitor for runtime upgrades on single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Client compatibility** - Ensure API compatibility ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `String` | No | Block hash for historical version | ## Request ```json { "jsonrpc": "2.0", "method": "state_getRuntimeVersion", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getRuntimeVersion", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const version = await api.rpc.state.getRuntimeVersion(); console.log('Spec name:', version.specName.toString()); console.log('Spec version:', version.specVersion.toNumber()); console.log('Impl version:', version.implVersion.toNumber()); await api.disconnect(); ``` ```python def get_runtime_version(): url = 'https://api-hydradx.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'state_getRuntimeVersion', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] version = get_runtime_version() print(f"Spec: {version['specName']} v{version['specVersion']}") ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata - [`system_version`](./system_version) - Get node version --- ## state_getStorage - Hydration RPC Method # state_getStorage Returns a storage entry at a specific key on Hydration. > **Why Hydration?** Build on Polkadot's leading DEX with $200M+ TVL, Omnipool AMM, and native HOLLAR stablecoin with Omnipool with reduced slippage, permissioned listings, 3M DOT DAO allocation, and 200%+ APR farm yields. ## Use Cases - **State queries** - Read on-chain storage values - **Account balances** - Query account data for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Pallet storage** - Access runtime storage items - **Historical state** - Query state at specific blocks ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `key` | `String` | Yes | Storage key (hex-encoded) | | `blockHash` | `String` | No | Block hash for historical query | ## Request ```json { "jsonrpc": "2.0", "method": "state_getStorage", "params": [""], "id": 1 } ``` ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_getStorage", "params": [""], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query account balance const account = '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'; const accountInfo = await api.query.system.account(account); console.log('Free balance:', accountInfo.data.free.toString()); // Query at specific block const blockHash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'; const historicalBalance = await api.query.system.account.at(blockHash, account); console.log('Historical balance:', historicalBalance.data.free.toString()); await api.disconnect(); ``` ```python def get_storage(key, block_hash=None): url = 'https://api-hydradx.dwellir.com/YOUR_API_KEY' params = [key] if block_hash is None else [key, block_hash] payload = { 'jsonrpc': '2.0', 'method': 'state_getStorage', 'params': params, 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] # Query :code storage (runtime wasm) storage_key = '' value = get_storage(storage_key) print(f'Storage value: {value[:66]}...' if value else 'None') ``` ## Related Methods - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata - [`state_getKeysPaged`](./state_getKeysPaged) - Enumerate storage keys --- ## state_queryStorageAt - Hydration RPC Method # state_queryStorageAt Query multiple storage keys at a specific block on Hydration. ## Use Cases - **Batch queries** - Efficiently query multiple storage items - **Snapshot state** - Get consistent multi-key state for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Data analysis** - Compare storage across blocks ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `keys` | `Array` | Yes | Array of storage keys | | `blockHash` | `String` | No | Block hash for query | ## Request ```json { "jsonrpc": "2.0", "method": "state_queryStorageAt", "params": [[""]], "id": 1 } ``` ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "state_queryStorageAt", "params": [[""]], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); // Query multiple accounts at once const accounts = ['5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY']; const entries = await api.query.system.account.multi(accounts); entries.forEach((info, idx) => { console.log(`Account ${idx}: ${info.data.free.toString()}`); }); await api.disconnect(); ``` ## Related Methods - [`state_getStorage`](./state_getStorage) - Single storage query - [`state_getKeysPaged`](./state_getKeysPaged) - Enumerate keys --- ## system_chain - Hydration RPC Method # system_chain Returns the chain name on Hydration. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_chain", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const chain = await api.rpc.system.chain(); console.log('Chain:', chain.toString()); await api.disconnect(); ``` ## Related Methods - [`system_name`](./system_name) - Get node implementation name - [`system_version`](./system_version) - Get node version --- ## system_health - Hydration RPC Method # system_health Returns the health status of the Hydration node. ## Use Cases - **Health checks** - Monitor node availability - **Load balancing** - Route traffic based on health for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **Sync status** - Verify node is synced ## Parameters This method accepts no parameters. ## Returns | Field | Type | Description | |-------|------|-------------| | `peers` | `Number` | Connected peer count | | `isSyncing` | `Boolean` | Whether node is syncing | | `shouldHavePeers` | `Boolean` | Whether node should have peers | ## Request ```json { "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_health", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const health = await api.rpc.system.health(); console.log('Peers:', health.peers.toNumber()); console.log('Is syncing:', health.isSyncing.isTrue); await api.disconnect(); ``` ```python def get_health(): url = 'https://api-hydradx.dwellir.com/YOUR_API_KEY' payload = { 'jsonrpc': '2.0', 'method': 'system_health', 'params': [], 'id': 1 } response = requests.post(url, json=payload) return response.json()['result'] health = get_health() print(f"Peers: {health['peers']}") print(f"Syncing: {health['isSyncing']}") ``` ## Related Methods - [`system_version`](./system_version) - Get node version - [`system_chain`](./system_chain) - Get chain name --- ## system_name - Hydration RPC Method # system_name Returns the node implementation name on Hydration. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_name", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_name", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const name = await api.rpc.system.name(); console.log('Node name:', name.toString()); await api.disconnect(); ``` ## Related Methods - [`system_version`](./system_version) - Get node version - [`system_chain`](./system_chain) - Get chain name --- ## system_properties - Hydration RPC Method # system_properties Returns chain properties including token symbol and decimals on Hydration. ## Use Cases - **Token formatting** - Get decimals and symbol for single-sided liquidity provision, cross-chain trading (SOL, KSM, tBTC), and HOLLAR decentralized stablecoin - **UI configuration** - Configure wallets and dApps - **Address formatting** - Get SS58 prefix ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_properties", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_properties", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const props = await api.rpc.system.properties(); console.log('Token symbol:', props.tokenSymbol.toString()); console.log('Token decimals:', props.tokenDecimals.toString()); console.log('SS58 prefix:', props.ss58Format.toString()); await api.disconnect(); ``` ## Related Methods - [`system_chain`](./system_chain) - Get chain name - [`state_getMetadata`](./state_getMetadata) - Get runtime metadata --- ## system_version - Hydration RPC Method # system_version Returns the node implementation version on Hydration. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "system_version", "params": [], "id": 1 } ``` ## Code Examples ```bash curl https://api-hydradx.dwellir.com/YOUR_API_KEY \ -X POST \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "system_version", "params": [], "id": 1 }' ``` ```javascript const provider = new WsProvider('wss://api-hydradx.dwellir.com/YOUR_API_KEY'); const api = await ApiPromise.create({ provider }); const version = await api.rpc.system.version(); console.log('Version:', version.toString()); await api.disconnect(); ``` ## Related Methods - [`system_chain`](./system_chain) - Get chain name - [`state_getRuntimeVersion`](./state_getRuntimeVersion) - Get runtime version --- ## debug_traceBlock - Hyperliquid RPC Method # debug_traceBlock Traces all transactions in a block on Hyperliquid by block RLP. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Analyze transaction execution step-by-step - **Smart contract analysis** - Debug contract interactions - **Security auditing** - Trace internal calls for perpetual futures trading, onchain order books, and institutional-grade derivatives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockRlp` | `DATA` | Yes | RLP-encoded block data | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlock", "params": ["0xf9..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); // Use debug_traceBlockByNumber instead (more practical) const traces = await provider.send('debug_traceBlockByNumber', ['latest', {}]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by block number - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by block hash --- ## debug_traceBlockByHash - Hyperliquid RPC Method # debug_traceBlockByHash Traces all transactions in a block on Hyperliquid by block hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0x749f10b5acfaa7240d49fe6356f8b2a62991aeea630831d13fda8c99d28dd6af", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByHash", "params": ["0x749f10b5acfaa7240d49fe6356f8b2a62991aeea630831d13fda8c99d28dd6af", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0x749f10b5acfaa7240d49fe6356f8b2a62991aeea630831d13fda8c99d28dd6af'; const traces = await provider.send('debug_traceBlockByHash', [blockHash, { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace by number - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceBlockByNumber - Hyperliquid RPC Method # debug_traceBlockByNumber Traces all transactions in a block on Hyperliquid by block number. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceBlockByNumber", "params": ["latest", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const traces = await provider.send('debug_traceBlockByNumber', ['latest', { tracer: 'callTracer' }]); console.log('Transaction traces:', traces.length); ``` ## Related Methods - [`debug_traceBlockByHash`](./debug_traceBlockByHash) - Trace by hash - [`debug_traceTransaction`](./debug_traceTransaction) - Trace single transaction --- ## debug_traceCall - Hyperliquid RPC Method # debug_traceCall Traces a call without creating a transaction on Hyperliquid. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction simulation** - Debug before sending - **Gas analysis** - Analyze gas usage per opcode - **Contract debugging** - Step through execution for perpetual futures trading, onchain order books, and institutional-grade derivatives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `call` | `Object` | Yes | Call object (same as eth_call) | | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number or tag | | `tracerConfig` | `Object` | No | Tracer configuration | ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ { "to": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "data": "0x70a0823100000000000000000000000030e54c9bc205e19d693d53c0b0be92299d4191ea" }, "latest", {} ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceCall", "params": [ {"to": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "data": "0x70a0823100000000000000000000000030e54c9bc205e19d693d53c0b0be92299d4191ea"}, "latest", {"tracer": "callTracer"} ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const trace = await provider.send('debug_traceCall', [ { to: '0x30e54c9bc205e19d693d53c0b0be92299d4191ea', data: '0x70a0823100000000000000000000000030e54c9bc205e19d693d53c0b0be92299d4191ea' }, 'latest', { tracer: 'callTracer' } ]); console.log('Trace:', trace); ``` ## Related Methods - [`eth_call`](./eth_call) - Execute call without trace - [`debug_traceTransaction`](./debug_traceTransaction) - Trace actual transaction --- ## debug_traceTransaction - Hyperliquid RPC Method # debug_traceTransaction Traces a transaction execution on Hyperliquid by transaction hash. :::info Archive Node Required This method requires an archive node. It is not available on full nodes. ::: ## Use Cases - **Transaction debugging** - Understand exactly what happened - **Failure analysis** - Find where and why a transaction reverted - **Gas optimization** - Analyze gas usage for perpetual futures trading, onchain order books, and institutional-grade derivatives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `txHash` | `DATA` | Yes | 32-byte transaction hash | | `tracerConfig` | `Object` | No | Tracer configuration | ## Tracer Options - `{}` - Default opcode tracer (verbose) - `{ tracer: "callTracer" }` - Call tree tracer - `{ tracer: "prestateTracer" }` - Pre-state tracer ## Request ```json { "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614", {"tracer": "callTracer"}], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "debug_traceTransaction", "params": ["0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614", {"tracer": "callTracer"}], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614'; // Call tracer - shows internal calls const callTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'callTracer' } ]); console.log('Type:', callTrace.type); console.log('From:', callTrace.from); console.log('To:', callTrace.to); console.log('Gas used:', parseInt(callTrace.gasUsed, 16)); // Prestate tracer - shows state before execution const prestateTrace = await provider.send('debug_traceTransaction', [ txHash, { tracer: 'prestateTracer' } ]); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614' # Call tracer trace = w3.provider.make_request('debug_traceTransaction', [ tx_hash, {'tracer': 'callTracer'} ]) print(f'Trace type: {trace["result"]["type"]}') print(f'Gas used: {int(trace["result"]["gasUsed"], 16)}') ``` ## Related Methods - [`debug_traceCall`](./debug_traceCall) - Trace without executing - [`debug_traceBlockByNumber`](./debug_traceBlockByNumber) - Trace entire block --- ## eth_accounts - Hyperliquid RPC Method # eth_accounts Returns a list of addresses owned by the client on Hyperliquid. > **Why Hyperliquid?** Build on the dominant perpetuals DEX with 70% market share, $2.7T+ lifetime volume, and $2B TVL with 200K orders/second throughput, zero gas fees, sub-second finality, and fully onchain Central Limit Order Book (CLOB). ## Important Note On public RPC endpoints like Dwellir, `eth_accounts` returns an empty array because the node does not hold any private keys. This method is primarily useful for: - Local development nodes (Ganache, Hardhat, Anvil) - Private nodes with managed accounts - Wallet provider connections (MetaMask injects accounts) ## When to Use This Method `eth_accounts` is relevant for derivatives traders, DeFi protocols, and teams building high-frequency trading applications in specific scenarios: - **Development Testing** — Retrieve test accounts from local nodes - **Wallet Detection** — Check if a wallet provider has connected accounts - **Client Verification** — Confirm node account access capabilities ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `Array` | List of 20-byte account addresses owned by the client | **Return format**: Array of `0x` prefixed hexadecimal addresses (typically empty for public nodes) ## Request ```json { "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 } ``` ## Response ### Successful Response (Public Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [] } ``` ### Successful Response (Local Development Node) ```json { "jsonrpc": "2.0", "id": 1, "result": [ "0x407d73d8a49eeb85d32cf465507dd71d507100c1", "0x85d32cf465507dd71d507100c1407d73d8a49eeb" ] } ``` ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_accounts', params: [], id: 1 }) }); const { result } = await response.json(); console.log('Accounts:', result); // Using ethers.js const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const accounts = await provider.listAccounts(); console.log('Accounts:', accounts); ``` ```python def get_accounts(): response = requests.post( 'https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_accounts', 'params': [], 'id': 1 } ) return response.json()['result'] accounts = get_accounts() print(f'Accounts: {accounts}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) print(f'Accounts: {w3.eth.accounts}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/rpc" ) func main() { client, err := rpc.Dial("https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } var accounts []string err = client.CallContext(context.Background(), &accounts, "eth_accounts") if err != nil { log.Fatal(err) } fmt.Printf("Accounts: %v\n", accounts) } ``` ## Common Use Cases ### 1. Development Environment Detection Check if running against a development node with test accounts: ```javascript async function isDevEnvironment(provider) { const accounts = await provider.listAccounts(); return accounts.length > 0; } const isDev = await isDevEnvironment(provider); if (isDev) { console.log('Development environment detected'); } ``` ### 2. Wallet Connection Check Verify wallet provider has connected accounts: ```javascript async function checkWalletConnection() { if (typeof window.ethereum === 'undefined') { return { connected: false, reason: 'No wallet detected' }; } const accounts = await window.ethereum.request({ method: 'eth_accounts' }); return { connected: accounts.length > 0, accounts: accounts }; } ``` ### 3. Fallback Account Selection Use first available account or request connection: ```javascript async function getActiveAccount() { // Check existing connections let accounts = await window.ethereum.request({ method: 'eth_accounts' }); // Request connection if no accounts if (accounts.length === 0) { accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); } return accounts[0] || null; } ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32601 | Method not found | Node may not support this method | | -32603 | Internal error | Retry with exponential backoff | ```javascript async function safeGetAccounts(provider) { try { const accounts = await provider.listAccounts(); return { success: true, accounts }; } catch (error) { if (error.code === -32601) { console.warn('eth_accounts not supported on this node'); return { success: false, accounts: [], reason: 'unsupported' }; } throw error; } } ``` ## Related Methods - [`eth_requestAccounts`](https://eips.ethereum.org/EIPS/eip-1102) — Request wallet connection (browser wallets) - [`eth_getBalance`](./eth_getBalance) — Get account balance - [`eth_getTransactionCount`](./eth_getTransactionCount) — Get account nonce --- ## eth_blockNumber - Hyperliquid RPC Method # eth_blockNumber Returns the number of the most recent block on Hyperliquid. > **Why Hyperliquid?** Build on the dominant perpetuals DEX with 70% market share, $2.7T+ lifetime volume, and $2B TVL with 200K orders/second throughput, zero gas fees, sub-second finality, and fully onchain Central Limit Order Book (CLOB). ## When to Use This Method `eth_blockNumber` is fundamental for derivatives traders, DeFi protocols, and teams building high-frequency trading applications: - **Syncing Applications** — Keep your dApp in sync with the latest Hyperliquid blockchain state - **Transaction Monitoring** — Verify confirmations by comparing block numbers - **Event Filtering** — Set the correct block range for querying logs on perpetual futures trading, onchain order books, and institutional-grade derivatives - **Health Checks** — Monitor node connectivity and sync status ## Parameters This method accepts no parameters. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | None | - | - | This method takes no parameters | ## Returns | Field | Type | Description | |-------|------|-------------| | result | `QUANTITY` | Hexadecimal string representing the current block number | **Return format**: `0x` prefixed hexadecimal (e.g., `0x5BAD55` = 6,008,149 in decimal) ## Request ```json { "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 } ``` ## Response ### Successful Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5BAD55" } ``` ### Error Response ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error" } } ``` ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_blockNumber", "params": [], "id": 1 }' ``` ```javascript // Using fetch const response = await fetch('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }) }); const { result } = await response.json(); const blockNumber = parseInt(result, 16); console.log('Hyperliquid block:', blockNumber); // Using ethers.js const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const blockNumber = await provider.getBlockNumber(); console.log('Hyperliquid block:', blockNumber); ``` ```python def get_block_number(): response = requests.post( 'https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY', json={ 'jsonrpc': '2.0', 'method': 'eth_blockNumber', 'params': [], 'id': 1 } ) result = response.json()['result'] return int(result, 16) block_number = get_block_number() print(f'Hyperliquid block: {block_number}') # Using web3.py from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) print(f'Hyperliquid block: {w3.eth.block_number}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockNumber, err := client.BlockNumber(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Hyperliquid block: %d\n", blockNumber) } ``` ## Common Use Cases ### 1. Block Confirmation Counter Monitor transaction confirmations on Hyperliquid: ```javascript async function getConfirmations(provider, txHash) { const tx = await provider.getTransaction(txHash); if (!tx || !tx.blockNumber) return 0; const currentBlock = await provider.getBlockNumber(); return currentBlock - tx.blockNumber + 1; } // Wait for specific confirmations async function waitForConfirmations(provider, txHash, confirmations = 6) { let currentConfirmations = 0; while (currentConfirmations < confirmations) { currentConfirmations = await getConfirmations(provider, txHash); console.log(`Confirmations: ${currentConfirmations}/${confirmations}`); await new Promise(r => setTimeout(r, 2000)); } return true; } ``` ### 2. Event Log Filtering Query events from recent blocks on Hyperliquid: ```javascript async function getRecentEvents(provider, contract, eventName, blockRange = 100) { const currentBlock = await provider.getBlockNumber(); const fromBlock = currentBlock - blockRange; const filter = contract.filters[eventName](); const events = await contract.queryFilter(filter, fromBlock, currentBlock); return events; } ``` ### 3. Node Health Monitoring Check if your Hyperliquid node is synced: ```javascript async function checkNodeHealth(provider) { try { const blockNumber = await provider.getBlockNumber(); const block = await provider.getBlock(blockNumber); const now = Date.now() / 1000; const blockAge = now - block.timestamp; if (blockAge > 60) { console.warn(`Node may be behind. Last block was ${blockAge}s ago`); return false; } console.log(`Node healthy. Latest block: ${blockNumber}`); return true; } catch (error) { console.error('Node unreachable:', error); return false; } } ``` ## Performance Optimization ### Caching Strategy Cache block numbers to reduce API calls: ```javascript class BlockNumberCache { constructor(ttl = 2000) { this.cache = null; this.timestamp = 0; this.ttl = ttl; } async get(provider) { const now = Date.now(); if (this.cache && (now - this.timestamp) < this.ttl) { return this.cache; } this.cache = await provider.getBlockNumber(); this.timestamp = now; return this.cache; } invalidate() { this.cache = null; this.timestamp = 0; } } const blockCache = new BlockNumberCache(); ``` ### Batch Requests Combine with other calls for efficiency: ```javascript const batch = [ { jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 }, { jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 }, { jsonrpc: '2.0', method: 'eth_chainId', params: [], id: 3 } ]; const response = await fetch('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(batch) }); const results = await response.json(); ``` ## Error Handling Common errors and solutions: | Error Code | Description | Solution | |------------|-------------|----------| | -32603 | Internal error | Retry with exponential backoff | | -32005 | Rate limit exceeded | Implement rate limiting client-side | | -32000 | Execution reverted | Check node sync status | ```javascript async function safeGetBlockNumber(provider, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await provider.getBlockNumber(); } catch (error) { if (error.code === -32005) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } else if (i === maxRetries - 1) { throw error; } } } } ``` ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) — Get full block details by number - [`eth_getBlockByHash`](./eth_getBlockByHash) — Get block details by hash - [`eth_syncing`](./eth_syncing) — Check if node is still syncing --- ## eth_call - Hyperliquid RPC Method # eth_call Executes a new message call immediately without creating a transaction on Hyperliquid. Used for reading smart contract state. > **Why Hyperliquid?** Build on the dominant perpetuals DEX with 70% market share, $2.7T+ lifetime volume, and $2B TVL with 200K orders/second throughput, zero gas fees, sub-second finality, and fully onchain Central Limit Order Book (CLOB). ## Use Cases The `eth_call` method is essential for: - **Reading contract state** - Query view/pure functions - **Simulating transactions** - Test execution without gas costs - **DeFi integrations** - Check prices, balances, allowances for perpetual futures trading, onchain order books, and institutional-grade derivatives - **Complex queries** - Execute multi-step contract logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | 20-byte address executing the call | | `to` | `DATA` | Yes | 20-byte contract address | | `gas` | `QUANTITY` | No | Gas limit for the call | | `gasPrice` | `QUANTITY` | No | Gas price in wei | | `value` | `QUANTITY` | No | Value to send in wei | | `data` | `DATA` | Yes | Encoded function call data | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_call", "params": [ { "to": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "data": "0x70a0823100000000000000000000000030e54c9bc205e19d693d53c0b0be92299d4191ea" }, "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | The return value of the executed contract function | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x0000000000000000000000000000000000000000000000000de0b6b3a7640000" } ``` ## Code Examples ```bash # Call ERC20 balanceOf function curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_call", "params": [{ "to": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "data": "0x70a0823100000000000000000000000030e54c9bc205e19d693d53c0b0be92299d4191ea" }, "latest"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); // ERC20 ABI for common functions const ERC20_ABI = [ "function balanceOf(address owner) view returns (uint256)", "function allowance(address owner, address spender) view returns (uint256)", "function totalSupply() view returns (uint256)", "function decimals() view returns (uint8)", "function symbol() view returns (string)" ]; // Read ERC20 token balance async function getTokenBalance(tokenAddress, walletAddress) { const contract = new Contract(tokenAddress, ERC20_ABI, provider); const balance = await contract.balanceOf(walletAddress); const decimals = await contract.decimals(); const symbol = await contract.symbol(); return { raw: balance.toString(), formatted: (Number(balance) / Math.pow(10, decimals)).toFixed(4), symbol: symbol }; } // Direct eth_call async function directCall(to, data) { const result = await provider.call({ to, data }); return result; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) def get_erc20_balance(token_address, wallet_address): # balanceOf(address) selector function_signature = "balanceOf(address)" function_selector = w3.keccak(text=function_signature)[:4].hex() # Encode address parameter encoded_address = wallet_address[2:].lower().zfill(64) data = function_selector + encoded_address # Make the call result = w3.eth.call({ 'to': token_address, 'data': data }) return int(result.hex(), 16) balance = get_erc20_balance( '0x30e54c9bc205e19d693d53c0b0be92299d4191ea', '0x30e54c9bc205e19d693d53c0b0be92299d4191ea' ) print(f'Balance: {balance}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0x30e54c9bc205e19d693d53c0b0be92299d4191ea") data := common.FromHex("0x70a0823100000000000000000000000030e54c9bc205e19d693d53c0b0be92299d4191ea") msg := ethereum.CallMsg{ To: &contractAddress, Data: data, } result, err := client.CallContract(context.Background(), msg, nil) if err != nil { log.Fatal(err) } fmt.Printf("Result: 0x%x\n", result) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Contract function reverted | | -32602 | Invalid parameters | Invalid data encoding | | -32015 | VM execution error | Contract logic error | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas for transaction - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send actual transaction --- ## eth_chainId - Hyperliquid RPC Method # eth_chainId Returns the chain ID used for transaction signing on Hyperliquid. > **Why Hyperliquid?** Build on the dominant perpetuals DEX with 70% market share, $2.7T+ lifetime volume, and $2B TVL with 200K orders/second throughput, zero gas fees, sub-second finality, and fully onchain Central Limit Order Book (CLOB). ## Use Cases The `eth_chainId` method is essential for: - **Transaction signing** - Ensure transactions are signed for the correct network - **Network verification** - Confirm connection to the expected chain - **Multi-chain apps** - Handle different networks programmatically - **Wallet integration** - Validate network before transactions ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Chain ID in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1" } ``` ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_chainId", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const network = await provider.getNetwork(); console.log('Chain ID:', network.chainId); // Verify network before transaction async function verifyNetwork(expectedChainId) { const network = await provider.getNetwork(); if (network.chainId !== BigInt(expectedChainId)) { throw new Error(`Wrong network. Expected ${expectedChainId}, got ${network.chainId}`); } return true; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) chain_id = w3.eth.chain_id print(f'Chain ID: {chain_id}') # Verify network def verify_network(expected_chain_id): chain_id = w3.eth.chain_id if chain_id != expected_chain_id: raise ValueError(f'Wrong network. Expected {expected_chain_id}, got {chain_id}') return True ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } chainID, err := client.ChainID(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Chain ID: %d\n", chainID) } ``` ## Related Methods - [`net_version`](./net_version) - Get network version - [`eth_syncing`](./eth_syncing) - Check sync status --- ## eth_estimateGas - Hyperliquid RPC Method # eth_estimateGas Estimates the gas necessary to execute a transaction on Hyperliquid. > **Why Hyperliquid?** Build on the dominant perpetuals DEX with 70% market share, $2.7T+ lifetime volume, and $2B TVL with 200K orders/second throughput, zero gas fees, sub-second finality, and fully onchain Central Limit Order Book (CLOB). ## Use Cases The `eth_estimateGas` method is essential for: - **Transaction preparation** - Set appropriate gas limits - **Cost estimation** - Calculate transaction costs before sending - **Error detection** - Identify reverts before spending gas - **DeFi operations** - Estimate costs for perpetual futures trading, onchain order books, and institutional-grade derivatives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `from` | `DATA` | No | Sender address | | `to` | `DATA` | No | Recipient address | | `gas` | `QUANTITY` | No | Gas limit | | `gasPrice` | `QUANTITY` | No | Gas price | | `value` | `QUANTITY` | No | Value in wei | | `data` | `DATA` | No | Transaction data | ## Request ```json { "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "to": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "value": "0x1" }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Estimated gas amount in hexadecimal | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x5208" } ``` **Note**: `0x5208` = 21000 gas (standard ETH transfer) ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_estimateGas", "params": [{ "from": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "to": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "value": "0x1" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); // Estimate simple transfer async function estimateTransfer(to, value) { const gasEstimate = await provider.estimateGas({ to: to, value: parseEther(value) }); console.log('Estimated gas:', gasEstimate.toString()); return gasEstimate; } // Estimate contract call async function estimateContractCall(contract, method, args) { const gasEstimate = await contract[method].estimateGas(...args); console.log('Estimated gas:', gasEstimate.toString()); // Add 20% buffer for safety return gasEstimate * 120n / 100n; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) def estimate_transfer(to, value_in_ether): gas_estimate = w3.eth.estimate_gas({ 'to': to, 'value': w3.to_wei(value_in_ether, 'ether') }) print(f'Estimated gas: {gas_estimate}') return gas_estimate def estimate_contract_call(contract, method, args): func = getattr(contract.functions, method) gas_estimate = func(*args).estimate_gas() # Add 20% buffer return int(gas_estimate * 1.2) # Estimate simple transfer gas = estimate_transfer('0x30e54c9bc205e19d693d53c0b0be92299d4191ea', 0.1) ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } toAddress := common.HexToAddress("0x30e54c9bc205e19d693d53c0b0be92299d4191ea") msg := ethereum.CallMsg{ To: &toAddress, Value: big.NewInt(1000000000000000000), } gasLimit, err := client.EstimateGas(context.Background(), msg) if err != nil { log.Fatal(err) } fmt.Printf("Estimated gas: %d\n", gasLimit) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Execution reverted | Transaction would fail | | -32602 | Invalid params | Invalid transaction parameters | **Tip**: If estimation fails, the transaction would likely revert if sent. ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_feeHistory - Hyperliquid RPC Method # eth_feeHistory Returns historical gas information on Hyperliquid for fee estimation. ## Use Cases - **Fee prediction** - Estimate future gas prices based on history - **Gas analytics** - Analyze fee trends over time - **Optimal timing** - Find best times for transactions on perpetual futures trading, onchain order books, and institutional-grade derivatives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockCount` | `QUANTITY` | Yes | Number of blocks in the range | | `newestBlock` | `QUANTITY\|TAG` | Yes | Highest block of the range | | `rewardPercentiles` | `Array` | Yes | Percentiles to sample for priority fees | ## Request ```json { "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_feeHistory", "params": ["0x5", "latest", [25, 50, 75]], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const feeHistory = await provider.send('eth_feeHistory', ['0xa', 'latest', [25, 50, 75]]); console.log('Base fees:', feeHistory.baseFeePerGas.map(f => formatUnits(f, 'gwei'))); console.log('Reward (25th percentile):', feeHistory.reward.map(r => formatUnits(r[0], 'gwei'))); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) fee_history = w3.eth.fee_history(10, 'latest', [25, 50, 75]) print(f'Base fees: {[w3.from_wei(f, "gwei") for f in fee_history["baseFeePerGas"]]}') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee --- ## eth_gasPrice - Hyperliquid RPC Method # eth_gasPrice Returns the current gas price on Hyperliquid in wei. > **Why Hyperliquid?** Build on the dominant perpetuals DEX with 70% market share, $2.7T+ lifetime volume, and $2B TVL with 200K orders/second throughput, zero gas fees, sub-second finality, and fully onchain Central Limit Order Book (CLOB). ## Use Cases The `eth_gasPrice` method is essential for: - **Transaction pricing** - Set appropriate gas prices - **Cost estimation** - Calculate transaction costs before sending - **Gas monitoring** - Track network congestion - **DeFi operations** - Optimize costs for perpetual futures trading, onchain order books, and institutional-grade derivatives ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Current gas price in wei (hexadecimal) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x3b9aca00" } ``` **Note**: `0x3b9aca00` = 1 Gwei (1,000,000,000 wei) ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_gasPrice", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); const gasPrice = feeData.gasPrice; console.log('Gas Price:', formatUnits(gasPrice, 'gwei'), 'Gwei'); // Calculate transaction cost async function estimateTransactionCost(gasLimit) { const feeData = await provider.getFeeData(); const cost = feeData.gasPrice * BigInt(gasLimit); return formatUnits(cost, 'ether'); } const cost = await estimateTransactionCost(21000); console.log('Transfer cost:', cost, 'ETH'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) gas_price = w3.eth.gas_price print(f'Gas Price: {w3.from_wei(gas_price, "gwei")} Gwei') # Calculate transaction cost def estimate_transaction_cost(gas_limit): gas_price = w3.eth.gas_price cost = gas_price * gas_limit return w3.from_wei(cost, 'ether') cost = estimate_transaction_cost(21000) print(f'Transfer cost: {cost} ETH') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } gasPrice, err := client.SuggestGasPrice(context.Background()) if err != nil { log.Fatal(err) } // Convert to Gwei gwei := new(big.Float).Quo( new(big.Float).SetInt(gasPrice), big.NewFloat(1e9), ) fmt.Printf("Gas Price: %f Gwei\n", gwei) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32603 | Internal error | Node error | ## Related Methods - [`eth_maxPriorityFeePerGas`](./eth_maxPriorityFeePerGas) - Get priority fee (EIP-1559) - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas needed --- ## eth_getBalance - Hyperliquid RPC Method # eth_getBalance Returns the balance of a given address on Hyperliquid. > **Why Hyperliquid?** Build on the dominant perpetuals DEX with 70% market share, $2.7T+ lifetime volume, and $2B TVL with 200K orders/second throughput, zero gas fees, sub-second finality, and fully onchain Central Limit Order Book (CLOB). ## Use Cases The `eth_getBalance` method is essential for: - **Wallet applications** - Display user balances - **Transaction validation** - Check if account has sufficient funds - **DeFi applications** - Monitor collateral and liquidity for perpetual futures trading, onchain order books, and institutional-grade derivatives - **Account monitoring** - Track balance changes over time ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address to check balance for | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Integer of the current balance in wei (hexadecimal) | **Note**: 1 native token = 10^18 wei. Convert using `balance / 10^18`. ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x1a055690d9db80000" } ``` ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBalance", "params": [ "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const address = '0x30e54c9bc205e19d693d53c0b0be92299d4191ea'; const balanceWei = await provider.getBalance(address); const balance = formatEther(balanceWei); console.log(`Balance: ${balance}`); // Get balance at specific block const historicalBalance = await provider.getBalance(address, 1000000); console.log(`Historical balance: ${formatEther(historicalBalance)}`); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) address = '0x30e54c9bc205e19d693d53c0b0be92299d4191ea' balance_wei = w3.eth.get_balance(address) balance = w3.from_wei(balance_wei, 'ether') print(f'Balance: {balance}') # Get balance at specific block historical_balance = w3.eth.get_balance(address, block_identifier=1000000) print(f'Historical balance: {w3.from_wei(historical_balance, "ether")}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0x30e54c9bc205e19d693d53c0b0be92299d4191ea") balance, err := client.BalanceAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } // Convert to ether fbalance := new(big.Float).SetInt(balance) ethValue := new(big.Float).Quo(fbalance, big.NewFloat(1e18)) fmt.Printf("Balance: %f\n", ethValue) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid address format or block parameter | | -32000 | Execution error | Node execution error | ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_getTransactionCount`](./eth_getTransactionCount) - Get account nonce --- ## eth_getBlockByHash - Hyperliquid RPC Method # eth_getBlockByHash Returns information about a block by hash on Hyperliquid. > **Why Hyperliquid?** Build on the dominant perpetuals DEX with 70% market share, $2.7T+ lifetime volume, and $2B TVL with 200K orders/second throughput, zero gas fees, sub-second finality, and fully onchain Central Limit Order Book (CLOB). ## Use Cases The `eth_getBlockByHash` method is essential for: - **Block verification** - Verify block data using its unique hash - **Chain reorganization handling** - Track blocks during reorgs - **Cross-chain bridges** - Verify block finality for perpetual futures trading, onchain order books, and institutional-grade derivatives - **Deterministic queries** - Get consistent block data regardless of chain state ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockHash` | `DATA` | Yes | 32-byte block hash | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0x749f10b5acfaa7240d49fe6356f8b2a62991aeea630831d13fda8c99d28dd6af", false ], "id": 1 } ``` ## Returns Returns the same block object as `eth_getBlockByNumber`, or `null` if no block is found. | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used | | `transactions` | `Array` | Transaction objects or hashes | ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByHash", "params": [ "0x749f10b5acfaa7240d49fe6356f8b2a62991aeea630831d13fda8c99d28dd6af", false ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const blockHash = '0x749f10b5acfaa7240d49fe6356f8b2a62991aeea630831d13fda8c99d28dd6af'; const block = await provider.getBlock(blockHash); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) block_hash = '0x749f10b5acfaa7240d49fe6356f8b2a62991aeea630831d13fda8c99d28dd6af' block = w3.eth.get_block(block_hash) print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } blockHash := common.HexToHash("0x749f10b5acfaa7240d49fe6356f8b2a62991aeea630831d13fda8c99d28dd6af") block, err := client.BlockByHash(context.Background(), blockHash) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block hash format | | -32000 | Block not found | Block with this hash does not exist | ## Related Methods - [`eth_getBlockByNumber`](./eth_getBlockByNumber) - Get block by number - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number --- ## eth_getBlockByNumber - Hyperliquid RPC Method # eth_getBlockByNumber Returns information about a block by block number on Hyperliquid. > **Why Hyperliquid?** Build on the dominant perpetuals DEX with 70% market share, $2.7T+ lifetime volume, and $2B TVL with 200K orders/second throughput, zero gas fees, sub-second finality, and fully onchain Central Limit Order Book (CLOB). ## Use Cases The `eth_getBlockByNumber` method is essential for: - **Block explorers** - Display complete block information - **Transaction indexers** - Process all transactions in a block - **Analytics platforms** - Analyze blockchain data for perpetual futures trading, onchain order books, and institutional-grade derivatives - **Timestamp verification** - Get block timestamps for time-based logic ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `blockNumber` | `QUANTITY\|TAG` | Yes | Block number in hex, or `"latest"`, `"earliest"`, `"pending"`, `"safe"`, `"finalized"` | | `fullTransactions` | `Boolean` | Yes | If `true`, returns full transaction objects; if `false`, returns transaction hashes | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `number` | `QUANTITY` | Block number | | `hash` | `DATA` | 32-byte block hash | | `parentHash` | `DATA` | 32-byte parent block hash | | `timestamp` | `QUANTITY` | Unix timestamp | | `gasUsed` | `QUANTITY` | Total gas used by all transactions | | `gasLimit` | `QUANTITY` | Maximum gas allowed in block | | `transactions` | `Array` | Array of transaction objects or hashes | | `baseFeePerGas` | `QUANTITY` | Base fee per gas (EIP-1559) | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": { "number": "0x5BAD55", "hash": "0x749f10b5acfaa7240d49fe6356f8b2a62991aeea630831d13fda8c99d28dd6af", "parentHash": "0x...", "timestamp": "0x64d8f6d0", "gasUsed": "0x1234", "gasLimit": "0x1c9c380", "transactions": [], "baseFeePerGas": "0x5f5e100" } } ``` ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getBlockByNumber", "params": ["latest", false], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); // Get latest block const block = await provider.getBlock('latest'); console.log('Block number:', block.number); console.log('Timestamp:', new Date(block.timestamp * 1000)); console.log('Transactions:', block.transactions.length); // Get block with full transactions const blockWithTxs = await provider.getBlock('latest', true); for (const tx of blockWithTxs.prefetchedTransactions) { console.log('Transaction:', tx.hash); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) # Get latest block block = w3.eth.get_block('latest') print(f'Block number: {block.number}') print(f'Timestamp: {block.timestamp}') print(f'Transactions: {len(block.transactions)}') # Get block with full transactions block_full = w3.eth.get_block('latest', full_transactions=True) for tx in block_full.transactions: print(f'Transaction: {tx.hash.hex()}') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } // Get latest block block, err := client.BlockByNumber(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Block number: %d\n", block.Number().Uint64()) fmt.Printf("Timestamp: %d\n", block.Time()) fmt.Printf("Transactions: %d\n", len(block.Transactions())) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid block number or parameter format | | -32000 | Block not found | Block does not exist | ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get latest block number - [`eth_getBlockByHash`](./eth_getBlockByHash) - Get block by hash - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_getCode - Hyperliquid RPC Method # eth_getCode Returns the bytecode at a given address on Hyperliquid. > **Why Hyperliquid?** Build on the dominant perpetuals DEX with 70% market share, $2.7T+ lifetime volume, and $2B TVL with 200K orders/second throughput, zero gas fees, sub-second finality, and fully onchain Central Limit Order Book (CLOB). ## Use Cases The `eth_getCode` method is essential for: - **Contract verification** - Check if address is a contract - **Security analysis** - Verify deployed bytecode matches expected - **DeFi integrations** - Validate contracts before interactions - **Protocol analysis** - Analyze contract deployments for perpetual futures trading, onchain order books, and institutional-grade derivatives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "latest" ], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | Contract bytecode or `0x` if EOA | ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getCode", "params": [ "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const address = '0x30e54c9bc205e19d693d53c0b0be92299d4191ea'; const code = await provider.getCode(address); if (code === '0x') { console.log('Address is an EOA (externally owned account)'); } else { console.log('Address is a contract'); console.log('Bytecode length:', code.length); } // Check if address is a contract async function isContract(address) { const code = await provider.getCode(address); return code !== '0x'; } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) address = '0x30e54c9bc205e19d693d53c0b0be92299d4191ea' code = w3.eth.get_code(address) if code == b'': print('Address is an EOA') else: print('Address is a contract') print(f'Bytecode length: {len(code.hex())}') # Check if address is a contract def is_contract(address): code = w3.eth.get_code(address) return code != b'' ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } address := common.HexToAddress("0x30e54c9bc205e19d693d53c0b0be92299d4191ea") code, err := client.CodeAt(context.Background(), address, nil) if err != nil { log.Fatal(err) } if len(code) == 0 { fmt.Println("Address is an EOA") } else { fmt.Printf("Contract bytecode length: %d\n", len(code)) } } ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_getStorageAt`](./eth_getStorageAt) - Get contract storage --- ## eth_getFilterChanges - Hyperliquid RPC Method # eth_getFilterChanges Polling method for a filter on Hyperliquid, returns an array of logs since last poll. ## Use Cases - **Event streaming** - Get new events incrementally - **Real-time monitoring** - Track contract activity for perpetual futures trading, onchain order books, and institutional-grade derivatives - **Efficient indexing** - Process only new events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterChanges", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); // Poll loop async function pollFilter(filterId, interval = 2000) { while (true) { const changes = await provider.send('eth_getFilterChanges', [filterId]); if (changes.length > 0) { console.log('New events:', changes); } await new Promise(r => setTimeout(r, interval)); } } ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter --- ## eth_getFilterLogs - Hyperliquid RPC Method # eth_getFilterLogs Returns an array of all logs matching filter with given ID on Hyperliquid. ## Use Cases - **Historical queries** - Get all matching logs for a filter - **Full event history** - Retrieve complete event data for perpetual futures trading, onchain order books, and institutional-grade derivatives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID from eth_newFilter | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getFilterLogs", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const logs = await provider.send('eth_getFilterLogs', [filterId]); console.log('All matching logs:', logs.length); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_getLogs - Hyperliquid RPC Method # eth_getLogs Returns an array of all logs matching a given filter object on Hyperliquid. > **Why Hyperliquid?** Build on the dominant perpetuals DEX with 70% market share, $2.7T+ lifetime volume, and $2B TVL with 200K orders/second throughput, zero gas fees, sub-second finality, and fully onchain Central Limit Order Book (CLOB). ## Use Cases The `eth_getLogs` method is essential for: - **Event indexing** - Track contract events for perpetual futures trading, onchain order books, and institutional-grade derivatives - **Token transfers** - Monitor ERC20/ERC721 transfers - **DeFi analytics** - Track swaps, liquidity events, and more - **Notification systems** - Alert on specific on-chain events ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block (default: `"latest"`) | | `toBlock` | `QUANTITY\|TAG` | No | Ending block (default: `"latest"`) | | `address` | `DATA\|Array` | No | Contract address(es) to filter | | `topics` | `Array` | No | Array of topic filters | | `blockHash` | `DATA` | No | Filter single block by hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns Array of log objects: | Field | Type | Description | |-------|------|-------------| | `address` | `DATA` | Contract that emitted the log | | `topics` | `Array` | Array of indexed topics | | `data` | `DATA` | Non-indexed log data | | `blockNumber` | `QUANTITY` | Block number | | `transactionHash` | `DATA` | Transaction hash | | `logIndex` | `QUANTITY` | Log index in block | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": [{ "address": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."], "data": "0x...", "blockNumber": "0x5BAD55", "transactionHash": "0x...", "logIndex": "0x0" }] } ``` ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getLogs", "params": [{ "fromBlock": "latest", "toBlock": "latest", "address": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); // Get Transfer events const TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'; async function getTransferEvents(tokenAddress, fromBlock, toBlock) { const logs = await provider.getLogs({ address: tokenAddress, topics: [TRANSFER_TOPIC], fromBlock: fromBlock, toBlock: toBlock }); return logs.map(log => ({ from: '0x' + log.topics[1].slice(26), to: '0x' + log.topics[2].slice(26), blockNumber: log.blockNumber, transactionHash: log.transactionHash })); } const events = await getTransferEvents( '0x30e54c9bc205e19d693d53c0b0be92299d4191ea', 'latest', 'latest' ); console.log('Transfer events:', events); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) TRANSFER_TOPIC = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' def get_transfer_events(token_address, from_block, to_block): logs = w3.eth.get_logs({ 'address': token_address, 'topics': [TRANSFER_TOPIC], 'fromBlock': from_block, 'toBlock': to_block }) events = [] for log in logs: events.append({ 'from': '0x' + log['topics'][1].hex()[26:], 'to': '0x' + log['topics'][2].hex()[26:], 'block': log['blockNumber'], 'tx': log['transactionHash'].hex() }) return events events = get_transfer_events( '0x30e54c9bc205e19d693d53c0b0be92299d4191ea', 'latest', 'latest' ) print(f'Found {len(events)} transfer events') ``` ```go package main "context" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } contractAddress := common.HexToAddress("0x30e54c9bc205e19d693d53c0b0be92299d4191ea") transferTopic := common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef") query := ethereum.FilterQuery{ FromBlock: big.NewInt(0), ToBlock: nil, Addresses: []common.Address{contractAddress}, Topics: [][]common.Hash, } logs, err := client.FilterLogs(context.Background(), query) if err != nil { log.Fatal(err) } fmt.Printf("Found %d events\n", len(logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32005 | Query returned more than 10000 results | Reduce block range | | -32602 | Invalid params | Invalid filter parameters | ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create a filter for logs - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for new logs --- ## eth_getStorageAt - Hyperliquid RPC Method # eth_getStorageAt Returns the value from a storage position at a given address on Hyperliquid. ## Use Cases - **Contract analysis** - Read raw storage values - **State verification** - Verify contract state - **Security auditing** - Analyze storage layout for perpetual futures trading, onchain order books, and institutional-grade derivatives - **Protocol monitoring** - Track state changes ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte contract address | | `position` | `QUANTITY` | Yes | Storage slot position | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "0x0", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getStorageAt", "params": [ "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "0x0", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const address = '0x30e54c9bc205e19d693d53c0b0be92299d4191ea'; const slot = 0; const storage = await provider.getStorage(address, slot); console.log('Storage at slot 0:', storage); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) address = '0x30e54c9bc205e19d693d53c0b0be92299d4191ea' storage = w3.eth.get_storage_at(address, 0) print(f'Storage at slot 0: {storage.hex()}') ``` ## Related Methods - [`eth_getCode`](./eth_getCode) - Get contract bytecode - [`eth_call`](./eth_call) - Call contract functions --- ## eth_getTransactionByHash - Hyperliquid RPC Method # eth_getTransactionByHash Returns the information about a transaction by transaction hash on Hyperliquid. > **Why Hyperliquid?** Build on the dominant perpetuals DEX with 70% market share, $2.7T+ lifetime volume, and $2B TVL with 200K orders/second throughput, zero gas fees, sub-second finality, and fully onchain Central Limit Order Book (CLOB). ## Use Cases The `eth_getTransactionByHash` method is essential for: - **Transaction tracking** - Get details of pending or confirmed transactions - **Payment verification** - Verify transaction parameters - **Debugging** - Analyze transaction data for perpetual futures trading, onchain order books, and institutional-grade derivatives - **Block explorers** - Display transaction information ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `hash` | `DATA` | Transaction hash | | `from` | `DATA` | Sender address | | `to` | `DATA` | Recipient address | | `value` | `QUANTITY` | Value in wei | | `gas` | `QUANTITY` | Gas provided | | `gasPrice` | `QUANTITY` | Gas price in wei | | `input` | `DATA` | Transaction input data | | `nonce` | `QUANTITY` | Sender's nonce | | `blockHash` | `DATA` | Block hash (null if pending) | | `blockNumber` | `QUANTITY` | Block number (null if pending) | ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionByHash", "params": ["0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614'; const tx = await provider.getTransaction(txHash); if (tx) { console.log('From:', tx.from); console.log('To:', tx.to); console.log('Value:', formatEther(tx.value)); console.log('Block:', tx.blockNumber); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614' tx = w3.eth.get_transaction(tx_hash) if tx: print(f'From: {tx["from"]}') print(f'To: {tx["to"]}') print(f'Value: {w3.from_wei(tx["value"], "ether")}') print(f'Block: {tx["blockNumber"]}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614") tx, isPending, err := client.TransactionByHash(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Pending: %v\n", isPending) fmt.Printf("Value: %s\n", tx.Value().String()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash format | ## Related Methods - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction receipt - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionCount - Hyperliquid RPC Method # eth_getTransactionCount Returns the number of transactions sent from an address on Hyperliquid (the nonce). ## Use Cases - **Transaction building** - Get correct nonce for new transactions - **Account analysis** - Count total outgoing transactions - **Nonce management** - Handle pending transaction queues - **Wallet operations** - Prepare transactions for perpetual futures trading, onchain order books, and institutional-grade derivatives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `address` | `DATA` | Yes | 20-byte address | | `blockParameter` | `QUANTITY\|TAG` | Yes | Block number or tag (`pending` for next nonce) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "latest" ], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionCount", "params": [ "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "latest" ], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const address = '0x30e54c9bc205e19d693d53c0b0be92299d4191ea'; const nonce = await provider.getTransactionCount(address); console.log('Nonce:', nonce); // Get pending nonce for new transaction const pendingNonce = await provider.getTransactionCount(address, 'pending'); console.log('Next nonce:', pendingNonce); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) address = '0x30e54c9bc205e19d693d53c0b0be92299d4191ea' nonce = w3.eth.get_transaction_count(address) print(f'Nonce: {nonce}') # Get pending nonce pending_nonce = w3.eth.get_transaction_count(address, 'pending') print(f'Next nonce: {pending_nonce}') ``` ## Related Methods - [`eth_getBalance`](./eth_getBalance) - Get account balance - [`eth_sendRawTransaction`](./eth_sendRawTransaction) - Send transaction --- ## eth_getTransactionReceipt - Hyperliquid RPC Method # eth_getTransactionReceipt Returns the receipt of a transaction by transaction hash on Hyperliquid. Receipt is only available for mined transactions. > **Why Hyperliquid?** Build on the dominant perpetuals DEX with 70% market share, $2.7T+ lifetime volume, and $2B TVL with 200K orders/second throughput, zero gas fees, sub-second finality, and fully onchain Central Limit Order Book (CLOB). ## Use Cases The `eth_getTransactionReceipt` method is essential for: - **Transaction confirmation** - Verify transaction was mined successfully - **Gas analysis** - Check actual gas used vs estimated - **Event parsing** - Read emitted events from logs - **Status verification** - Confirm success/failure for perpetual futures trading, onchain order books, and institutional-grade derivatives ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `transactionHash` | `DATA` | Yes | 32-byte transaction hash | ## Request ```json { "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614"], "id": 1 } ``` ## Returns | Field | Type | Description | |-------|------|-------------| | `status` | `QUANTITY` | `1` (success) or `0` (failure) | | `transactionHash` | `DATA` | Transaction hash | | `blockHash` | `DATA` | Block hash | | `blockNumber` | `QUANTITY` | Block number | | `gasUsed` | `QUANTITY` | Gas used by this transaction | | `cumulativeGasUsed` | `QUANTITY` | Total gas used in block up to this tx | | `logs` | `Array` | Array of log objects | | `contractAddress` | `DATA` | Created contract address (if deployment) | ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_getTransactionReceipt", "params": ["0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const txHash = '0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614'; const receipt = await provider.getTransactionReceipt(txHash); if (receipt) { console.log('Status:', receipt.status === 1 ? 'Success' : 'Failed'); console.log('Gas Used:', receipt.gasUsed.toString()); console.log('Block:', receipt.blockNumber); console.log('Logs:', receipt.logs.length); // Parse specific events for (const log of receipt.logs) { console.log('Event from:', log.address); } } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) tx_hash = '0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614' receipt = w3.eth.get_transaction_receipt(tx_hash) if receipt: status = 'Success' if receipt['status'] == 1 else 'Failed' print(f'Status: {status}') print(f'Gas Used: {receipt["gasUsed"]}') print(f'Block: {receipt["blockNumber"]}') print(f'Logs: {len(receipt["logs"])}') ``` ```go package main "context" "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } txHash := common.HexToHash("0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614") receipt, err := client.TransactionReceipt(context.Background(), txHash) if err != nil { log.Fatal(err) } fmt.Printf("Status: %d\n", receipt.Status) fmt.Printf("Gas Used: %d\n", receipt.GasUsed) fmt.Printf("Logs: %d\n", len(receipt.Logs)) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32602 | Invalid params | Invalid transaction hash | **Note**: Returns `null` if transaction is not yet mined. ## Related Methods - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details - [`eth_getLogs`](./eth_getLogs) - Query logs by filter --- ## eth_maxPriorityFeePerGas - Hyperliquid RPC Method # eth_maxPriorityFeePerGas Returns the current recommended priority fee per gas on Hyperliquid for EIP-1559 transactions. ## Use Cases - **EIP-1559 transactions** - Set appropriate priority fees - **Transaction acceleration** - Calculate tips for faster inclusion - **Gas optimization** - Balance speed vs cost for perpetual futures trading, onchain order books, and institutional-grade derivatives ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 } ``` ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_maxPriorityFeePerGas", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const feeData = await provider.getFeeData(); console.log('Max Priority Fee:', formatUnits(feeData.maxPriorityFeePerGas, 'gwei'), 'Gwei'); console.log('Max Fee Per Gas:', formatUnits(feeData.maxFeePerGas, 'gwei'), 'Gwei'); ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) priority_fee = w3.eth.max_priority_fee print(f'Max Priority Fee: {w3.from_wei(priority_fee, "gwei")} Gwei') ``` ## Related Methods - [`eth_gasPrice`](./eth_gasPrice) - Get legacy gas price - [`eth_feeHistory`](./eth_feeHistory) - Get historical fee data --- ## eth_newBlockFilter - Hyperliquid RPC Method # eth_newBlockFilter Creates a filter on Hyperliquid to notify when a new block arrives. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newBlockFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newBlockFilter', []); // Poll for new blocks const newBlocks = await provider.send('eth_getFilterChanges', [filterId]); console.log('New block hashes:', newBlocks); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_blockNumber`](./eth_blockNumber) - Get current block --- ## eth_newFilter - Hyperliquid RPC Method # eth_newFilter Creates a filter object on Hyperliquid to notify when state changes (logs). ## Use Cases - **Event monitoring** - Subscribe to contract events - **Real-time updates** - Track events for perpetual futures trading, onchain order books, and institutional-grade derivatives - **Indexing** - Build event indexes incrementally ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `fromBlock` | `QUANTITY\|TAG` | No | Starting block | | `toBlock` | `QUANTITY\|TAG` | No | Ending block | | `address` | `DATA\|Array` | No | Contract address(es) | | `topics` | `Array` | No | Topic filters | ## Request ```json { "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"] }], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newFilter", "params": [{ "fromBlock": "latest", "address": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea" }], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); // Create filter const filterId = await provider.send('eth_newFilter', [{ fromBlock: 'latest', address: '0x30e54c9bc205e19d693d53c0b0be92299d4191ea', topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'] }]); // Poll for changes const changes = await provider.send('eth_getFilterChanges', [filterId]); console.log('New events:', changes); // Cleanup await provider.send('eth_uninstallFilter', [filterId]); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter for changes - [`eth_uninstallFilter`](./eth_uninstallFilter) - Remove filter - [`eth_getLogs`](./eth_getLogs) - Direct log query --- ## eth_newPendingTransactionFilter - Hyperliquid RPC Method # eth_newPendingTransactionFilter Creates a filter on Hyperliquid to notify when new pending transactions arrive. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `QUANTITY` | Filter ID | ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_newPendingTransactionFilter", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const filterId = await provider.send('eth_newPendingTransactionFilter', []); // Poll for pending transactions const pendingTxs = await provider.send('eth_getFilterChanges', [filterId]); console.log('Pending transaction hashes:', pendingTxs); ``` ## Related Methods - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter - [`eth_getTransactionByHash`](./eth_getTransactionByHash) - Get transaction details --- ## eth_sendRawTransaction - Hyperliquid RPC Method # eth_sendRawTransaction Submits a pre-signed transaction for broadcast to Hyperliquid. > **Why Hyperliquid?** Build on the dominant perpetuals DEX with 70% market share, $2.7T+ lifetime volume, and $2B TVL with 200K orders/second throughput, zero gas fees, sub-second finality, and fully onchain Central Limit Order Book (CLOB). ## Use Cases The `eth_sendRawTransaction` method is essential for: - **Broadcasting transactions** - Submit signed transactions to the network - **Wallet operations** - Send native tokens and interact with contracts - **DeFi operations** - Execute swaps, provide liquidity for perpetual futures trading, onchain order books, and institutional-grade derivatives - **Batch operations** - Submit multiple transactions efficiently ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `signedTransactionData` | `DATA` | Yes | The signed transaction data (RLP encoded) | ## Request ```json { "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c..."], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `DATA` | 32-byte transaction hash | ## Response ```json { "jsonrpc": "2.0", "id": 1, "result": "0x..." } ``` ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_sendRawTransaction", "params": ["0xf86c808504a817c80082520894..."], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const wallet = new Wallet('YOUR_PRIVATE_KEY', provider); // Send native tokens async function sendTransaction(to, value) { const tx = await wallet.sendTransaction({ to: to, value: parseEther(value) }); console.log('Transaction hash:', tx.hash); // Wait for confirmation const receipt = await tx.wait(); console.log('Confirmed in block:', receipt.blockNumber); return receipt; } // Send to contract async function sendContractTransaction(contract, method, args, value = '0') { const tx = await contract[method](...args, { value: parseEther(value) }); return await tx.wait(); } ``` ```python from web3 import Web3 w3 = Web3(Web3.HTTPProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY')) def send_transaction(private_key, to, value_in_ether): account = w3.eth.account.from_key(private_key) # Build transaction tx = { 'nonce': w3.eth.get_transaction_count(account.address), 'to': to, 'value': w3.to_wei(value_in_ether, 'ether'), 'gas': 21000, 'gasPrice': w3.eth.gas_price, 'chainId': w3.eth.chain_id } # Sign transaction signed_tx = account.sign_transaction(tx) # Send transaction tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction) print(f'Transaction hash: {tx_hash.hex()}') # Wait for confirmation receipt = w3.eth.wait_for_transaction_receipt(tx_hash) print(f'Confirmed in block: {receipt["blockNumber"]}') return receipt ``` ```go package main "context" "crypto/ecdsa" "fmt" "log" "math/big" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" ) func main() { client, err := ethclient.Dial("https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY") if err != nil { log.Fatal(err) } privateKey, err := crypto.HexToECDSA("YOUR_PRIVATE_KEY") if err != nil { log.Fatal(err) } publicKey := privateKey.Public() publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey) fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA) nonce, _ := client.PendingNonceAt(context.Background(), fromAddress) value := big.NewInt(1000000000000000000) gasLimit := uint64(21000) gasPrice, _ := client.SuggestGasPrice(context.Background()) toAddress := common.HexToAddress("0x30e54c9bc205e19d693d53c0b0be92299d4191ea") tx := types.NewTransaction(nonce, toAddress, value, gasLimit, gasPrice, nil) chainID, _ := client.NetworkID(context.Background()) signedTx, _ := types.SignTx(tx, types.NewEIP155Signer(chainID), privateKey) err = client.SendTransaction(context.Background(), signedTx) if err != nil { log.Fatal(err) } fmt.Printf("Transaction hash: %s\n", signedTx.Hash().Hex()) } ``` ## Error Handling | Error Code | Message | Description | |------------|---------|-------------| | -32000 | Nonce too low | Transaction nonce already used | | -32000 | Insufficient funds | Account has insufficient balance | | -32000 | Gas too low | Gas limit insufficient | | -32000 | Replacement underpriced | Gas price too low for replacement | ## Related Methods - [`eth_estimateGas`](./eth_estimateGas) - Estimate gas required - [`eth_gasPrice`](./eth_gasPrice) - Get current gas price - [`eth_getTransactionReceipt`](./eth_getTransactionReceipt) - Get transaction result --- ## eth_syncing - Hyperliquid RPC Method # eth_syncing Returns syncing status of Hyperliquid node. ## Parameters This method accepts no parameters. ## Request ```json { "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 } ``` ## Returns Returns `false` if not syncing, or an object with sync status. ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_syncing", "params": [], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const syncing = await provider.send('eth_syncing', []); if (syncing === false) { console.log('Node is fully synced'); } else { console.log('Syncing:', syncing); } ``` ## Related Methods - [`eth_blockNumber`](./eth_blockNumber) - Get current block - [`net_peerCount`](./net_peerCount) - Get peer count --- ## eth_uninstallFilter - Hyperliquid RPC Method # eth_uninstallFilter Uninstalls a filter on Hyperliquid. Should be called when no longer needed. ## Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `filterId` | `QUANTITY` | Yes | Filter ID to uninstall | ## Request ```json { "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 } ``` ## Returns | Type | Description | |------|-------------| | `Boolean` | `true` if filter was found and uninstalled | ## Code Examples ```bash curl -X POST https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "method": "eth_uninstallFilter", "params": ["0x1"], "id": 1 }' ``` ```javascript const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'); const success = await provider.send('eth_uninstallFilter', [filterId]); console.log('Filter removed:', success); ``` ## Related Methods - [`eth_newFilter`](./eth_newFilter) - Create filter - [`eth_getFilterChanges`](./eth_getFilterChanges) - Poll filter --- ## GetBlock - Get Block Data # GetBlock Retrieve a single block at a specific position from the Hyperliquid L1 Gateway. :::tip Full Code Examples Clone our [gRPC Code Examples Repository](https://github.com/dwellir-public/gRPC-code-examples) for complete, runnable implementations in Go, Python, and Node.js. ::: ## When to Use This Method `GetBlock` is essential for: - **Point-in-Time Analysis** - Get blockchain state at a specific block or timestamp - **Backtesting** - Retrieve historical block data for strategy analysis - **Auditing** - Verify transactions and state changes at specific points - **Debugging** - Investigate specific blocks during development ## Method Signature ```protobuf rpc GetBlock(Position) returns (Block) {} ``` ## Request Message ```protobuf message Position { // Leave all fields unset or zero to target the latest data. oneof position { int64 timestamp_ms = 1; // ms since Unix epoch, inclusive int64 block_height = 2; // block height, inclusive } } ``` The `Position` message allows flexible block targeting: - **timestamp_ms**: Get block at or after a specific time (milliseconds since Unix epoch) - **block_height**: Get block at a specific height - **Empty/zero**: Get the latest block ## Response Message ```protobuf message Block { // JSON-encoded Hyperliquid block from "replica_cmds". bytes data = 1; } ``` The `data` field contains a JSON-encoded block with the following structure: ### Data Structure ```json { "abci_block": { "time": "2025-09-08T06:41:57.997372546", "round": 992814678, "parent_round": 992814677, "proposer": "0x5ac99df645f3414876c816caa18b2d234024b487", "hardfork": { "version": 57, "round": 990500929 }, "signed_action_bundles": [ [ "0xb4b1f5a9c233f9d90fd24b9961fd12708b36cc3d56f8fda47f32b667ee8d1227", { "signed_actions": [ { "signature": { "r": "0x...", "s": "0x...", "v": 27 }, "action": { "type": "order", "orders": [...] }, "nonce": 1757313597362 } ], "broadcaster": "0x67e451964e0421f6e7d07be784f35c530667c2b3", "broadcaster_nonce": 1757313597367 } ] ] }, "resps": { "Full": [ [ "0xb4b1f5a9c233f9d90fd24b9961fd12708b36cc3d56f8fda47f32b667ee8d1227", [ { "user": "0xecb63caa47c7c4e77f60f1ce858cf28dc2b82b00", "res": { "status": "ok", "response": { "type": "order", "data": {...} } } } ] ] ] } } ``` ### Field Descriptions | Field | Type | Description | |-------|------|-------------| | `abci_block.time` | string | ISO-8601 timestamp with nanosecond precision | | `abci_block.round` | number | Current block number (height) | | `abci_block.parent_round` | number | Previous block number | | `abci_block.proposer` | string | Validator address that proposed the block | | `abci_block.hardfork` | object | Protocol version information | | `abci_block.signed_action_bundles` | array | Array of [hash, bundle_data] pairs | | `resps.Full` | array | Execution responses matching bundle structure | For the complete block specification including all action types, see the [StreamBlocks documentation](/hyperliquid/stream_blocks#full-block-spec). ## Implementation Examples ```go package main "context" "encoding/json" "fmt" "log" "os" "time" pb "hyperliquid-grpc-client/api/v2" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" ) type BlockData struct { AbciBlock struct { Time string `json:"time"` Round int64 `json:"round"` ParentRound int64 `json:"parent_round"` Proposer string `json:"proposer"` SignedActionBundles []interface{} `json:"signed_action_bundles"` } `json:"abci_block"` Resps struct { Full []interface{} `json:"Full"` } `json:"resps"` } func getBlock(ctx context.Context, client pb.HyperliquidL1GatewayClient, position *pb.Position) (*BlockData, error) { ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() response, err := client.GetBlock(ctx, position) if err != nil { return nil, fmt.Errorf("RPC call failed: %v", err) } fmt.Printf("Response size: %d bytes\n\n", len(response.Data)) var block BlockData if err := json.Unmarshal(response.Data, &block); err != nil { return nil, fmt.Errorf("failed to parse JSON: %v", err) } return &block, nil } func main() { endpoint := os.Getenv("HYPERLIQUID_ENDPOINT") apiKey := os.Getenv("API_KEY") if endpoint == "" { log.Fatal("Error: HYPERLIQUID_ENDPOINT environment variable is required.") } if apiKey == "" { log.Fatal("Error: API_KEY environment variable is required.") } fmt.Println("Hyperliquid Go gRPC Client - Get Block") fmt.Println("======================================") fmt.Printf("Endpoint: %s\n\n", endpoint) // Set up TLS connection creds := credentials.NewTLS(nil) opts := []grpc.DialOption{ grpc.WithTransportCredentials(creds), grpc.WithDefaultCallOptions( grpc.MaxCallRecvMsgSize(150 * 1024 * 1024), ), } fmt.Println("Connecting to gRPC server...") conn, err := grpc.NewClient(endpoint, opts...) if err != nil { log.Fatalf("Failed to connect: %v", err) } defer conn.Close() client := pb.NewHyperliquidL1GatewayClient(conn) fmt.Println("Connected successfully!\n") // Get block with API key ctx := context.Background() ctx = metadata.AppendToOutgoingContext(ctx, "x-api-key", apiKey) // Request latest block (empty position) request := &pb.Position{} // Or request by block height: // request := &pb.Position{Position: &pb.Position_BlockHeight{BlockHeight: 992814678}} // Or request by timestamp: // request := &pb.Position{Position: &pb.Position_TimestampMs{TimestampMs: 1725778917997}} fmt.Println("Fetching block...\n") block, err := getBlock(ctx, client, request) if err != nil { log.Fatalf("Failed to get block: %v", err) } // Display block information fmt.Printf("Block Height: %d\n", block.AbciBlock.Round) fmt.Printf("Parent Block: %d\n", block.AbciBlock.ParentRound) fmt.Printf("Time: %s\n", block.AbciBlock.Time) fmt.Printf("Proposer: %s\n", block.AbciBlock.Proposer) fmt.Printf("Action Bundles: %d\n", len(block.AbciBlock.SignedActionBundles)) } ``` ```python from datetime import datetime from dotenv import load_dotenv load_dotenv() def get_block(block_height=None, timestamp_ms=None): endpoint = os.getenv('HYPERLIQUID_ENDPOINT') api_key = os.getenv('API_KEY') if not endpoint: print("Error: HYPERLIQUID_ENDPOINT environment variable is required.") sys.exit(1) if not api_key: print("Error: API_KEY environment variable is required.") sys.exit(1) print('Hyperliquid Python gRPC Client - Get Block') print('==========================================') print(f'Endpoint: {endpoint}\n') credentials = grpc.ssl_channel_credentials() options = [ ('grpc.max_receive_message_length', 150 * 1024 * 1024), ] metadata = [('x-api-key', api_key)] print('Connecting to gRPC server...') with grpc.secure_channel(endpoint, credentials, options=options) as channel: client = hyperliquid_pb2_grpc.HyperliquidL1GatewayStub(channel) print('Connected successfully!\n') # Create request based on parameters if block_height is not None: request = hyperliquid_pb2.Position(block_height=block_height) print(f'Requesting block at height: {block_height}') elif timestamp_ms is not None: request = hyperliquid_pb2.Position(timestamp_ms=timestamp_ms) print(f'Requesting block at timestamp: {timestamp_ms}') else: request = hyperliquid_pb2.Position() print('Requesting latest block') print('\nFetching block...\n') try: response = client.GetBlock(request, metadata=metadata) print(f'Response size: {len(response.data)} bytes\n') process_block(response.data) except grpc.RpcError as e: print(f'RPC error: {e}') except Exception as e: print(f'Error: {e}') def process_block(data): try: block = json.loads(data.decode('utf-8')) print('BLOCK DATA') print('==========') abci_block = block.get('abci_block', {}) # Display block info print(f'Block Height: {abci_block.get("round")}') print(f'Parent Block: {abci_block.get("parent_round")}') print(f'Time: {abci_block.get("time")}') print(f'Proposer: {abci_block.get("proposer")}') # Display hardfork info hardfork = abci_block.get('hardfork', {}) print(f'\nHardfork Version: {hardfork.get("version")}') print(f'Hardfork Round: {hardfork.get("round")}') # Count action bundles bundles = abci_block.get('signed_action_bundles', []) print(f'\nAction Bundles: {len(bundles)}') # Count total actions total_actions = 0 action_types = {} for bundle in bundles: if len(bundle) >= 2: bundle_data = bundle[1] signed_actions = bundle_data.get('signed_actions', []) total_actions += len(signed_actions) for action in signed_actions: action_type = action.get('action', {}).get('type', 'unknown') action_types[action_type] = action_types.get(action_type, 0) + 1 print(f'Total Actions: {total_actions}') if action_types: print('\nAction Types:') for action_type, count in sorted(action_types.items(), key=lambda x: -x[1]): print(f' {action_type}: {count}') except json.JSONDecodeError as e: print(f'Failed to parse JSON: {e}') except Exception as e: print(f'Error processing block: {e}') if __name__ == '__main__': # Get latest block get_block() # Or get by block height: # get_block(block_height=992814678) # Or get by timestamp: # get_block(timestamp_ms=1725778917997) ``` ```javascript const grpc = require('@grpc/grpc-js'); const protoLoader = require('@grpc/proto-loader'); const path = require('path'); require('dotenv').config(); const PROTO_PATH = path.join(__dirname, 'v2.proto'); const packageDefinition = protoLoader.loadSync(PROTO_PATH, { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true }); const proto = grpc.loadPackageDefinition(packageDefinition); async function getBlock(options = {}) { const endpoint = process.env.HYPERLIQUID_ENDPOINT; const apiKey = process.env.API_KEY; if (!endpoint) { console.error('Error: HYPERLIQUID_ENDPOINT environment variable is required.'); process.exit(1); } if (!apiKey) { console.error('Error: API_KEY environment variable is required.'); process.exit(1); } console.log('Hyperliquid Node.js gRPC Client - Get Block'); console.log('==========================================='); console.log(`Endpoint: ${endpoint}\n`); const metadata = new grpc.Metadata(); metadata.add('x-api-key', apiKey); const client = new proto.hyperliquid_l1_gateway.v2.HyperliquidL1Gateway( endpoint, grpc.credentials.createSsl(), { 'grpc.max_receive_message_length': 150 * 1024 * 1024 } ); // Build request const request = {}; if (options.blockHeight) { request.block_height = options.blockHeight; console.log(`Requesting block at height: ${options.blockHeight}`); } else if (options.timestampMs) { request.timestamp_ms = options.timestampMs; console.log(`Requesting block at timestamp: ${options.timestampMs}`); } else { console.log('Requesting latest block'); } console.log('\nFetching block...\n'); client.GetBlock(request, metadata, (error, response) => { if (error) { console.error('gRPC error:', error.message); return; } try { const block = JSON.parse(response.data); console.log(`Response size: ${response.data.length} bytes\n`); processBlock(block); } catch (error) { console.error('Failed to parse response:', error.message); } }); } function processBlock(block) { console.log('BLOCK DATA'); console.log('=========='); const abciBlock = block.abci_block || {}; console.log(`Block Height: ${abciBlock.round}`); console.log(`Parent Block: ${abciBlock.parent_round}`); console.log(`Time: ${abciBlock.time}`); console.log(`Proposer: ${abciBlock.proposer}`); // Hardfork info const hardfork = abciBlock.hardfork || {}; console.log(`\nHardfork Version: ${hardfork.version}`); console.log(`Hardfork Round: ${hardfork.round}`); // Count bundles and actions const bundles = abciBlock.signed_action_bundles || []; console.log(`\nAction Bundles: ${bundles.length}`); let totalActions = 0; const actionTypes = {}; for (const bundle of bundles) { if (bundle.length >= 2) { const bundleData = bundle[1]; const signedActions = bundleData.signed_actions || []; totalActions += signedActions.length; for (const action of signedActions) { const actionType = action.action?.type || 'unknown'; actionTypes[actionType] = (actionTypes[actionType] || 0) + 1; } } } console.log(`Total Actions: ${totalActions}`); if (Object.keys(actionTypes).length > 0) { console.log('\nAction Types:'); const sorted = Object.entries(actionTypes).sort((a, b) => b[1] - a[1]); for (const [type, count] of sorted) { console.log(` ${type}: ${count}`); } } } // Get latest block getBlock(); // Or get by block height: // getBlock({ blockHeight: 992814678 }); // Or get by timestamp: // getBlock({ timestampMs: 1725778917997 }); ``` ## Common Use Cases ### 1. Historical Block Analysis ```python def analyze_block_activity(client, block_height): """Analyze trading activity in a specific block""" request = hyperliquid_pb2.Position(block_height=block_height) response = client.GetBlock(request, metadata=metadata) block = json.loads(response.data) abci_block = block.get('abci_block', {}) bundles = abci_block.get('signed_action_bundles', []) analysis = { 'block_height': abci_block.get('round'), 'timestamp': abci_block.get('time'), 'total_bundles': len(bundles), 'total_actions': 0, 'order_count': 0, 'cancel_count': 0, 'transfer_count': 0 } for bundle in bundles: if len(bundle) >= 2: for action in bundle[1].get('signed_actions', []): analysis['total_actions'] += 1 action_type = action.get('action', {}).get('type', '') if action_type == 'order': analysis['order_count'] += 1 elif action_type in ['cancel', 'cancelByCloid']: analysis['cancel_count'] += 1 elif action_type in ['spotSend', 'usdSend', 'withdraw3']: analysis['transfer_count'] += 1 return analysis ``` ### 2. Block Comparison ```go func compareBlocks(client pb.HyperliquidL1GatewayClient, ctx context.Context, height1, height2 int64) { block1, _ := client.GetBlock(ctx, &pb.Position{Position: &pb.Position_BlockHeight{BlockHeight: height1}}) block2, _ := client.GetBlock(ctx, &pb.Position{Position: &pb.Position_BlockHeight{BlockHeight: height2}}) var data1, data2 map[string]interface{} json.Unmarshal(block1.Data, &data1) json.Unmarshal(block2.Data, &data2) abci1 := data1["abci_block"].(map[string]interface{}) abci2 := data2["abci_block"].(map[string]interface{}) bundles1 := abci1["signed_action_bundles"].([]interface{}) bundles2 := abci2["signed_action_bundles"].([]interface{}) fmt.Printf("Block %d: %d bundles\n", height1, len(bundles1)) fmt.Printf("Block %d: %d bundles\n", height2, len(bundles2)) } ``` ### 3. Transaction Verification ```javascript async function verifyTransaction(client, metadata, txHash, blockHeight) { return new Promise((resolve, reject) => { const request = { block_height: blockHeight }; client.GetBlock(request, metadata, (error, response) => { if (error) { reject(error); return; } const block = JSON.parse(response.data); const bundles = block.abci_block?.signed_action_bundles || []; for (const bundle of bundles) { const bundleHash = bundle[0]; if (bundleHash === txHash) { resolve({ found: true, block_height: block.abci_block.round, bundle_data: bundle[1] }); return; } } resolve({ found: false }); }); }); } ``` ## Error Handling ```javascript async function robustGetBlock(client, metadata, position, retries = 3) { for (let attempt = 0; attempt < retries; attempt++) { try { return await new Promise((resolve, reject) => { client.GetBlock(position, metadata, (error, response) => { if (error) reject(error); else resolve(response); }); }); } catch (error) { console.warn(`Attempt ${attempt + 1} failed:`, error.message); if (attempt === retries - 1) { throw error; } // Exponential backoff await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000) ); } } } ``` ## Best Practices 1. **Position Selection**: Use block height for precise queries; timestamps may return different blocks across requests if near block boundaries 2. **Data Validation**: Always validate JSON structure before processing 3. **Error Recovery**: Implement retry logic with exponential backoff 4. **Resource Management**: Close gRPC connections properly to avoid resource leaks 5. **Caching**: Cache block data when analyzing the same blocks multiple times ## Current Limitations - **Data Retention**: Historical block data is limited to a 24-hour rolling window - **Rate Limits**: Be mindful of request frequency to avoid overwhelming the service ## Resources - **[GitHub: gRPC Code Examples](https://github.com/dwellir-public/gRPC-code-examples)** - Complete working examples - **[StreamBlocks Documentation](/hyperliquid/stream_blocks)** - Full block specification and action types reference *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Hyperliquid gRPC documentation](./grpc).* --- ## GetFills - Get Fill Data # GetFills Retrieve fills at a specific position from the Hyperliquid L1 Gateway. :::tip Full Code Examples Clone our [gRPC Code Examples Repository](https://github.com/dwellir-public/gRPC-code-examples) for complete, runnable implementations in Go, Python, and Node.js. ::: ## When to Use This Method `GetFills` is essential for: - **Trade Reconciliation** - Verify fills at a specific point in time - **Historical Analysis** - Retrieve fill data for backtesting or reporting - **Auditing** - Verify trade executions at specific blocks - **Debugging** - Investigate specific fills during development ## Method Signature ```protobuf rpc GetFills(Position) returns (BlockFills) {} ``` ## Request Message ```protobuf message Position { // Leave all fields unset or zero to target the latest data. oneof position { int64 timestamp_ms = 1; // ms since Unix epoch, inclusive int64 block_height = 2; // block height, inclusive } } ``` The `Position` message allows flexible fill targeting: - **timestamp_ms**: Get fills at or after a specific time (milliseconds since Unix epoch) - **block_height**: Get fills at a specific block height - **Empty/zero**: Get the latest fills ## Response Message ```protobuf message BlockFills { // JSON-encoded object from "node_fills" or "node_fills_by_block". bytes data = 1; } ``` The `data` field contains a JSON-encoded fills object with the following structure: ### Data Structure ```json { "local_time": "2025-07-27T08:50:10.334741319", "block_time": "2025-07-27T08:50:10.273720809", "block_number": 676607012, "events": [ [ "0x7839e2f2c375dd2935193f2736167514efff9916", { "coin": "BTC", "px": "118136.0", "sz": "0.00009", "side": "B", "time": 1753606210273, "startPosition": "-1.41864", "dir": "Close Short", "closedPnl": "-0.003753", "hash": "0xe7822040155eaa2e737e042854342401120052bbf063906ce8c8f3babe853a79", "oid": 121670079265, "crossed": false, "fee": "-0.000212", "tid": 161270588369408, "cloid": "0x09367b9f8541c581f95b02aaf05f1508", "feeToken": "USDC", "builder": "0x49ae63056b3a0be0b166813ee687309ab653c07c", "builderFee": "0.005528" } ] ] } ``` ### Field Descriptions | Field | Type | Description | |-------|------|-------------| | `local_time` | string | ISO-8601 timestamp when node processed the fill | | `block_time` | string | ISO-8601 timestamp from block consensus | | `block_number` | number | Block height containing these fills | | `events` | array | Array of [address, fill_data] pairs | ### Fill Event Fields | Field | Type | Description | |-------|------|-------------| | `coin` | string | Trading pair symbol (e.g., "BTC", "ETH") | | `px` | string | Fill price | | `sz` | string | Fill size | | `side` | string | `"B"` for buy, `"A"` for sell | | `time` | number | Fill timestamp in milliseconds | | `startPosition` | string | Position size before this fill | | `dir` | string | Direction: "Open Long", "Open Short", "Close Long", "Close Short" | | `closedPnl` | string | Realized PnL if closing position | | `hash` | string | Transaction hash | | `oid` | number | Order ID | | `crossed` | boolean | Whether order crossed the spread | | `fee` | string | Trading fee (negative = rebate) | | `tid` | number | Unique trade identifier | | `cloid` | string | Client order ID (optional) | | `feeToken` | string | Token used for fee | | `builder` | string | Builder address (optional) | | `builderFee` | string | Builder fee amount (optional) | For the complete fill specification, see the [StreamFills documentation](/hyperliquid/stream_fills#full-fill-spec). ## Implementation Examples ```go package main "context" "encoding/json" "fmt" "log" "os" "time" pb "hyperliquid-grpc-client/api/v2" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" ) type FillEvent struct { Coin string `json:"coin"` Px string `json:"px"` Sz string `json:"sz"` Side string `json:"side"` Time int64 `json:"time"` StartPosition string `json:"startPosition"` Dir string `json:"dir"` ClosedPnl string `json:"closedPnl"` Hash string `json:"hash"` Oid int64 `json:"oid"` Crossed bool `json:"crossed"` Fee string `json:"fee"` Tid int64 `json:"tid"` Cloid string `json:"cloid,omitempty"` FeeToken string `json:"feeToken"` } type FillsData struct { LocalTime string `json:"local_time"` BlockTime string `json:"block_time"` BlockNumber int64 `json:"block_number"` Events [][]interface{} `json:"events"` } func getFills(ctx context.Context, client pb.HyperliquidL1GatewayClient, position *pb.Position) (*FillsData, error) { ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() response, err := client.GetFills(ctx, position) if err != nil { return nil, fmt.Errorf("RPC call failed: %v", err) } fmt.Printf("Response size: %d bytes\n\n", len(response.Data)) var fills FillsData if err := json.Unmarshal(response.Data, &fills); err != nil { return nil, fmt.Errorf("failed to parse JSON: %v", err) } return &fills, nil } func main() { endpoint := os.Getenv("HYPERLIQUID_ENDPOINT") apiKey := os.Getenv("API_KEY") if endpoint == "" { log.Fatal("Error: HYPERLIQUID_ENDPOINT environment variable is required.") } if apiKey == "" { log.Fatal("Error: API_KEY environment variable is required.") } fmt.Println("Hyperliquid Go gRPC Client - Get Fills") fmt.Println("======================================") fmt.Printf("Endpoint: %s\n\n", endpoint) creds := credentials.NewTLS(nil) opts := []grpc.DialOption{ grpc.WithTransportCredentials(creds), grpc.WithDefaultCallOptions( grpc.MaxCallRecvMsgSize(150 * 1024 * 1024), ), } fmt.Println("Connecting to gRPC server...") conn, err := grpc.NewClient(endpoint, opts...) if err != nil { log.Fatalf("Failed to connect: %v", err) } defer conn.Close() client := pb.NewHyperliquidL1GatewayClient(conn) fmt.Println("Connected successfully!\n") ctx := context.Background() ctx = metadata.AppendToOutgoingContext(ctx, "x-api-key", apiKey) // Request latest fills (empty position) request := &pb.Position{} // Or request by block height: // request := &pb.Position{Position: &pb.Position_BlockHeight{BlockHeight: 676607012}} fmt.Println("Fetching fills...\n") fills, err := getFills(ctx, client, request) if err != nil { log.Fatalf("Failed to get fills: %v", err) } // Display fills information fmt.Printf("Block Number: %d\n", fills.BlockNumber) fmt.Printf("Block Time: %s\n", fills.BlockTime) fmt.Printf("Local Time: %s\n", fills.LocalTime) fmt.Printf("Fill Events: %d\n\n", len(fills.Events)) // Process each fill event for i, event := range fills.Events { if len(event) >= 2 { address := event[0].(string) fillData, _ := json.Marshal(event[1]) var fill FillEvent json.Unmarshal(fillData, &fill) fmt.Printf("Fill #%d:\n", i+1) fmt.Printf(" Address: %s\n", address) fmt.Printf(" Coin: %s\n", fill.Coin) fmt.Printf(" Side: %s\n", fill.Side) fmt.Printf(" Price: %s\n", fill.Px) fmt.Printf(" Size: %s\n", fill.Sz) fmt.Printf(" Direction: %s\n", fill.Dir) fmt.Printf(" Fee: %s %s\n", fill.Fee, fill.FeeToken) fmt.Println() } } } ``` ```python from datetime import datetime from dotenv import load_dotenv load_dotenv() def get_fills(block_height=None, timestamp_ms=None): endpoint = os.getenv('HYPERLIQUID_ENDPOINT') api_key = os.getenv('API_KEY') if not endpoint: print("Error: HYPERLIQUID_ENDPOINT environment variable is required.") sys.exit(1) if not api_key: print("Error: API_KEY environment variable is required.") sys.exit(1) print('Hyperliquid Python gRPC Client - Get Fills') print('==========================================') print(f'Endpoint: {endpoint}\n') credentials = grpc.ssl_channel_credentials() options = [ ('grpc.max_receive_message_length', 150 * 1024 * 1024), ] metadata = [('x-api-key', api_key)] print('Connecting to gRPC server...') with grpc.secure_channel(endpoint, credentials, options=options) as channel: client = hyperliquid_pb2_grpc.HyperliquidL1GatewayStub(channel) print('Connected successfully!\n') # Create request based on parameters if block_height is not None: request = hyperliquid_pb2.Position(block_height=block_height) print(f'Requesting fills at block height: {block_height}') elif timestamp_ms is not None: request = hyperliquid_pb2.Position(timestamp_ms=timestamp_ms) print(f'Requesting fills at timestamp: {timestamp_ms}') else: request = hyperliquid_pb2.Position() print('Requesting latest fills') print('\nFetching fills...\n') try: response = client.GetFills(request, metadata=metadata) print(f'Response size: {len(response.data)} bytes\n') process_fills(response.data) except grpc.RpcError as e: print(f'RPC error: {e}') except Exception as e: print(f'Error: {e}') def process_fills(data): try: fills = json.loads(data.decode('utf-8')) print('FILLS DATA') print('==========') print(f'Block Number: {fills.get("block_number")}') print(f'Block Time: {fills.get("block_time")}') print(f'Local Time: {fills.get("local_time")}') events = fills.get('events', []) print(f'Fill Events: {len(events)}\n') # Aggregate statistics total_volume = 0 total_pnl = 0 coins_traded = set() buy_count = 0 sell_count = 0 for i, event in enumerate(events): if len(event) >= 2: address = event[0] fill = event[1] coins_traded.add(fill.get('coin', '')) size = float(fill.get('sz', 0)) price = float(fill.get('px', 0)) total_volume += size * price pnl = float(fill.get('closedPnl', 0)) total_pnl += pnl if fill.get('side') == 'B': buy_count += 1 else: sell_count += 1 # Display first 5 fills in detail if i < 5: print(f'Fill #{i + 1}:') print(f' Address: {address}') print(f' Coin: {fill.get("coin")}') print(f' Side: {"Buy" if fill.get("side") == "B" else "Sell"}') print(f' Price: {fill.get("px")}') print(f' Size: {fill.get("sz")}') print(f' Direction: {fill.get("dir")}') print(f' Closed PnL: {fill.get("closedPnl")}') print(f' Fee: {fill.get("fee")} {fill.get("feeToken")}') print() if len(events) > 5: print(f'... and {len(events) - 5} more fills\n') # Summary print('SUMMARY') print('=======') print(f'Total Fills: {len(events)}') print(f'Buys: {buy_count}, Sells: {sell_count}') print(f'Coins Traded: {", ".join(coins_traded)}') print(f'Total Volume: ${total_volume:,.2f}') print(f'Total Realized PnL: ${total_pnl:,.4f}') except json.JSONDecodeError as e: print(f'Failed to parse JSON: {e}') except Exception as e: print(f'Error processing fills: {e}') if __name__ == '__main__': # Get latest fills get_fills() # Or get by block height: # get_fills(block_height=676607012) # Or get by timestamp: # get_fills(timestamp_ms=1753606210273) ``` ```javascript const grpc = require('@grpc/grpc-js'); const protoLoader = require('@grpc/proto-loader'); const path = require('path'); require('dotenv').config(); const PROTO_PATH = path.join(__dirname, 'v2.proto'); const packageDefinition = protoLoader.loadSync(PROTO_PATH, { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true }); const proto = grpc.loadPackageDefinition(packageDefinition); async function getFills(options = {}) { const endpoint = process.env.HYPERLIQUID_ENDPOINT; const apiKey = process.env.API_KEY; if (!endpoint) { console.error('Error: HYPERLIQUID_ENDPOINT environment variable is required.'); process.exit(1); } if (!apiKey) { console.error('Error: API_KEY environment variable is required.'); process.exit(1); } console.log('Hyperliquid Node.js gRPC Client - Get Fills'); console.log('==========================================='); console.log(`Endpoint: ${endpoint}\n`); const metadata = new grpc.Metadata(); metadata.add('x-api-key', apiKey); const client = new proto.hyperliquid_l1_gateway.v2.HyperliquidL1Gateway( endpoint, grpc.credentials.createSsl(), { 'grpc.max_receive_message_length': 150 * 1024 * 1024 } ); // Build request const request = {}; if (options.blockHeight) { request.block_height = options.blockHeight; console.log(`Requesting fills at block height: ${options.blockHeight}`); } else if (options.timestampMs) { request.timestamp_ms = options.timestampMs; console.log(`Requesting fills at timestamp: ${options.timestampMs}`); } else { console.log('Requesting latest fills'); } console.log('\nFetching fills...\n'); client.GetFills(request, metadata, (error, response) => { if (error) { console.error('gRPC error:', error.message); return; } try { const fills = JSON.parse(response.data); console.log(`Response size: ${response.data.length} bytes\n`); processFills(fills); } catch (error) { console.error('Failed to parse response:', error.message); } }); } function processFills(fills) { console.log('FILLS DATA'); console.log('=========='); console.log(`Block Number: ${fills.block_number}`); console.log(`Block Time: ${fills.block_time}`); console.log(`Local Time: ${fills.local_time}`); const events = fills.events || []; console.log(`Fill Events: ${events.length}\n`); // Aggregate statistics let totalVolume = 0; let totalPnl = 0; const coinsTraded = new Set(); let buyCount = 0; let sellCount = 0; for (let i = 0; i < events.length; i++) { const event = events[i]; if (event.length >= 2) { const address = event[0]; const fill = event[1]; coinsTraded.add(fill.coin || ''); const size = parseFloat(fill.sz || 0); const price = parseFloat(fill.px || 0); totalVolume += size * price; const pnl = parseFloat(fill.closedPnl || 0); totalPnl += pnl; if (fill.side === 'B') { buyCount++; } else { sellCount++; } // Display first 5 fills in detail if (i < 5) { console.log(`Fill #${i + 1}:`); console.log(` Address: ${address}`); console.log(` Coin: ${fill.coin}`); console.log(` Side: ${fill.side === 'B' ? 'Buy' : 'Sell'}`); console.log(` Price: ${fill.px}`); console.log(` Size: ${fill.sz}`); console.log(` Direction: ${fill.dir}`); console.log(` Closed PnL: ${fill.closedPnl}`); console.log(` Fee: ${fill.fee} ${fill.feeToken}`); console.log(); } } } if (events.length > 5) { console.log(`... and ${events.length - 5} more fills\n`); } // Summary console.log('SUMMARY'); console.log('======='); console.log(`Total Fills: ${events.length}`); console.log(`Buys: ${buyCount}, Sells: ${sellCount}`); console.log(`Coins Traded: ${[...coinsTraded].join(', ')}`); console.log(`Total Volume: $${totalVolume.toLocaleString(undefined, { minimumFractionDigits: 2 })}`); console.log(`Total Realized PnL: $${totalPnl.toFixed(4)}`); } // Get latest fills getFills(); // Or get by block height: // getFills({ blockHeight: 676607012 }); // Or get by timestamp: // getFills({ timestampMs: 1753606210273 }); ``` ## Common Use Cases ### 1. PnL Reconciliation ```python def reconcile_pnl(client, metadata, start_block, end_block): """Calculate total PnL between two blocks""" pnl_by_address = {} for block_height in range(start_block, end_block + 1): request = hyperliquid_pb2.Position(block_height=block_height) response = client.GetFills(request, metadata=metadata) fills = json.loads(response.data) for event in fills.get('events', []): if len(event) >= 2: address = event[0] fill = event[1] pnl = float(fill.get('closedPnl', 0)) if address not in pnl_by_address: pnl_by_address[address] = 0 pnl_by_address[address] += pnl return pnl_by_address ``` ### 2. Fill Verification ```go func verifyFill(client pb.HyperliquidL1GatewayClient, ctx context.Context, blockHeight int64, traderId string) []map[string]interface{} { request := &pb.Position{Position: &pb.Position_BlockHeight{BlockHeight: blockHeight}} response, _ := client.GetFills(ctx, request) var fills map[string]interface{} json.Unmarshal(response.Data, &fills) var traderFills []map[string]interface{} events := fills["events"].([]interface{}) for _, event := range events { eventArr := event.([]interface{}) if len(eventArr) >= 2 { address := eventArr[0].(string) if address == traderId { fillData := eventArr[1].(map[string]interface{}) traderFills = append(traderFills, fillData) } } } return traderFills } ``` ### 3. Volume Analysis ```javascript function analyzeVolume(fills) { const volumeByCoin = {}; const events = fills.events || []; for (const event of events) { if (event.length >= 2) { const fill = event[1]; const coin = fill.coin; const volume = parseFloat(fill.sz) * parseFloat(fill.px); if (!volumeByCoin[coin]) { volumeByCoin[coin] = { totalVolume: 0, buyVolume: 0, sellVolume: 0, fillCount: 0 }; } volumeByCoin[coin].totalVolume += volume; volumeByCoin[coin].fillCount++; if (fill.side === 'B') { volumeByCoin[coin].buyVolume += volume; } else { volumeByCoin[coin].sellVolume += volume; } } } return volumeByCoin; } ``` ## Error Handling ```javascript async function robustGetFills(client, metadata, position, retries = 3) { for (let attempt = 0; attempt < retries; attempt++) { try { return await new Promise((resolve, reject) => { client.GetFills(position, metadata, (error, response) => { if (error) reject(error); else resolve(response); }); }); } catch (error) { console.warn(`Attempt ${attempt + 1} failed:`, error.message); if (attempt === retries - 1) { throw error; } // Exponential backoff await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000) ); } } } ``` ## Best Practices 1. **Position Selection**: Use block height for precise queries; timestamps may return different fills across requests 2. **Data Validation**: Always validate JSON structure and handle optional fields 3. **Deduplication**: Use `tid` (trade ID) as the unique identifier for deduplication 4. **Error Recovery**: Implement retry logic with exponential backoff 5. **Resource Management**: Close gRPC connections properly to avoid resource leaks ## Current Limitations - **Data Retention**: Historical fill data is limited to a 24-hour rolling window - **Rate Limits**: Be mindful of request frequency to avoid overwhelming the service ## Resources - **[GitHub: gRPC Code Examples](https://github.com/dwellir-public/gRPC-code-examples)** - Complete working examples - **[StreamFills Documentation](/hyperliquid/stream_fills)** - Full fill specification and streaming examples - **[Copy Trading Bot](https://github.com/dwellir-public/gRPC-code-examples/tree/main/copy-trading-bot)** - Production-ready example using fill data *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Hyperliquid gRPC documentation](./grpc).* --- ## GetOrderBookSnapshot - Get Order Book Data # GetOrderBookSnapshot Retrieve a single order book snapshot at a specific point in time from the Hyperliquid L1 Gateway. :::tip Full Code Examples Clone our [gRPC Code Examples Repository](https://github.com/dwellir-public/gRPC-code-examples) for complete, runnable implementations in Go, Python, and Node.js. ::: ## When to Use This Method `GetOrderBookSnapshot` is essential for: - **Market Analysis** - Get current market depth and liquidity - **Trading Strategies** - Analyze bid/ask spreads and order distribution - **Price Discovery** - Determine fair market value - **Risk Management** - Assess market impact before placing orders ## Method Signature ```protobuf rpc GetOrderBookSnapshot(Timestamp) returns (OrderBookSnapshot) {} ``` ## Request Message ```protobuf message Timestamp { int64 timestamp_ms = 1; } ``` The `timestamp_ms` field specifies the time in milliseconds since Unix epoch for the requested snapshot. ## Response Message ```protobuf message OrderBookSnapshot { // JSON-encoded object conforming to a // Hyperliquid order book snapshot bytes data = 1; } ``` The `data` field contains a JSON-encoded order book snapshot with the following structure: ### Data Structure ```json { "coin": "string", // Trading pair symbol (e.g., "@1" for ETH) "time": 1757672867000, // Unix timestamp in milliseconds "levels": [ [ // Bid levels (index 0) { "px": "18.414", // Price level "sz": "100.0", // Total size at this level "n": 1 // Number of orders at this level }, // ... more bid levels ], [ // Ask levels (index 1) { "px": "18.515", // Price level "sz": "50.5", // Total size at this level "n": 2 // Number of orders at this level }, // ... more ask levels ] ] } ``` ### Field Descriptions | Field | Type | Description | |-------|------|-------------| | `coin` | string | The trading pair symbol | | `time` | number | Unix timestamp in milliseconds | | `levels[0]` | array | Bid orders sorted by price (descending) | | `levels[1]` | array | Ask orders sorted by price (ascending) | | `px` | string | Price at this level | | `sz` | string | Total size/volume at this price level | | `n` | number | Number of individual orders at this level | ## Implementation Examples ```go package main "context" "encoding/json" "fmt" "log" "os" "time" pb "hyperliquid-grpc-client/api/v2" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" ) type OrderBookLevel struct { Price string `json:"px"` Size string `json:"sz"` Orders int `json:"n"` } type OrderBookData struct { Coin string `json:"coin"` Time float64 `json:"time"` Levels [][]OrderBookLevel `json:"levels"` } func getOrderBookSnapshot(ctx context.Context, client pb.HyperliquidL1GatewayClient) (*OrderBookData, error) { // Create context with timeout ctx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() // Request current snapshot (timestamp_ms 0 = latest) request := &pb.Timestamp{TimestampMs: 0} response, err := client.GetOrderBookSnapshot(ctx, request) if err != nil { return nil, fmt.Errorf("RPC call failed: %v", err) } fmt.Printf("📦 Response size: %d bytes\n\n", len(response.Data)) // Parse JSON response var orderBook OrderBookData if err := json.Unmarshal(response.Data, &orderBook); err != nil { return nil, fmt.Errorf("failed to parse JSON: %v", err) } return &orderBook, nil } func main() { endpoint := os.Getenv("HYPERLIQUID_ENDPOINT") apiKey := os.Getenv("API_KEY") if endpoint == "" { log.Fatal("Error: HYPERLIQUID_ENDPOINT environment variable is required.\nPlease create a .env file and set your endpoint.") } if apiKey == "" { log.Fatal("Error: API_KEY environment variable is required.\nPlease set your API key in the .env file.") } fmt.Println("🚀 Hyperliquid Go gRPC Client - Get Order Book Snapshot") fmt.Println("======================================================") fmt.Printf("📡 Endpoint: %s\n\n", endpoint) // Set up TLS connection creds := credentials.NewTLS(nil) // Connection options opts := []grpc.DialOption{ grpc.WithTransportCredentials(creds), grpc.WithDefaultCallOptions( grpc.MaxCallRecvMsgSize(150 * 1024 * 1024), // 150MB max ), } fmt.Println("🔌 Connecting to gRPC server...") conn, err := grpc.NewClient(endpoint, opts...) if err != nil { log.Fatalf("❌ Failed to connect: %v", err) } defer conn.Close() // Create the client client := pb.NewHyperliquidL1GatewayClient(conn) fmt.Println("✅ Connected successfully!\n") fmt.Println("📥 Fetching order book snapshot...\n") // Get order book snapshot with API key ctx := context.Background() ctx = metadata.AppendToOutgoingContext(ctx, "x-api-key", apiKey) orderBook, err := getOrderBookSnapshot(ctx, client) if err != nil { log.Fatalf("❌ Failed to get order book: %v", err) } // Process the response processOrderBook(orderBook) } func processOrderBook(orderBook *OrderBookData) { // Display basic information fmt.Printf("Coin: %s\n", orderBook.Coin) // Convert timestamp timestamp := time.Unix(int64(orderBook.Time/1000), 0) fmt.Printf("Time: %s\n", timestamp.Format("2006-01-02 15:04:05 UTC")) if len(orderBook.Levels) >= 2 { bids := orderBook.Levels[0] asks := orderBook.Levels[1] fmt.Printf("\nBids: %d levels\n", len(bids)) fmt.Printf("Asks: %d levels\n", len(asks)) // Display best bid and ask if len(bids) > 0 && len(asks) > 0 { fmt.Printf("\nBest Bid: %s @ %s (Orders: %d)\n", bids[0].Size, bids[0].Price, bids[0].Orders) fmt.Printf("Best Ask: %s @ %s (Orders: %d)\n", asks[0].Size, asks[0].Price, asks[0].Orders) // Calculate spread spread := calculateSpread(bids[0].Price, asks[0].Price) fmt.Printf("Spread: %.6f\n", spread) } // Display market depth (top 5 levels) fmt.Println("\nMarket Depth (Top 5):") displayDepth(bids, asks, 5) } } func calculateSpread(bidPrice, askPrice string) float64 { var bid, ask float64 fmt.Sscanf(bidPrice, "%f", &bid) fmt.Sscanf(askPrice, "%f", &ask) return ask - bid } func displayDepth(bids, asks []OrderBookLevel, levels int) { maxLevels := min(levels, len(bids), len(asks)) fmt.Println(" Bids | Asks") fmt.Println(" --------------- | ---------------") for i := 0; i < maxLevels; i++ { fmt.Printf(" %s @ %-8s | %s @ %s\n", bids[i].Size, bids[i].Price, asks[i].Size, asks[i].Price) } } func min(values ...int) int { minVal := values[0] for _, v := range values[1:] { if v < minVal { minVal = v } } return minVal } ``` ```python from datetime import datetime from dotenv import load_dotenv # Load environment variables load_dotenv() def get_order_book_snapshot(): endpoint = os.getenv('HYPERLIQUID_ENDPOINT') api_key = os.getenv('API_KEY') if not endpoint: print("Error: HYPERLIQUID_ENDPOINT environment variable is required.") print("Please create a .env file from .env.example and set your endpoint.") sys.exit(1) if not api_key: print("Error: API_KEY environment variable is required.") print("Please set your API key in the .env file.") sys.exit(1) print('🚀 Hyperliquid Python gRPC Client - Get Order Book Snapshot') print('=========================================================') print(f'📡 Endpoint: {endpoint}\n') # Create SSL credentials credentials = grpc.ssl_channel_credentials() # Create channel with options options = [ ('grpc.max_receive_message_length', 150 * 1024 * 1024), # 150MB max ] # Prepare metadata with API key metadata = [('x-api-key', api_key)] print('🔌 Connecting to gRPC server...') with grpc.secure_channel(endpoint, credentials, options=options) as channel: # Create client stub client = hyperliquid_pb2_grpc.HyperliquidL1GatewayStub(channel) print('✅ Connected successfully!\n') # Create request - 0 means latest snapshot request = hyperliquid_pb2.Timestamp(timestamp_ms=0) print('📥 Fetching order book snapshot...\n') try: # Get order book snapshot with metadata response = client.GetOrderBookSnapshot(request, metadata=metadata) print(f'📦 Response size: {len(response.data)} bytes\n') # Process the snapshot process_order_book(response.data) except grpc.RpcError as e: print(f'❌ RPC error: {e}') except Exception as e: print(f'❌ Error: {e}') def process_order_book(data): try: # Parse JSON order_book = json.loads(data.decode('utf-8')) print('📊 ORDER BOOK SNAPSHOT') print('===================') # Display coin/symbol if 'coin' in order_book: print(f'🪙 Coin: {order_book["coin"]}') # Display timestamp if 'time' in order_book: timestamp = order_book['time'] dt = datetime.fromtimestamp(timestamp / 1000) print(f'⏰ Time: {dt.strftime("%Y-%m-%d %H:%M:%S UTC")}') # Display levels if 'levels' in order_book and isinstance(order_book['levels'], list): if len(order_book['levels']) >= 2: bids = order_book['levels'][0] asks = order_book['levels'][1] print(f'\n📋 Bids: {len(bids)} levels') print(f'📋 Asks: {len(asks)} levels') # Display best bid and ask if len(bids) > 0 and len(asks) > 0: best_bid = bids[0] best_ask = asks[0] print(f'\n💰 Best Bid: {best_bid["sz"]} @ {best_bid["px"]} (Orders: {best_bid["n"]})') print(f'💰 Best Ask: {best_ask["sz"]} @ {best_ask["px"]} (Orders: {best_ask["n"]})') # Calculate spread bid_price = float(best_bid['px']) ask_price = float(best_ask['px']) spread = ask_price - bid_price spread_bps = (spread / bid_price) * 10000 print(f'\n📊 Spread: {spread:.6f} ({spread_bps:.2f} bps)') # Display top 5 levels print('\n📈 ORDER BOOK (Top 5 Levels)') print(' Bids | Asks') print(' -------------------- | --------------------') max_levels = min(5, len(bids), len(asks)) for i in range(max_levels): bid = bids[i] ask = asks[i] print(f' {bid["sz"]:>8s} @ {bid["px"]:<9s} | {ask["sz"]:>8s} @ {ask["px"]:<9s}') # Calculate depth top_10_bids = bids[:10] top_10_asks = asks[:10] bid_depth = sum(float(level['sz']) for level in top_10_bids) ask_depth = sum(float(level['sz']) for level in top_10_asks) total_depth = bid_depth + ask_depth print(f'\n📊 Market Depth (Top 10 levels):') print(f' Bid depth: {bid_depth:.4f}') print(f' Ask depth: {ask_depth:.4f}') print(f' Total depth: {total_depth:.4f}') if total_depth > 0: imbalance = (bid_depth - ask_depth) / total_depth print(f' Depth imbalance: {imbalance:.3f}') except json.JSONDecodeError as e: print(f'❌ Failed to parse JSON: {e}') print(f'Raw data (first 200 bytes): {data[:200]}') except Exception as e: print(f'❌ Error processing order book: {e}') if __name__ == '__main__': get_order_book_snapshot() ``` ```javascript const grpc = require('@grpc/grpc-js'); const protoLoader = require('@grpc/proto-loader'); const path = require('path'); require('dotenv').config(); // Load proto file const PROTO_PATH = path.join(__dirname, 'v2.proto'); const packageDefinition = protoLoader.loadSync(PROTO_PATH, { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true }); const proto = grpc.loadPackageDefinition(packageDefinition); // Main function async function getOrderBookSnapshot() { const endpoint = process.env.HYPERLIQUID_ENDPOINT; const apiKey = process.env.API_KEY; if (!endpoint) { console.error('Error: HYPERLIQUID_ENDPOINT environment variable is required.'); console.error('Please create a .env file from .env.example and set your endpoint.'); process.exit(1); } if (!apiKey) { console.error('Error: API_KEY environment variable is required.'); console.error('Please set your API key in the .env file.'); process.exit(1); } console.log('🚀 Hyperliquid Node.js gRPC Client - Get Order Book Snapshot'); console.log('==========================================================='); console.log(`📡 Endpoint: ${endpoint}\n`); // Create metadata with API key const metadata = new grpc.Metadata(); metadata.add('x-api-key', apiKey); // Create client with SSL credentials and 150MB message size limit const client = new proto.hyperliquid_l1_gateway.v2.HyperliquidL1Gateway( endpoint, grpc.credentials.createSsl(), { 'grpc.max_receive_message_length': 150 * 1024 * 1024 } ); console.log('📥 Fetching order book snapshot...\n'); // Make the gRPC call client.GetOrderBookSnapshot({ timestamp_ms: 0 }, metadata, (error, response) => { if (error) { console.error('❌ gRPC error:', error.message); return; } try { const orderBook = JSON.parse(response.data); console.log(`📦 Response size: ${response.data.length} bytes\n`); // Process the order book processOrderBook(orderBook); } catch (error) { console.error('❌ Failed to parse response:', error.message); } }); } function processOrderBook(orderBook) { console.log('📊 ORDER BOOK SNAPSHOT'); console.log('==================='); // Display coin/symbol if (orderBook.coin) { console.log(`🪙 Coin: ${orderBook.coin}`); } // Display timestamp if (orderBook.time) { const date = new Date(orderBook.time); console.log(`⏰ Time: ${date.toISOString()}`); } // Display levels const levels = orderBook.levels || []; if (levels.length >= 2) { const bids = levels[0]; const asks = levels[1]; console.log(`\n📋 Bids: ${bids.length} levels`); console.log(`📋 Asks: ${asks.length} levels`); // Display best bid and ask if (bids.length > 0 && asks.length > 0) { const bestBid = bids[0]; const bestAsk = asks[0]; console.log(`\n💰 Best Bid: ${bestBid.sz} @ ${bestBid.px} (Orders: ${bestBid.n})`); console.log(`💰 Best Ask: ${bestAsk.sz} @ ${bestAsk.px} (Orders: ${bestAsk.n})`); // Calculate spread const bidPrice = parseFloat(bestBid.px); const askPrice = parseFloat(bestAsk.px); const spread = askPrice - bidPrice; const spreadBps = (spread / bidPrice) * 10000; console.log(`\n📊 Spread: ${spread.toFixed(6)} (${spreadBps.toFixed(2)} bps)`); } // Display top 5 levels console.log('\n📈 ORDER BOOK (Top 5 Levels)'); console.log(' Bids | Asks'); console.log(' -------------------- | --------------------'); const maxLevels = Math.min(5, bids.length, asks.length); for (let i = 0; i < maxLevels; i++) { const bid = bids[i]; const ask = asks[i]; const bidStr = `${bid.sz.padStart(8)} @ ${bid.px.padEnd(9)}`; const askStr = `${ask.sz.padStart(8)} @ ${ask.px.padEnd(9)}`; console.log(` ${bidStr} | ${askStr}`); } // Calculate depth const top10Bids = bids.slice(0, 10); const top10Asks = asks.slice(0, 10); const bidDepth = top10Bids.reduce((sum, level) => sum + parseFloat(level.sz), 0); const askDepth = top10Asks.reduce((sum, level) => sum + parseFloat(level.sz), 0); const totalDepth = bidDepth + askDepth; console.log('\n📊 Market Depth (Top 10 levels):'); console.log(` Bid depth: ${bidDepth.toFixed(4)}`); console.log(` Ask depth: ${askDepth.toFixed(4)}`); console.log(` Total depth: ${totalDepth.toFixed(4)}`); if (totalDepth > 0) { const imbalance = (bidDepth - askDepth) / totalDepth; console.log(` Depth imbalance: ${imbalance.toFixed(3)}`); } } } // Run it getOrderBookSnapshot(); ``` ## Common Use Cases ### 1. Market Making Strategy ```javascript async function marketMakingSignals(client) { const orderBook = await client.getSnapshot(); const metrics = client.calculateMetrics(orderBook); if (!metrics) return null; // Calculate fair value and optimal spread const midPrice = (metrics.bestBid + metrics.bestAsk) / 2; const optimalSpread = Math.max(metrics.spread * 0.8, 0.001); // Minimum spread // Analyze order book imbalance for pricing adjustment const imbalanceAdjustment = metrics.depthImbalance * 0.0001; // Adjust based on imbalance return { fairValue: midPrice, bidPrice: midPrice - (optimalSpread / 2) + imbalanceAdjustment, askPrice: midPrice + (optimalSpread / 2) + imbalanceAdjustment, marketDepth: metrics.totalVolume, spreadTightness: metrics.spreadBps, imbalance: metrics.depthImbalance, bidOrders: metrics.bidOrders, askOrders: metrics.askOrders }; } ``` ### 2. Liquidity Assessment ```python def assess_liquidity(order_book, target_size): """Assess market impact for a given trade size""" levels = order_book.get('levels', []) if len(levels) < 2: return None bids = levels[0] # Bid levels asks = levels[1] # Ask levels def calculate_slippage(levels, size, is_buy): filled = 0 weighted_price = 0 orders_hit = 0 for level in levels: price = float(level['px']) volume = float(level['sz']) num_orders = level['n'] fill_amount = min(size - filled, volume) weighted_price += price * fill_amount filled += fill_amount orders_hit += num_orders if filled >= size: break return { 'avg_price': weighted_price / filled if filled > 0 else None, 'filled': filled, 'orders_hit': orders_hit } # Calculate slippage for buy and sell buy_impact = calculate_slippage(asks, target_size, True) # Buy from asks sell_impact = calculate_slippage(bids, target_size, False) # Sell to bids if not bids or not asks: return None best_bid = float(bids[0]['px']) best_ask = float(asks[0]['px']) mid_price = (best_bid + best_ask) / 2 result = { 'mid_price': mid_price, 'target_size': target_size, 'can_buy': buy_impact['filled'] >= target_size, 'can_sell': sell_impact['filled'] >= target_size } if buy_impact['avg_price']: result['buy_price'] = buy_impact['avg_price'] result['buy_slippage'] = (buy_impact['avg_price'] - mid_price) / mid_price result['buy_orders_hit'] = buy_impact['orders_hit'] if sell_impact['avg_price']: result['sell_price'] = sell_impact['avg_price'] result['sell_slippage'] = (mid_price - sell_impact['avg_price']) / mid_price result['sell_orders_hit'] = sell_impact['orders_hit'] return result ``` ### 3. Real-time Price Display ```go func displayOrderBookLadder(orderBook *OrderBookData) { fmt.Println("\n=== ORDER BOOK LADDER ===") fmt.Printf("Coin: %s\n", orderBook.Coin) // Convert and display timestamp timestamp := time.Unix(int64(orderBook.Time/1000), 0) fmt.Printf("Time: %s\n", timestamp.Format("15:04:05 UTC")) if len(orderBook.Levels) < 2 { fmt.Println("No order book data available") return } bids := orderBook.Levels[0] asks := orderBook.Levels[1] // Display top 5 asks in reverse order (highest price first) fmt.Println("\n ASKS") fmt.Println(" Orders | Size | Price") fmt.Println(" -------|-------------|------------") displayCount := min(5, len(asks)) for i := displayCount - 1; i >= 0; i-- { ask := asks[i] fmt.Printf(" %6d | %11s | %10s\n", ask.Orders, ask.Size, ask.Price) } // Display spread line fmt.Println(" ======================================") if len(bids) > 0 && len(asks) > 0 { spread := calculateSpread(bids[0].Price, asks[0].Price) fmt.Printf(" SPREAD: %.6f\n", spread) } fmt.Println(" ======================================") // Display top 5 bids fmt.Println(" BIDS") fmt.Println(" Orders | Size | Price") fmt.Println(" -------|-------------|------------") for i := 0; i < min(5, len(bids)); i++ { bid := bids[i] fmt.Printf(" %6d | %11s | %10s\n", bid.Orders, bid.Size, bid.Price) } // Display summary fmt.Printf("\nTotal Levels: %d bids, %d asks\n", len(bids), len(asks)) } ``` ## Error Handling ```javascript async function robustGetSnapshot(client, retries = 3) { for (let attempt = 0; attempt < retries; attempt++) { try { return await client.getSnapshot(); } catch (error) { console.warn(`Attempt ${attempt + 1} failed:`, error.message); if (attempt === retries - 1) { throw error; } // Exponential backoff await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000) ); } } } ``` ## Best Practices 1. **Cache Management**: Order book snapshots can be cached briefly (1-5 seconds) for non-critical applications 2. **Data Validation**: Always validate JSON structure and numerical values 3. **Error Recovery**: Implement retry logic with exponential backoff 4. **Resource Management**: Close gRPC connections properly to avoid resource leaks 5. **Performance**: For high-frequency updates, consider using the streaming methods instead ## Current Limitations - **Data Retention**: Historical order book data is limited to a 24-hour rolling window - **Rate Limits**: Be mindful of request frequency to avoid overwhelming the service ## Resources - **[GitHub: gRPC Code Examples](https://github.com/dwellir-public/gRPC-code-examples)** - Complete working examples - **[Copy Trading Bot](https://github.com/dwellir-public/gRPC-code-examples/tree/main/copy-trading-bot)** - Production-ready trading bot example *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Hyperliquid gRPC documentation](./grpc).* --- ## StreamBlocks - Real-time Block Streaming # StreamBlocks Stream continuous block data starting from a position, providing real-time access to Hyperliquid blockchain state changes. :::tip Full Code Examples Clone our [gRPC Code Examples Repository](https://github.com/dwellir-public/gRPC-code-examples) for complete, runnable implementations in Go, Python, and Node.js. ::: ## When to Use This Method `StreamBlocks` is essential for: - **Blockchain Monitoring** - Track all network activity and state changes - **Block Explorers** - Build real-time blockchain data applications - **Analytics Systems** - Collect comprehensive blockchain metrics - **Compliance & Auditing** - Monitor all network transactions and events ## Method Signature ```protobuf rpc StreamBlocks(Position) returns (stream Block) {} ``` ## Request Message ```protobuf message Position { // Leave all fields unset or zero to target the latest data. oneof position { int64 timestamp_ms = 1; // ms since Unix epoch, inclusive int64 block_height = 2; // block height, inclusive } } ``` The `Position` message allows flexible stream starting points: - **timestamp_ms**: Start streaming from a specific time (milliseconds since Unix epoch) - **block_height**: Start streaming from a specific block height - **Empty/zero**: Start streaming from the latest block ## Response Stream ```protobuf message Block { // JSON-encoded Hyperliquid block from "replica_cmds". bytes data = 1; } ``` The `data` field contains a JSON-encoded block object with: - Block header information (height `round`, timestamp `time`) - Transaction data and execution results - State changes and events - Validator signatures and consensus data - Note: The sample format does not include a top-level block hash; bundle hashes are present per `signed_action_bundles`. ## Full Block Spec `StreamBlocks` emits a JSON payload matching Hyperliquid's `replica_cmds` BlockData. Below is the exact structure. Top-level keys (always present): ```json { "abci_block": { "time": "2025-09-08T06:41:57.997372546", // ISO-8601 with nanosecond precision "round": 992814678, // Current block number (always incrementing) "parent_round": 992814677, // Previous block (always round - 1) "proposer": "0x5ac99df645f3414876c816caa18b2d234024b487", // 40 hex chars, lowercase "hardfork": { "version": 57, // Protocol version number "round": 990500929 // Block when this version activated }, "signed_action_bundles": [ // Array of [hash, bundle_data] pairs [ "0xb4b1f5a9c233f9d90fd24b9961fd12708b36cc3d56f8fda47f32b667ee8d1227", // Bundle hash (64 hex) { "signed_actions": [ // Array of transactions in this bundle { "signature": { "r": "0xd931f13565ae66c3bc41a05da4180bb795dbd9ed2d365efaf639fd23b3774ac6", "s": "0x4a7a0534bf0a4238dfe404a88d335ab4c9b8222909100d773635e328d2ab864c", "v": 27 // Recovery ID: always 27 or 28 }, "action": { "type": "order", // Action type identifier "orders": [{ // Type-specific payload "a": 170, // Asset ID "b": true, // Buy=true, Sell=false "p": "0.038385", // Price as string "s": "1514", // Size as string "r": false, // Reduce-only flag "t": { "limit": { "tif": "Ioc" // Time-in-force: Ioc/Alo/Gtc } }, "c": "0x7192c49bcadb32d394e38617ea99cc09" // Client order ID }] }, "nonce": 1757313597362 // Unique transaction nonce } // ... more signed_actions ], "broadcaster": "0x67e451964e0421f6e7d07be784f35c530667c2b3", // Who sent bundle "broadcaster_nonce": 1757313597367 // Bundle-level nonce } ] // ... more bundles (typically 1-6 total) ] }, "resps": { "Full": [ // Matches signed_action_bundles structure [ "0xb4b1f5a9c233f9d90fd24b9961fd12708b36cc3d56f8fda47f32b667ee8d1227", // Same bundle hash [ // One response per signed_action { "user": "0xecb63caa47c7c4e77f60f1ce858cf28dc2b82b00", // Address of action signer "res": { "status": "ok", // "ok" or "err" "response": { "type": "order", // Response type "data": { "statuses": [{ "filled": { // Order state: filled/resting/error "totalSz": "1514.0", // Filled size "avgPx": "0.038385", // Average fill price "oid": 156190414943, // Order ID assigned "cloid": "0x7192c49bcadb32d394e38617ea99cc09" // Client order ID } }] } } } } // ... more responses (one per action) ] ] // ... more response bundles (matches signed_action_bundles count) ] } } ``` ### Bundle Entry Structure ```jsonc [ "0x...", // bundle_hash { "signed_actions": [ /* SignedAction */ ], "broadcaster": "0x...", "broadcaster_nonce": 1757313597367 } ] ``` ### SignedAction Envelope Common fields across all actions: ```jsonc { "signature": { "r": "0x...", "s": "0x...", "v": 27 }, "action": { "type": "order" }, // Action type identifier "nonce": 1757313597362, "vaultAddress": "0x...", // optional "expiresAfter": 1757313718705 // optional } ``` ### Data Guarantees - `abci_block` and `resps.Full` are always present. - `resps.Full.length === abci_block.signed_action_bundles.length`. - For each bundle, `responses.length === signed_actions.length`. - Height is `abci_block.round`, parent is `abci_block.parent_round`. - Timestamp `abci_block.time` is ISO-8601 with nanosecond precision (treat as UTC if no suffix). ### Developer Tips - Dispatch on `action.type` and handle new types defensively. - Store `bundle_hash` as the stable join key between actions and responses. - Normalize prices/sizes (strings) to numeric types as appropriate. --- ## Action Types Reference Each block contains signed action bundles where individual actions are categorized by type. Dispatch on `action.type` to process different categories. ### Trading Actions Core order management and execution operations. | Action Type | Description | |-------------|-------------| | [order](/hyperliquid/order) | Submit new limit or market orders | | [cancel](/hyperliquid/cancel) | Cancel orders by order ID | | [cancelByCloid](/hyperliquid/cancelByCloid) | Cancel orders by client order ID | | [batchModify](/hyperliquid/batchModify) | Modify multiple orders atomically | | [modify](/hyperliquid/modify) | Modify a single existing order | | [scheduleCancel](/hyperliquid/scheduleCancel) | Schedule future order cancellation | | [twapOrder](/hyperliquid/twapOrder) | Submit time-weighted average price order | | [twapCancel](/hyperliquid/twapCancel) | Cancel TWAP order | ### Transfer Actions Asset movement between accounts and withdrawals. | Action Type | Description | |-------------|-------------| | [spotSend](/hyperliquid/spotSend) | Send spot assets to another address | | [sendAsset](/hyperliquid/sendAsset) | Generic asset transfer | | [usdClassTransfer](/hyperliquid/usdClassTransfer) | Transfer USD-class assets between margin modes | | [withdraw3](/hyperliquid/withdraw3) | Withdraw assets to external address | | [usdSend](/hyperliquid/usdSend) | Send USD to another address | ### Risk Management Actions Leverage and margin configuration. | Action Type | Description | |-------------|-------------| | [updateLeverage](/hyperliquid/updateLeverage) | Update position leverage | | [updateIsolatedMargin](/hyperliquid/updateIsolatedMargin) | Adjust isolated margin for position | | [userPortfolioMargin](/hyperliquid/userPortfolioMargin) | Enable or configure portfolio margin mode | ### Permissions Actions Agent authorization and trading permissions. | Action Type | Description | |-------------|-------------| | [approveAgent](/hyperliquid/approveAgent) | Authorize agent to trade on behalf of user | | [approveBuilderFee](/hyperliquid/approveBuilderFee) | Approve builder fee for order routing | | [userDexAbstraction](/hyperliquid/userDexAbstraction) | Configure DEX abstraction settings | | [agentEnableDexAbstraction](/hyperliquid/agentEnableDexAbstraction) | Agent enables DEX abstraction for user | ### SubAccount Actions Sub-account creation and management. | Action Type | Description | |-------------|-------------| | [subAccountTransfer](/hyperliquid/subAccountTransfer) | Transfer assets between main and sub-account | | [createSubAccount](/hyperliquid/createSubAccount) | Create new sub-account | | [subAccountModify](/hyperliquid/subAccountModify) | Modify sub-account settings | | [subAccountSpotTransfer](/hyperliquid/subAccountSpotTransfer) | Transfer spot assets to/from sub-account | ### Vault Actions Vault creation, deposits, and position management. | Action Type | Description | |-------------|-------------| | [createVault](/hyperliquid/createVault) | Create new trading vault | | [vaultTransfer](/hyperliquid/vaultTransfer) | Deposit or withdraw from vault | | [NetChildVaultPositionsAction](/hyperliquid/NetChildVaultPositionsAction) | Net child vault positions | ### Validator Actions Consensus and cross-chain bridge operations. | Action Type | Description | |-------------|-------------| | [VoteEthDepositAction](/hyperliquid/VoteEthDepositAction) | Validator vote on ETH deposit | | [VoteEthFinalizedWithdrawalAction](/hyperliquid/VoteEthFinalizedWithdrawalAction) | Validator vote on finalized ETH withdrawal | | [ValidatorSignWithdrawalAction](/hyperliquid/ValidatorSignWithdrawalAction) | Validator signs withdrawal transaction | | [voteAppHash](/hyperliquid/voteAppHash) | Validator votes on application state hash | ### EVM Actions HyperEVM transaction execution and configuration. | Action Type | Description | |-------------|-------------| | [evmRawTx](/hyperliquid/evmRawTx) | Execute raw EVM transaction | | [evmUserModify](/hyperliquid/evmUserModify) | Modify EVM user settings | ### Security Actions Multi-signature and account security. | Action Type | Description | |-------------|-------------| | [multiSig](/hyperliquid/multiSig) | Multi-signature operation | | [convertToMultiSigUser](/hyperliquid/convertToMultiSigUser) | Convert account to multi-sig | ### Referral Actions Referral program management. | Action Type | Description | |-------------|-------------| | [setReferrer](/hyperliquid/setReferrer) | Set referrer for account | | [registerReferrer](/hyperliquid/registerReferrer) | Register as referrer | ### Market Actions Perpetual market deployment. | Action Type | Description | |-------------|-------------| | [perpDeploy](/hyperliquid/perpDeploy) | Deploy new perpetual market | ### Rewards Actions Reward claiming operations. | Action Type | Description | |-------------|-------------| | [claimRewards](/hyperliquid/claimRewards) | Claim accumulated rewards | ### Staking Actions Token delegation and staking. | Action Type | Description | |-------------|-------------| | [tokenDelegate](/hyperliquid/tokenDelegate) | Delegate tokens to validator | ### Lending Actions Borrow and lending operations. | Action Type | Description | |-------------|-------------| | [borrowLend](/hyperliquid/borrowLend) | Borrow or lend assets | ### Collateral Actions Collateral deposits and withdrawals. | Action Type | Description | |-------------|-------------| | [cDeposit](/hyperliquid/cDeposit) | Deposit collateral | | [cWithdraw](/hyperliquid/cWithdraw) | Withdraw collateral | ### Spot Actions Spot market configuration. | Action Type | Description | |-------------|-------------| | [spotUser](/hyperliquid/spotUser) | Spot user configuration | ### System Actions Internal system operations. | Action Type | Description | |-------------|-------------| | [noop](/hyperliquid/noop) | No operation (heartbeat/padding) | | [SetGlobalAction](/hyperliquid/SetGlobalAction) | Set global system parameters | | [reserveRequestWeight](/hyperliquid/reserveRequestWeight) | Reserve request weight allocation | --- ## Best Practices 1. **Connection Management**: Implement robust reconnection logic with exponential backoff 2. **Memory Management**: Use bounded collections for storing recent blocks to prevent memory leaks 3. **Performance**: Process blocks asynchronously to avoid blocking the stream 4. **Error Recovery**: Handle various error types (network, parsing, processing) gracefully 5. **Resource Cleanup**: Properly close streams and connections on shutdown ## Current Limitations - **Historical Data**: Cannot stream from historical timestamps; only real-time streaming available - **Data Retention**: Node maintains only 24 hours of historical block data - **Backpressure**: High-volume periods may require careful handling to avoid overwhelming downstream systems ## Resources - **[GitHub: gRPC Code Examples](https://github.com/dwellir-public/gRPC-code-examples)** - Complete working implementations in Go, Python, and Node.js - **[Copy Trading Bot](https://github.com/dwellir-public/gRPC-code-examples/tree/main/copy-trading-bot)** - Production-ready trading bot example *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Hyperliquid gRPC documentation](./index.mdx).* --- ## StreamFills - Real-time Fill Streaming # StreamFills Stream continuous fill data starting from a position, providing real-time access to order executions on Hyperliquid. :::tip Full Code Examples Clone our [gRPC Code Examples Repository](https://github.com/dwellir-public/gRPC-code-examples) for complete, runnable implementations. See the [copy-trading-bot](https://github.com/dwellir-public/gRPC-code-examples/tree/main/copy-trading-bot) for a production-ready example using `StreamFills`. ::: ## When to Use This Method `StreamFills` is essential for: - **Trade Monitoring** - Track order executions in real-time - **Position Management** - Monitor fills for active trading strategies - **Settlement Tracking** - Verify order completions and partial fills - **Analytics & Reporting** - Collect comprehensive trade execution data ## Method Signature ```protobuf rpc StreamFills(Position) returns (stream BlockFills) {} ``` ## Request Message ```protobuf message Position { // Leave all fields unset or zero to target the latest data. oneof position { int64 timestamp_ms = 1; // ms since Unix epoch, inclusive int64 block_height = 2; // block height, inclusive } } ``` The `Position` message allows flexible stream starting points: - **timestamp_ms**: Start streaming from a specific time (milliseconds since Unix epoch) - **block_height**: Start streaming from a specific block height - **Empty/zero**: Start streaming from the latest fills ## Response Stream ```protobuf message BlockFills { // JSON-encoded object from "node_fills" or "node_fills_by_block". bytes data = 1; } ``` The `data` field contains a JSON-encoded fills object with: - Fill execution details (price, size, side) - Order identifiers (order ID, client order ID) - Counterparty information - Timestamp and block reference ## Full Fill Spec `StreamFills` emits a JSON payload matching Hyperliquid's `node_fills` format. Below is the exact structure. Top-level keys (always present): ```json { "local_time": "2025-07-27T08:50:10.334741319", // ISO-8601 timestamp when node processed fill (nanosecond precision) "block_time": "2025-07-27T08:50:10.273720809", // ISO-8601 timestamp from block consensus "block_number": 676607012, // Block height containing this fill "events": [ // Array of [address, fill_data] pairs [ "0x7839e2f2c375dd2935193f2736167514efff9916", // User address (40 hex chars, lowercase) { "coin": "BTC", // Trading pair symbol "px": "118136.0", // Fill price (string) "sz": "0.00009", // Fill size (string) "side": "B", // "B" (buy) or "A" (sell/ask) "time": 1753606210273, // Fill timestamp (ms since Unix epoch) "startPosition": "-1.41864", // Position size before fill (string) "dir": "Close Short", // Direction: "Open Long" | "Open Short" | "Close Long" | "Close Short" "closedPnl": "-0.003753", // Realized PnL from closing position (string, can be negative) "hash": "0xe7822040155eaa2e737e042854342401120052bbf063906ce8c8f3babe853a79", // Transaction hash (64 hex) "oid": 121670079265, // Order ID (numeric) "crossed": false, // Whether order crossed the spread "fee": "-0.000212", // Trading fee (string, negative = rebate) "tid": 161270588369408, // Trade ID (unique identifier) "cloid": "0x09367b9f8541c581f95b02aaf05f1508", // Client order ID (optional, 32 hex) "feeToken": "USDC", // Token used for fee payment "builder": "0x49ae63056b3a0be0b166813ee687309ab653c07c", // Builder address (optional) "builderFee": "0.005528" // Builder fee amount (optional, string) } ] // ... more [address, fill_data] pairs ] } ``` Fill event entry (`events[i]`): ```jsonc [ "0x...", // user_address - the trader's address { // Fill details object } ] ``` Fill details fields: | Field | Type | Description | |-------|------|-------------| | `coin` | string | Trading pair symbol (e.g., "BTC", "ETH", "SOL") | | `px` | string | Fill price | | `sz` | string | Fill size | | `side` | string | `"B"` for buy, `"A"` for sell | | `time` | number | Fill timestamp in milliseconds since Unix epoch | | `startPosition` | string | Position size before this fill | | `dir` | string | Position direction: `"Open Long"`, `"Open Short"`, `"Close Long"`, `"Close Short"` | | `closedPnl` | string | Realized PnL if closing a position (can be negative) | | `hash` | string | Transaction hash (64 hex characters) | | `oid` | number | Order ID assigned by the system | | `crossed` | boolean | Whether the order crossed the spread (taker vs maker) | | `fee` | string | Trading fee (negative values indicate rebates) | | `tid` | number | Unique trade identifier | | `cloid` | string | Client order ID if provided (optional) | | `feeToken` | string | Token used for fee payment | | `builder` | string | Builder address if order was routed through a builder (optional) | | `builderFee` | string | Fee paid to builder (optional) | Guarantees and alignment: - `events` array contains all fills from the block for all users. - Each event pairs a user address with their fill details. - `block_number` corresponds to `abci_block.round` in StreamBlocks. - `block_time` aligns with `abci_block.time` in StreamBlocks. - Multiple fills per block are delivered in a single message. Developer tips: - Use `tid` as the unique identifier for deduplication. - Track `startPosition` and `dir` to reconstruct position changes. - Sum `closedPnl` across fills to calculate realized PnL. - Normalize `px`, `sz`, `fee`, and `closedPnl` (strings) to numeric types as appropriate. - Handle optional fields (`cloid`, `builder`, `builderFee`) defensively. ## Implementation Examples ```go package main "context" "encoding/json" "fmt" "log" "os" "strings" pb "hyperliquid-grpc-client/api/v2" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" ) func streamFills() { endpoint := os.Getenv("HYPERLIQUID_ENDPOINT") apiKey := os.Getenv("API_KEY") fmt.Println("🚀 Hyperliquid Go gRPC Client - Stream Fills") fmt.Println("=============================================") fmt.Printf("📡 Endpoint: %s\n\n", endpoint) // Set up TLS connection creds := credentials.NewTLS(nil) // Connection options opts := []grpc.DialOption{ grpc.WithTransportCredentials(creds), grpc.WithDefaultCallOptions( grpc.MaxCallRecvMsgSize(150 * 1024 * 1024), // 150MB max ), } // Connect to server fmt.Println("🔌 Connecting to gRPC server...") conn, err := grpc.NewClient(endpoint, opts...) if err != nil { log.Fatalf("❌ Failed to connect: %v", err) } defer conn.Close() // Create the client using generated code client := pb.NewHyperliquidL1GatewayClient(conn) fmt.Println("✅ Connected successfully!\n") // Create context with API key ctx := metadata.AppendToOutgoingContext(context.Background(), "x-api-key", apiKey) // Create request - empty Position means latest/current fills request := &pb.Position{} fmt.Println("📥 Starting fills stream...") fmt.Println("Press Ctrl+C to stop streaming\n") // Start streaming fills stream, err := client.StreamFills(ctx, request) if err != nil { log.Fatalf("❌ Failed to start stream: %v", err) } fillCount := 0 for { response, err := stream.Recv() if err != nil { fmt.Printf("❌ Stream ended: %v\n", err) break } fillCount++ fmt.Printf("\n===== FILLS #%d =====\n", fillCount) fmt.Printf("📦 Response size: %d bytes\n", len(response.Data)) // Process each fill processFills(response.Data, fillCount) fmt.Println("\n" + strings.Repeat("─", 50)) } fmt.Printf("\n📊 Total fill batches received: %d\n", fillCount) } func processFills(data []byte, batchNum int) { // Parse JSON var fills interface{} if err := json.Unmarshal(data, &fills); err != nil { fmt.Printf("❌ Failed to parse JSON: %v\n", err) fmt.Printf("Raw data (first 200 bytes): %.200s\n", data) return } fmt.Printf("🔄 FILLS BATCH #%d DETAILS\n", batchNum) fmt.Println("=========================") // Pretty print the fills data prettyJSON, err := json.MarshalIndent(fills, "", " ") if err != nil { fmt.Printf("Data: %v\n", fills) } else { // Limit output to first 500 chars for readability output := string(prettyJSON) if len(output) > 500 { output = output[:500] + "..." } fmt.Printf("%s\n", output) } } func main() { streamFills() } ``` ```python from datetime import datetime from dotenv import load_dotenv # Load environment variables load_dotenv() def stream_fills(): endpoint = os.getenv('HYPERLIQUID_ENDPOINT') api_key = os.getenv('API_KEY') if not endpoint: print("Error: HYPERLIQUID_ENDPOINT environment variable is required.") print("Please create a .env file from .env.example and set your endpoint.") sys.exit(1) if not api_key: print("Error: API_KEY environment variable is required.") print("Please set your API key in the .env file.") sys.exit(1) print('🚀 Hyperliquid Python gRPC Client - Stream Fills') print('================================================') print(f'📡 Endpoint: {endpoint}\n') # Create SSL credentials credentials = grpc.ssl_channel_credentials() # Create channel with options options = [ ('grpc.max_receive_message_length', 150 * 1024 * 1024), # 150MB max ] # Prepare metadata with API key metadata = [('x-api-key', api_key)] print('🔌 Connecting to gRPC server...') with grpc.secure_channel(endpoint, credentials, options=options) as channel: # Create client stub client = hyperliquid_pb2_grpc.HyperliquidL1GatewayStub(channel) print('✅ Connected successfully!\n') # Create request - empty Position means latest/current fills request = hyperliquid_pb2.Position() print('📥 Starting fills stream...') print('Press Ctrl+C to stop streaming\n') fill_count = 0 # Set up signal handler for graceful shutdown def signal_handler(sig, frame): print('\n🛑 Stopping stream...') print(f'📊 Total fill batches received: {fill_count}') sys.exit(0) signal.signal(signal.SIGINT, signal_handler) try: # Start streaming fills with metadata for response in client.StreamFills(request, metadata=metadata): fill_count += 1 print(f'\n===== FILLS #{fill_count} =====') print(f'📦 Response size: {len(response.data)} bytes') # Process each fill batch process_fills(response.data, fill_count) print('\n' + '─' * 50) except grpc.RpcError as e: print(f'❌ Stream error: {e}') except KeyboardInterrupt: print('\n🛑 Stopping stream...') print(f'\n📊 Total fill batches received: {fill_count}') def process_fills(data, batch_num): try: # Parse JSON fills = json.loads(data.decode('utf-8')) print(f'🔄 FILLS BATCH #{batch_num} DETAILS') print('=========================') # Pretty print (limited output) output = json.dumps(fills, indent=2) if len(output) > 500: output = output[:500] + '...' print(output) except json.JSONDecodeError as e: print(f'❌ Failed to parse JSON: {e}') print(f'Raw data (first 200 bytes): {data[:200]}') except Exception as e: print(f'❌ Error processing fills: {e}') if __name__ == '__main__': stream_fills() ``` ```javascript const grpc = require('@grpc/grpc-js'); const protoLoader = require('@grpc/proto-loader'); const path = require('path'); require('dotenv').config(); // Load proto file const PROTO_PATH = path.join(__dirname, 'v2.proto'); const packageDefinition = protoLoader.loadSync(PROTO_PATH, { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true }); const proto = grpc.loadPackageDefinition(packageDefinition); // Main function async function streamFills() { const endpoint = process.env.HYPERLIQUID_ENDPOINT; const apiKey = process.env.API_KEY; if (!endpoint) { console.error('Error: HYPERLIQUID_ENDPOINT environment variable is required.'); console.error('Please create a .env file from .env.example and set your endpoint.'); process.exit(1); } if (!apiKey) { console.error('Error: API_KEY environment variable is required.'); console.error('Please set your API key in the .env file.'); process.exit(1); } console.log('🚀 Hyperliquid Node.js gRPC Client - Stream Fills'); console.log('================================================='); console.log(`📡 Endpoint: ${endpoint}\n`); // Create metadata with API key const metadata = new grpc.Metadata(); metadata.add('x-api-key', apiKey); // Create client with SSL credentials and 150MB message size limit const client = new proto.hyperliquid_l1_gateway.v2.HyperliquidL1Gateway( endpoint, grpc.credentials.createSsl(), { 'grpc.max_receive_message_length': 150 * 1024 * 1024 } ); console.log('📥 Starting fills stream...'); console.log('Press Ctrl+C to stop streaming\n'); // Make the gRPC call - empty Position for latest const stream = client.StreamFills({}, metadata); let fillCount = 0; stream.on('data', (data) => { fillCount++; try { const fills = JSON.parse(data.data); console.log(`\n===== FILLS #${fillCount} =====`); console.log(`📦 Response size: ${data.data.length} bytes`); // Process each fill batch processFills(fills, fillCount); console.log('\n' + '─'.repeat(50)); } catch (error) { console.error(`❌ Failed to parse message #${fillCount}:`, error.message); } }); stream.on('error', (error) => { console.error('❌ Stream error:', error.message); }); stream.on('end', () => { console.log('Stream ended'); console.log(`\n📊 Total fill batches received: ${fillCount}`); }); } function processFills(fills, batchNum) { console.log(`🔄 FILLS BATCH #${batchNum} DETAILS`); console.log('========================='); // Pretty print (limited output) let output = JSON.stringify(fills, null, 2); if (output.length > 500) { output = output.substring(0, 500) + '...'; } console.log(output); } // Run it streamFills(); ``` ## Common Use Cases ### 1. Trade Execution Tracker ```javascript class TradeExecutionTracker { constructor(streamManager) { this.streamManager = streamManager; this.executedTrades = new Map(); streamManager.on('fill', (fillData) => { this.processFill(fillData); }); } processFill(fillData) { // Track each fill by order ID const orderId = fillData.oid; if (!this.executedTrades.has(orderId)) { this.executedTrades.set(orderId, { orderId, fills: [], totalFilled: 0, avgPrice: 0 }); } const trade = this.executedTrades.get(orderId); trade.fills.push(fillData); trade.totalFilled += parseFloat(fillData.sz); // Recalculate average price const totalValue = trade.fills.reduce( (sum, f) => sum + parseFloat(f.px) * parseFloat(f.sz), 0 ); trade.avgPrice = totalValue / trade.totalFilled; console.log(`Order ${orderId}: Filled ${trade.totalFilled} @ avg ${trade.avgPrice}`); } } ``` ### 2. Fill Rate Monitor ```python class FillRateMonitor: def __init__(self): self.fills_per_minute = [] self.current_minute_fills = 0 self.last_minute = None def record_fill(self, fill_data): """Record a fill and track rates""" from datetime import datetime current_minute = datetime.now().replace(second=0, microsecond=0) if self.last_minute != current_minute: if self.last_minute is not None: self.fills_per_minute.append({ 'minute': self.last_minute, 'count': self.current_minute_fills }) self.last_minute = current_minute self.current_minute_fills = 0 self.current_minute_fills += 1 def get_average_rate(self, minutes=5): """Get average fills per minute over last N minutes""" recent = self.fills_per_minute[-minutes:] if not recent: return 0 return sum(r['count'] for r in recent) / len(recent) ``` ### 3. Position Reconciliation ```go type PositionReconciler struct { client pb.HyperliquidL1GatewayClient positions map[string]float64 } func (pr *PositionReconciler) ReconcileFills(ctx context.Context) { stream, err := pr.client.StreamFills(ctx, &pb.Position{}) if err != nil { log.Fatal(err) } for { fill, err := stream.Recv() if err != nil { log.Printf("Stream error: %v", err) return } pr.updatePosition(fill.Data) } } func (pr *PositionReconciler) updatePosition(data []byte) { var fillData map[string]interface{} json.Unmarshal(data, &fillData) // Extract fill details and update position if coin, ok := fillData["coin"].(string); ok { size, _ := fillData["sz"].(float64) side, _ := fillData["side"].(string) if side == "B" { pr.positions[coin] += size } else { pr.positions[coin] -= size } log.Printf("Position %s: %f", coin, pr.positions[coin]) } } ``` ## Error Handling and Reconnection ```javascript class RobustFillStreamer { constructor(endpoint) { this.endpoint = endpoint; this.maxRetries = 5; this.retryDelay = 1000; this.currentRetries = 0; } async startStreamWithRetry() { while (this.currentRetries < this.maxRetries) { try { await this.startStream(); this.currentRetries = 0; this.retryDelay = 1000; } catch (error) { this.currentRetries++; console.error(`Stream attempt ${this.currentRetries} failed:`, error.message); if (this.currentRetries >= this.maxRetries) { throw new Error('Max retry attempts exceeded'); } // Exponential backoff await this.sleep(this.retryDelay); this.retryDelay *= 2; } } } sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } } ``` ## Best Practices 1. **Connection Management**: Implement robust reconnection logic with exponential backoff 2. **Memory Management**: Use bounded collections for storing recent fills to prevent memory leaks 3. **Performance**: Process fills asynchronously to avoid blocking the stream 4. **Monitoring**: Track stream health and fill rates 5. **Error Recovery**: Handle various error types (network, parsing, processing) gracefully 6. **Resource Cleanup**: Properly close streams and connections on shutdown ## Current Limitations - **Historical Data**: Cannot stream from historical timestamps; only real-time streaming available - **Data Retention**: Node maintains only 24 hours of historical fill data - **Backpressure**: High-volume periods may require careful handling to avoid overwhelming downstream systems ## Resources - **[GitHub: gRPC Code Examples](https://github.com/dwellir-public/gRPC-code-examples)** - Complete working examples - **[Copy Trading Bot](https://github.com/dwellir-public/gRPC-code-examples/tree/main/copy-trading-bot)** - Uses `StreamFills` to mirror trades in real-time *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Hyperliquid gRPC documentation](./grpc).* --- ## StreamOrderbookSnapshots - Real-time Order Book Streaming # StreamOrderbookSnapshots Stream continuous order book snapshots starting from a position, providing real-time access to market depth and liquidity data on Hyperliquid. :::tip Full Code Examples Clone our [gRPC Code Examples Repository](https://github.com/dwellir-public/gRPC-code-examples) for complete, runnable implementations in Go, Python, and Node.js. ::: ## When to Use This Method `StreamOrderbookSnapshots` is essential for: - **Market Making** - Monitor bid/ask spreads and adjust quotes in real-time - **Trading Algorithms** - Access live order book data for execution strategies - **Market Analysis** - Track liquidity and depth changes over time - **Risk Management** - Monitor market conditions and liquidity availability ## Method Signature ```protobuf rpc StreamOrderbookSnapshots(Position) returns (stream OrderBookSnapshot) {} ``` ## Request Message ```protobuf message Position { // Leave all fields unset or zero to target the latest data. oneof position { int64 timestamp_ms = 1; // ms since Unix epoch, inclusive int64 block_height = 2; // block height, inclusive } } ``` The `Position` message allows flexible stream starting points: - **timestamp_ms**: Start streaming from a specific time (milliseconds since Unix epoch) - **block_height**: Start streaming from a specific block height - **Empty/zero**: Start streaming from the latest order book snapshot ## Response Stream ```protobuf message OrderBookSnapshot { // JSON-encoded Hyperliquid order book snapshot. bytes data = 1; } ``` The `data` field contains a JSON-encoded order book snapshot with: - Bid and ask levels with price, size, and order count - Trading pair symbol - Timestamp of the snapshot ### Data Structure ```json { "coin": "string", // Trading pair symbol (e.g., "@1" for ETH) "time": 1757672867000, // Unix timestamp in milliseconds "levels": [ [ // Bid levels (index 0) { "px": "18.414", // Price level "sz": "100.0", // Total size at this level "n": 1 // Number of orders at this level } ], [ // Ask levels (index 1) { "px": "18.515", // Price level "sz": "50.5", // Total size at this level "n": 2 // Number of orders at this level } ] ] } ``` ## Implementation Examples ```go package main "context" "encoding/json" "fmt" "log" "os" "strings" pb "hyperliquid-grpc-client/api/v2" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/metadata" ) type OrderBookLevel struct { Price string `json:"px"` Size string `json:"sz"` Orders int `json:"n"` } type OrderBookData struct { Coin string `json:"coin"` Time float64 `json:"time"` Levels [][]OrderBookLevel `json:"levels"` } func streamOrderbookSnapshots() { endpoint := os.Getenv("HYPERLIQUID_ENDPOINT") apiKey := os.Getenv("API_KEY") fmt.Println("🚀 Hyperliquid Go gRPC Client - Stream Order Book Snapshots") fmt.Println("============================================================") fmt.Printf("📡 Endpoint: %s\n\n", endpoint) // Set up TLS connection creds := credentials.NewTLS(nil) // Connection options opts := []grpc.DialOption{ grpc.WithTransportCredentials(creds), grpc.WithDefaultCallOptions( grpc.MaxCallRecvMsgSize(150 * 1024 * 1024), // 150MB max ), } // Connect to server fmt.Println("🔌 Connecting to gRPC server...") conn, err := grpc.NewClient(endpoint, opts...) if err != nil { log.Fatalf("❌ Failed to connect: %v", err) } defer conn.Close() // Create the client using generated code client := pb.NewHyperliquidL1GatewayClient(conn) fmt.Println("✅ Connected successfully!\n") // Create context with API key ctx := metadata.AppendToOutgoingContext(context.Background(), "x-api-key", apiKey) // Create request - empty Position means latest/current snapshots request := &pb.Position{} fmt.Println("📥 Starting order book snapshots stream...") fmt.Println("Press Ctrl+C to stop streaming\n") // Start streaming order book snapshots stream, err := client.StreamOrderbookSnapshots(ctx, request) if err != nil { log.Fatalf("❌ Failed to start stream: %v", err) } snapshotCount := 0 for { response, err := stream.Recv() if err != nil { fmt.Printf("❌ Stream ended: %v\n", err) break } snapshotCount++ fmt.Printf("\n===== SNAPSHOT #%d =====\n", snapshotCount) fmt.Printf("📦 Response size: %d bytes\n", len(response.Data)) // Process each snapshot processOrderBookSnapshot(response.Data, snapshotCount) fmt.Println("\n" + strings.Repeat("─", 50)) } fmt.Printf("\n📊 Total snapshots received: %d\n", snapshotCount) } func processOrderBookSnapshot(data []byte, snapshotNum int) { // Parse JSON var orderBook OrderBookData if err := json.Unmarshal(data, &orderBook); err != nil { fmt.Printf("❌ Failed to parse JSON: %v\n", err) fmt.Printf("Raw data (first 200 bytes): %.200s\n", data) return } fmt.Printf("📊 ORDER BOOK SNAPSHOT #%d\n", snapshotNum) fmt.Println("==========================") fmt.Printf("🪙 Coin: %s\n", orderBook.Coin) if len(orderBook.Levels) >= 2 { bids := orderBook.Levels[0] asks := orderBook.Levels[1] fmt.Printf("📋 Bids: %d levels\n", len(bids)) fmt.Printf("📋 Asks: %d levels\n", len(asks)) // Display best bid and ask if len(bids) > 0 && len(asks) > 0 { fmt.Printf("\n💰 Best Bid: %s @ %s (Orders: %d)\n", bids[0].Size, bids[0].Price, bids[0].Orders) fmt.Printf("💰 Best Ask: %s @ %s (Orders: %d)\n", asks[0].Size, asks[0].Price, asks[0].Orders) } } } func main() { streamOrderbookSnapshots() } ``` ```python from datetime import datetime from dotenv import load_dotenv # Load environment variables load_dotenv() def stream_orderbook_snapshots(): endpoint = os.getenv('HYPERLIQUID_ENDPOINT') api_key = os.getenv('API_KEY') if not endpoint: print("Error: HYPERLIQUID_ENDPOINT environment variable is required.") print("Please create a .env file from .env.example and set your endpoint.") sys.exit(1) if not api_key: print("Error: API_KEY environment variable is required.") print("Please set your API key in the .env file.") sys.exit(1) print('🚀 Hyperliquid Python gRPC Client - Stream Order Book Snapshots') print('================================================================') print(f'📡 Endpoint: {endpoint}\n') # Create SSL credentials credentials = grpc.ssl_channel_credentials() # Create channel with options options = [ ('grpc.max_receive_message_length', 150 * 1024 * 1024), # 150MB max ] # Prepare metadata with API key metadata = [('x-api-key', api_key)] print('🔌 Connecting to gRPC server...') with grpc.secure_channel(endpoint, credentials, options=options) as channel: # Create client stub client = hyperliquid_pb2_grpc.HyperliquidL1GatewayStub(channel) print('✅ Connected successfully!\n') # Create request - empty Position means latest/current snapshots request = hyperliquid_pb2.Position() print('📥 Starting order book snapshots stream...') print('Press Ctrl+C to stop streaming\n') snapshot_count = 0 # Set up signal handler for graceful shutdown def signal_handler(sig, frame): print('\n🛑 Stopping stream...') print(f'📊 Total snapshots received: {snapshot_count}') sys.exit(0) signal.signal(signal.SIGINT, signal_handler) try: # Start streaming order book snapshots with metadata for response in client.StreamOrderbookSnapshots(request, metadata=metadata): snapshot_count += 1 print(f'\n===== SNAPSHOT #{snapshot_count} =====') print(f'📦 Response size: {len(response.data)} bytes') # Process each snapshot process_orderbook_snapshot(response.data, snapshot_count) print('\n' + '─' * 50) except grpc.RpcError as e: print(f'❌ Stream error: {e}') except KeyboardInterrupt: print('\n🛑 Stopping stream...') print(f'\n📊 Total snapshots received: {snapshot_count}') def process_orderbook_snapshot(data, snapshot_num): try: # Parse JSON order_book = json.loads(data.decode('utf-8')) print(f'📊 ORDER BOOK SNAPSHOT #{snapshot_num}') print('==========================') # Display coin/symbol if 'coin' in order_book: print(f'🪙 Coin: {order_book["coin"]}') # Display timestamp if 'time' in order_book: timestamp = order_book['time'] dt = datetime.fromtimestamp(timestamp / 1000) print(f'⏰ Time: {dt.strftime("%Y-%m-%d %H:%M:%S UTC")}') # Display levels if 'levels' in order_book and len(order_book['levels']) >= 2: bids = order_book['levels'][0] asks = order_book['levels'][1] print(f'\n📋 Bids: {len(bids)} levels') print(f'📋 Asks: {len(asks)} levels') # Display best bid and ask if len(bids) > 0 and len(asks) > 0: best_bid = bids[0] best_ask = asks[0] print(f'\n💰 Best Bid: {best_bid["sz"]} @ {best_bid["px"]} (Orders: {best_bid["n"]})') print(f'💰 Best Ask: {best_ask["sz"]} @ {best_ask["px"]} (Orders: {best_ask["n"]})') # Calculate spread bid_price = float(best_bid['px']) ask_price = float(best_ask['px']) spread = ask_price - bid_price spread_bps = (spread / bid_price) * 10000 print(f'\n📊 Spread: {spread:.6f} ({spread_bps:.2f} bps)') except json.JSONDecodeError as e: print(f'❌ Failed to parse JSON: {e}') print(f'Raw data (first 200 bytes): {data[:200]}') except Exception as e: print(f'❌ Error processing snapshot: {e}') if __name__ == '__main__': stream_orderbook_snapshots() ``` ```javascript const grpc = require('@grpc/grpc-js'); const protoLoader = require('@grpc/proto-loader'); const path = require('path'); require('dotenv').config(); // Load proto file const PROTO_PATH = path.join(__dirname, 'v2.proto'); const packageDefinition = protoLoader.loadSync(PROTO_PATH, { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true }); const proto = grpc.loadPackageDefinition(packageDefinition); // Main function async function streamOrderbookSnapshots() { const endpoint = process.env.HYPERLIQUID_ENDPOINT; const apiKey = process.env.API_KEY; if (!endpoint) { console.error('Error: HYPERLIQUID_ENDPOINT environment variable is required.'); console.error('Please create a .env file from .env.example and set your endpoint.'); process.exit(1); } if (!apiKey) { console.error('Error: API_KEY environment variable is required.'); console.error('Please set your API key in the .env file.'); process.exit(1); } console.log('🚀 Hyperliquid Node.js gRPC Client - Stream Order Book Snapshots'); console.log('================================================================='); console.log(`📡 Endpoint: ${endpoint}\n`); // Create metadata with API key const metadata = new grpc.Metadata(); metadata.add('x-api-key', apiKey); // Create client with SSL credentials and 150MB message size limit const client = new proto.hyperliquid_l1_gateway.v2.HyperliquidL1Gateway( endpoint, grpc.credentials.createSsl(), { 'grpc.max_receive_message_length': 150 * 1024 * 1024 } ); console.log('📥 Starting order book snapshots stream...'); console.log('Press Ctrl+C to stop streaming\n'); // Make the gRPC call - empty Position for latest const stream = client.StreamOrderbookSnapshots({}, metadata); let snapshotCount = 0; stream.on('data', (data) => { snapshotCount++; try { const orderBook = JSON.parse(data.data); console.log(`\n===== SNAPSHOT #${snapshotCount} =====`); console.log(`📦 Response size: ${data.data.length} bytes`); // Process each snapshot processOrderbookSnapshot(orderBook, snapshotCount); console.log('\n' + '─'.repeat(50)); } catch (error) { console.error(`❌ Failed to parse message #${snapshotCount}:`, error.message); } }); stream.on('error', (error) => { console.error('❌ Stream error:', error.message); }); stream.on('end', () => { console.log('Stream ended'); console.log(`\n📊 Total snapshots received: ${snapshotCount}`); }); } function processOrderbookSnapshot(orderBook, snapshotNum) { console.log(`📊 ORDER BOOK SNAPSHOT #${snapshotNum}`); console.log('=========================='); // Display coin/symbol if (orderBook.coin) { console.log(`🪙 Coin: ${orderBook.coin}`); } // Display timestamp if (orderBook.time) { const date = new Date(orderBook.time); console.log(`⏰ Time: ${date.toISOString()}`); } // Display levels const levels = orderBook.levels || []; if (levels.length >= 2) { const bids = levels[0]; const asks = levels[1]; console.log(`\n📋 Bids: ${bids.length} levels`); console.log(`📋 Asks: ${asks.length} levels`); // Display best bid and ask if (bids.length > 0 && asks.length > 0) { const bestBid = bids[0]; const bestAsk = asks[0]; console.log(`\n💰 Best Bid: ${bestBid.sz} @ ${bestBid.px} (Orders: ${bestBid.n})`); console.log(`💰 Best Ask: ${bestAsk.sz} @ ${bestAsk.px} (Orders: ${bestAsk.n})`); // Calculate spread const bidPrice = parseFloat(bestBid.px); const askPrice = parseFloat(bestAsk.px); const spread = askPrice - bidPrice; const spreadBps = (spread / bidPrice) * 10000; console.log(`\n📊 Spread: ${spread.toFixed(6)} (${spreadBps.toFixed(2)} bps)`); } } } // Run it streamOrderbookSnapshots(); ``` ## Common Use Cases ### 1. Real-time Market Making ```javascript class MarketMaker { constructor(streamManager) { this.streamManager = streamManager; this.currentSpread = null; this.quotesActive = false; streamManager.on('orderbook', (snapshot) => { this.updateQuotes(snapshot); }); } updateQuotes(snapshot) { const levels = snapshot.levels || []; if (levels.length < 2) return; const bids = levels[0]; const asks = levels[1]; if (bids.length === 0 || asks.length === 0) return; const bestBid = parseFloat(bids[0].px); const bestAsk = parseFloat(asks[0].px); const midPrice = (bestBid + bestAsk) / 2; const spread = bestAsk - bestBid; // Calculate new quote prices const targetSpread = Math.max(spread * 0.9, 0.001); const newBid = midPrice - (targetSpread / 2); const newAsk = midPrice + (targetSpread / 2); console.log(`Mid: ${midPrice}, Spread: ${spread}, Quotes: ${newBid}/${newAsk}`); // Update quotes if spread has changed significantly if (this.shouldUpdateQuotes(newBid, newAsk)) { this.sendQuotes(newBid, newAsk); } } shouldUpdateQuotes(newBid, newAsk) { // Implement quote update logic based on threshold return true; } sendQuotes(bid, ask) { // Send quote updates to exchange console.log(`Sending quotes: ${bid} / ${ask}`); } } ``` ### 2. Liquidity Depth Monitor ```python class LiquidityMonitor: def __init__(self): self.depth_history = [] self.alerts_threshold = 0.2 # 20% depth change def analyze_depth(self, snapshot): """Analyze order book depth and detect significant changes""" levels = snapshot.get('levels', []) if len(levels) < 2: return None bids = levels[0] asks = levels[1] # Calculate depth at different price levels bid_depth_1pct = self.calculate_depth_at_percent(bids, 0.01) ask_depth_1pct = self.calculate_depth_at_percent(asks, 0.01) depth_data = { 'timestamp': snapshot.get('time'), 'coin': snapshot.get('coin'), 'bid_depth_1pct': bid_depth_1pct, 'ask_depth_1pct': ask_depth_1pct, 'total_depth': bid_depth_1pct + ask_depth_1pct, 'imbalance': (bid_depth_1pct - ask_depth_1pct) / (bid_depth_1pct + ask_depth_1pct) } self.check_for_alerts(depth_data) self.depth_history.append(depth_data) return depth_data def calculate_depth_at_percent(self, levels, percent): """Calculate total depth within X% of best price""" if not levels: return 0 best_price = float(levels[0]['px']) threshold = best_price * percent total_depth = 0 for level in levels: price = float(level['px']) if abs(price - best_price) <= threshold: total_depth += float(level['sz']) else: break return total_depth def check_for_alerts(self, current_depth): """Check for significant depth changes""" if len(self.depth_history) < 2: return prev_depth = self.depth_history[-1] change = abs(current_depth['total_depth'] - prev_depth['total_depth']) change_pct = change / prev_depth['total_depth'] if prev_depth['total_depth'] > 0 else 0 if change_pct > self.alerts_threshold: print(f"⚠️ Significant depth change: {change_pct:.1%}") ``` ### 3. Spread Analytics ```go type SpreadAnalyzer struct { client pb.HyperliquidL1GatewayClient spreads []SpreadData } type SpreadData struct { Timestamp int64 BestBid float64 BestAsk float64 Spread float64 SpreadBps float64 } func (sa *SpreadAnalyzer) AnalyzeSpreads(ctx context.Context) { stream, err := sa.client.StreamOrderbookSnapshots(ctx, &pb.Position{}) if err != nil { log.Fatal(err) } for { snapshot, err := stream.Recv() if err != nil { log.Printf("Stream error: %v", err) return } sa.processSnapshot(snapshot.Data) } } func (sa *SpreadAnalyzer) processSnapshot(data []byte) { var orderBook map[string]interface{} json.Unmarshal(data, &orderBook) levels, ok := orderBook["levels"].([]interface{}) if !ok || len(levels) < 2 { return } bids := levels[0].([]interface{}) asks := levels[1].([]interface{}) if len(bids) == 0 || len(asks) == 0 { return } bestBid := parseLevel(bids[0]) bestAsk := parseLevel(asks[0]) spread := bestAsk.Price - bestBid.Price spreadBps := (spread / bestBid.Price) * 10000 spreadData := SpreadData{ Timestamp: time.Now().Unix(), BestBid: bestBid.Price, BestAsk: bestAsk.Price, Spread: spread, SpreadBps: spreadBps, } sa.spreads = append(sa.spreads, spreadData) log.Printf("Spread: %.6f (%.2f bps)", spread, spreadBps) } ``` ## Error Handling and Reconnection ```javascript class RobustOrderbookStreamer { constructor(endpoint) { this.endpoint = endpoint; this.maxRetries = 5; this.retryDelay = 1000; this.currentRetries = 0; } async startStreamWithRetry() { while (this.currentRetries < this.maxRetries) { try { await this.startStream(); this.currentRetries = 0; this.retryDelay = 1000; } catch (error) { this.currentRetries++; console.error(`Stream attempt ${this.currentRetries} failed:`, error.message); if (this.currentRetries >= this.maxRetries) { throw new Error('Max retry attempts exceeded'); } // Exponential backoff await this.sleep(this.retryDelay); this.retryDelay *= 2; } } } sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } } ``` ## Best Practices 1. **Connection Management**: Implement robust reconnection logic with exponential backoff 2. **Memory Management**: Use bounded collections for storing historical snapshots 3. **Performance**: Process snapshots asynchronously to avoid blocking the stream 4. **Monitoring**: Track stream health and snapshot rates 5. **Error Recovery**: Handle various error types gracefully 6. **Resource Cleanup**: Properly close streams and connections on shutdown ## Current Limitations - **Historical Data**: Cannot stream from historical timestamps; only real-time streaming available - **Data Retention**: Node maintains only 24 hours of historical order book data - **Backpressure**: High-volume periods may require careful handling to avoid overwhelming downstream systems ## Resources - **[GitHub: gRPC Code Examples](https://github.com/dwellir-public/gRPC-code-examples)** - Complete working examples - **[Copy Trading Bot](https://github.com/dwellir-public/gRPC-code-examples/tree/main/copy-trading-bot)** - Production-ready trading bot example *Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Hyperliquid gRPC documentation](./grpc).* --- ## NetChildVaultPositionsAction - Net Child Vault Positions # NetChildVaultPositionsAction Net positions across child vaults for consolidated risk management and position reconciliation. ## Sample Data ```json { "signature": { "r": "0xd84c596af3ebf2fed0a6a73a04bf11c4602534e53bca68175f8036f5d087052a", "s": "0x7d00b1602687f3e7143559df0f7a8dd7b37dce46d7e463dcb49867df613a30c6", "v": 28 }, "action": { "type": "NetChildVaultPositionsAction", "childVaultAddresses": [ "0x010461c14e146ac35fe42271bdc1134ee31c703a", "0x31ca8395cf837de08b24da3f660e77761dfb974b" ], "assets": [22, 34, 52] }, "nonce": 1768146734567, "vaultAddress": "0xdfc24b077bc1425ad1dea75bcb6f8158e10df303" } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x115e4ffc86b151e312d8043326460402016700e221b470b5b526fb4f45b52bcd) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"NetChildVaultPositionsAction"` | | `childVaultAddresses` | array | Child vault addresses to net | | `assets` | array | Asset indices to net positions for | ## Use Cases ### Vault Position Management Track position netting across child vaults: ```python def process_NetChildVaultPositionsAction(action): children = action.get('childVaultAddresses', []) assets = action.get('assets', []) print(f"Netting {len(assets)} assets across {len(children)} vaults") ``` ## Related Action Types - [vaultTransfer](./vaultTransfer) - Vault deposits/withdrawals --- ## SetGlobalAction - Set Global Parameters # SetGlobalAction Set global system parameters including oracle prices and market configurations. ## Sample Data ```json { "signature": { "r": "0x92258565da730223bbd076688bcdabb5826de44527ee6c407688aa376e3ff8ef", "s": "0x7783859200389c21fe5600f6cdb1ed8477d5c6b5da3ebd818b7d1494a9579c9b", "v": 28 }, "action": { "type": "SetGlobalAction", "pxs": [ ["90802", "90762"], ["3114.6", "3113.3"], ["2.5905", "2.5878"] ], "externalPerpPxs": [ ["0G", "0.87235"], ["2Z", "0.11722"], ["AAVE", "166.5"] ], "usdtUsdcPx": "0.9989012086704624", "nativePx": "24.4025" }, "nonce": 1768146734571 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x1aaf367e0079ae3e1c28043326350b0000ea4e639b7ccd10be77e1d0bf7d8828) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"SetGlobalAction"` | | `pxs` | array | Price updates [bid, ask] for each market | ## Use Cases ### Oracle Price Monitoring Track oracle price updates: ```python def process_SetGlobalAction(action): prices = action.get('pxs', []) print(f"Oracle update: {len(prices)} markets") ``` ## Related Action Types - [noop](./noop) - No-operation action - [perpDeploy](./perpDeploy) - Market deployment --- ## ValidatorSignWithdrawalAction - Validator Withdrawal Signatures # ValidatorSignWithdrawalAction Validators sign withdrawal transactions to authorize bridge transfers to external addresses. ## Sample Data ```json { "signature": { "r": "0x62a3295228b569f9a08d3776a12bbb2bd56e75153c3dadefda97e84c1be87097", "s": "0x5b7d385d6e32cbb89ed5fad01877ca78bf562e1333ae16fb1bcb7eca946ed7c6", "v": 28 }, "action": { "type": "ValidatorSignWithdrawalAction", "user": "0x6275c773fa0d1fd29e39322afee475827171c26b", "destination": "0xc2c9981b9061e533affaaf03105c561154f1ec84", "usd": 15494002, "nonce": 1768146916924000, "signature": { "r": "0x1e63066eff19a658f69813bf33d081f856846c684e1488b1d021ec5419ba2f0c", "s": "0x8a56ce8e4ff9f0115fdef290e6ea2cc4364d9d0faa406a255a8f13df936a16d", "v": 28 } }, "nonce": 1768146734592 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0xd0629981833e39c6d1dc0433264532010900b1671e315898742b44d4423213b1) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"ValidatorSignWithdrawalAction"` | | `user` | string | User requesting withdrawal | | `destination` | string | External destination address | | `nonce` | number | Withdrawal nonce | | `usd` | number | Amount in raw units | ## Use Cases ### Withdrawal Authorization Tracking Monitor validator withdrawal signatures: ```python def process_ValidatorSignWithdrawalAction(action): user = action.get('user') amount = action.get('usd') / 1_000_000 print(f"Withdrawal signed: ${amount:,.2f} for {user[:10]}...") ``` ## Related Action Types - [withdraw3](./withdraw3) - Initiate withdrawals - [VoteEthFinalizedWithdrawalAction](./VoteEthFinalizedWithdrawalAction) - Finalization votes --- ## VoteEthDepositAction - Validator Deposit Votes # VoteEthDepositAction Validators vote to confirm ETH deposit transactions from the bridge contract. This is part of the cross-chain consensus mechanism that secures deposits from Arbitrum to Hyperliquid. ## Sample Data ```json { "signature": { "r": "0x74e0218199716f8217518bcb72240de1c17ff6e6682fbacdd820e60c13ac0454", "s": "0x4a5a442f5dad771b48f3852b4d96cc561de2804b6c1853e8d1548015a732b89f", "v": 28 }, "action": { "type": "VoteEthDepositAction", "user": "0x09a8c041c8d966ddb20b2ea5b556ef0318365182", "usd": 90391034, "ethId": { "block_number": 420281244, "tx_index": 25, "event_type": "Deposit", "event_index": 0, "tx_hash": "0x107c5fc0f824b2993b28ade0560cb732b0f25df4a47a777c47be108c432ce933" } }, "nonce": 1768146734681 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x13362fd89699384714af043326473502016000be319c5719b6fedb2b559d1231) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"VoteEthDepositAction"` | | `user` | string | Address of the user who made the deposit | | `usd` | number | Deposit amount in raw units (6 decimals) | | `ethTxHash` | string | Transaction hash of the deposit on Arbitrum | ## Bridge Consensus Process 1. User deposits funds to bridge contract on Arbitrum 2. Validators observe the deposit transaction 3. Validators submit `VoteEthDepositAction` votes 4. Once threshold is reached, funds are credited on Hyperliquid ## Use Cases ### Bridge Monitoring Track deposit confirmations across the bridge: ```python def process_VoteEthDepositAction(action): user = action.get('user') amount = action.get('usd') / 1_000_000 eth_tx = action.get('ethTxHash') print(f"Deposit vote: ${amount:,.2f} for {user[:10]}... (tx: {eth_tx[:10]}...)") ``` ### Validator Activity Tracking Monitor which validators are actively participating in bridge consensus. ### Deposit Latency Analysis Track time from Arbitrum transaction to Hyperliquid credit. ## Related Action Types - [VoteEthFinalizedWithdrawalAction](./VoteEthFinalizedWithdrawalAction) - Withdrawal votes - [ValidatorSignWithdrawalAction](./ValidatorSignWithdrawalAction) - Withdrawal signatures - [voteAppHash](./voteAppHash) - Application state votes --- ## VoteEthFinalizedWithdrawalAction - Validator Withdrawal Votes # VoteEthFinalizedWithdrawalAction Validators vote to confirm that a withdrawal transaction has been finalized on Arbitrum. This completes the bridge withdrawal process. ## Sample Data ```json { "signature": { "r": "0x8e85e979af4151570ff20d1c17d380cd244f7b373df4082de4a271f2df8c2e3b", "s": "0x5855f07fcaf680d3213b3aea27c4b51cbfcd5681678a3b3264ad71a39d245c4c", "v": 28 }, "action": { "type": "VoteEthFinalizedWithdrawalAction", "user": "0xe095f4cc38ae81839c368a83ad906544aed36564", "destination": "0xe095f4cc38ae81839c368a83ad906544aed36564", "nonce": 1768146676227000, "usd": 15082681, "ethTxHash": "0xac1d8a6cea30fcce8527c823941239c621075ddcaebd8347ef8aa2df03659ea8" }, "nonce": 1768146734586 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x7aaa86d76798832d7c24043326280a0107009ebd029ba1ff1e73322a269c5d18) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"VoteEthFinalizedWithdrawalAction"` | | `user` | string | Address of the user who initiated the withdrawal | | `destination` | string | Destination address on Arbitrum | | `nonce` | number | Withdrawal nonce | | `usd` | number | Withdrawal amount in raw units (6 decimals) | | `ethTxHash` | string | Transaction hash of the withdrawal on Arbitrum | ## Withdrawal Finalization Process 1. User submits [withdraw3](./withdraw3) action 2. Validators sign the withdrawal ([ValidatorSignWithdrawalAction](./ValidatorSignWithdrawalAction)) 3. Bridge transaction executes on Arbitrum 4. Validators vote to confirm finalization (`VoteEthFinalizedWithdrawalAction`) 5. Withdrawal is marked complete ## Use Cases ### Withdrawal Completion Tracking Monitor withdrawal finalization: ```python def process_VoteEthFinalizedWithdrawalAction(action): user = action.get('user') destination = action.get('destination') amount = action.get('usd') / 1_000_000 print(f"Withdrawal finalized: ${amount:,.2f} from {user[:10]}... to {destination[:10]}...") ``` ### Bridge Health Monitoring Track withdrawal finalization rates and latencies. ### Validator Consensus Analysis Monitor validator participation in withdrawal confirmations. ## Related Action Types - [withdraw3](./withdraw3) - Initiate withdrawal - [ValidatorSignWithdrawalAction](./ValidatorSignWithdrawalAction) - Validator signs withdrawal - [VoteEthDepositAction](./VoteEthDepositAction) - Deposit votes --- ## agentEnableDexAbstraction - Agent DEX Abstraction # agentEnableDexAbstraction Enable DEX abstraction functionality for an agent wallet. ## Sample Data ```json { "signature": { "r": "0x2d58053666731bbc738cb5bafd19bb148a85248b19565bf72ab22599a00eaf51", "s": "0x1b7aae8cfa48af734057d0f886fd8b14b2d4a3e53df388f30901934ad3552453", "v": 28 }, "action": { "type": "agentEnableDexAbstraction" }, "nonce": 1768146926373 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0xd11ddee9a7be6badd297043326457f02015000cf42b18a7f74e68a3c66b24598) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"agentEnableDexAbstraction"` | ## Use Cases ### DEX Abstraction Tracking Monitor DEX abstraction enablement: ```python def process_agentEnableDexAbstraction_action(action): print("DEX abstraction enabled for agent") ``` ## Related Action Types - [approveAgent](./approveAgent) - Authorize agents - [userDexAbstraction](./userDexAbstraction) - User DEX settings --- ## approveAgent - Authorize API Wallets # approveAgent Authorize an API wallet (also called an agent) to sign transactions on behalf of the master account or its sub-accounts. This enables programmatic trading while keeping the master private key secure. ## Sample Data ```json { "signature": { "r": "0xa440cd8904dfbd812cb3669258413c6139c12dbc7083ea000b1f73e4ff4ef1e3", "s": "0x79c77f830c666018af5e13d229d8955e1e4f7fe89e225886cd9b8f638c2d8638", "v": 28 }, "action": { "type": "approveAgent", "signatureChainId": "0x2105", "hyperliquidChain": "Mainnet", "agentAddress": "0x9c0e10bb3ac3b461b2a24c4465ece3f343d6321a", "agentName": "DEFI_AGENT_3 valid_until 1768319711089", "nonce": 1768146911127 }, "nonce": 1768146911127 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0xe21c188afbddc331e39504332644bf0201a2007096d0e20385e4c3ddbad19d1c) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"approveAgent"` | | `signatureChainId` | string | Chain ID for EIP-712 signing (e.g., `"0xa4b1"` for Arbitrum) | | `hyperliquidChain` | string | Target chain: `"Mainnet"` or `"Testnet"` | | `agentAddress` | string | Ethereum address of the agent wallet to authorize | | `agentName` | string | Optional human-readable name for the agent | | `nonce` | number | Timestamp-based nonce for replay protection | ## Agent Naming Agents can be named or unnamed: - **Named agents**: Identified by `agentName`. Sending a new `approveAgent` with the same name replaces the previous agent. - **Unnamed agents**: No name specified. Only one unnamed agent can exist at a time. Common agent names include wallet integrations like `"rabby-mobile"`, `"metamask"`, or custom names for trading bots. ## Security Considerations - Agent wallets can only sign trading operations, not withdrawals - The master wallet must sign `approveAgent` actions directly - Once deregistered, an agent's nonce state may be pruned, potentially allowing replay of old signed actions - Generate new agent wallets rather than reusing addresses ## Use Cases ### Trading Bot Setup Detection Monitor when new trading bots or API integrations are authorized: ```python def process_approveAgent_action(action): agent_address = action.get('agentAddress') agent_name = action.get('agentName', 'unnamed') print(f"Agent authorized: {agent_name} ({agent_address})") ``` ### Wallet Integration Tracking Track adoption of different wallet providers by monitoring agent names. ### Security Monitoring Detect unauthorized agent approvals for accounts you're monitoring. ## Related Action Types - [approveBuilderFee](./approveBuilderFee) - Approve builder fee rates - [agentEnableDexAbstraction](./agentEnableDexAbstraction) - Enable DEX abstraction for agents --- ## approveBuilderFee - Authorize Builder Fees # approveBuilderFee Approve a maximum fee rate that a builder (DeFi application) can charge on trades executed on your behalf. Builder codes enable third-party applications to earn fees for order routing. ## Sample Data ```json { "signature": { "r": "0x819ad144d5c0c3d55a176f1b61ee61f2ad290f1b4cc2afb3944c2f70235a507d", "s": "0x2fea989745633804f70c5528c9258a89b3789bd99c6a03c6a1bd884cf5dc1b6b", "v": 28 }, "action": { "type": "approveBuilderFee", "signatureChainId": "0x66eee", "hyperliquidChain": "Mainnet", "maxFeeRate": "0.01%", "builder": "0x6530512a6c89c7cfcebc3ba7fcd9ada5f30827a6", "nonce": 1768146914155 }, "nonce": 1768146914155 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0xb044c574237def57b1be04332644d00202170059be710e29540d70c6e271c942) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"approveBuilderFee"` | | `maxFeeRate` | string | Maximum fee rate the builder can charge (e.g., `"0.001"` = 0.1%) | | `builder` | string | Ethereum address of the builder | | `nonce` | number | Timestamp-based nonce for replay protection | ## Fee Limits Hyperliquid enforces maximum builder fees: | Market Type | Maximum Builder Fee | |-------------|---------------------| | Perpetuals | 0.1% (10 basis points) | | Spot | 1% (100 basis points) | Builder codes do not apply to the buying side of spot trades. ## How Builder Fees Work 1. User approves a max fee rate for a builder address 2. Builder submits orders with a fee parameter: `{"b": address, "f": fee_bps}` 3. Fee is deducted from the user's trade and credited to the builder 4. Builders claim fees through the referral reward system ## Use Cases ### DeFi Integration Tracking Monitor which builders users are authorizing: ```python def process_approveBuilderFee_action(action): builder = action.get('builder') max_fee = float(action.get('maxFeeRate', 0)) print(f"Builder approved: {builder} with max fee {max_fee * 100}%") ``` ### Fee Analytics Track builder fee approvals to understand: - Popular trading interfaces - Average fee tolerance - Builder market share ### Competition Analysis Monitor which builders are gaining traction in the Hyperliquid ecosystem. ## Requirements - Builder must maintain at least 100 USDC in perps account value - Approval must be signed by the user's main wallet (not an agent) - Users can revoke permissions at any time ## Related Action Types - [approveAgent](./approveAgent) - Authorize API wallets - [order](./order) - Orders can include builder fee parameters --- ## batchModify - Atomic Order Modifications # batchModify Modify multiple existing orders atomically in a single transaction. All modifications either succeed together or fail together, preventing partial updates that could expose unwanted risk. ## Sample Data ```json { "signature": { "r": "0x34b4fe28e091111949d4925ae53c10c552e859523debcafa41048767ca88bace", "s": "0x48ecd1cd140ecb3d91bfac13410794e5cdbf3221fcf4371a293a737ffab4b3d0", "v": 28 }, "action": { "type": "batchModify", "modifies": [ { "oid": 291708433915, "order": { "a": 168, "b": false, "p": "0.03302", "s": "8000", "r": false, "t": { "limit": { "tif": "Alo" } } } } ] }, "nonce": 1768146913007 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x0fd9bc835e9ad5bc115304332644bd013800d468f99df48eb3a267d61d9eafa6) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"batchModify"` | | `modifies` | array | Array of modification objects | ### Modify Object Fields | Field | Type | Description | |-------|------|-------------| | `oid` | number | Order ID of the order to modify | | `order` | object | New order parameters (same structure as [order](./order) action) | ### Order Fields | Field | Type | Description | |-------|------|-------------| | `a` | number | Asset index | | `b` | boolean | Side: `true` for buy, `false` for sell | | `p` | string | New limit price | | `s` | string | New size | | `r` | boolean | Reduce-only flag | | `t` | object | Order type configuration | ## Atomicity Guarantee All modifications in a batch are executed atomically: - **All succeed**: Every order is updated - **All fail**: No orders are changed This prevents scenarios where partial updates could leave a market maker with imbalanced quotes. ## Use Cases ### Market Making Quote Updates Update bid and ask quotes together to maintain spread: ```python def process_batchModify_action(action): modifies = action.get('modifies', []) for mod in modifies: oid = mod['oid'] new_price = mod['order']['p'] new_size = mod['order']['s'] side = 'BUY' if mod['order']['b'] else 'SELL' print(f"Modified {oid}: {side} {new_size} @ {new_price}") ``` ### Spread Analysis Track how market makers adjust their quotes in response to price movements. ### Quote Refresh Rate Monitoring Measure how frequently market makers update their orders. ## Related Action Types - [order](./order) - Submit new orders - [modify](./modify) - Modify a single order - [cancel](./cancel) - Cancel orders --- ## borrowLend - Borrow and Lend Operations # borrowLend Borrow or lend assets through Hyperliquid's lending protocol. ## Sample Data ```json { "signature": { "r": "0x73fe72e61a4a23d81cfaf36a5a313266a7f990fe5782bbd210b2d3ef1cd3d1c0", "s": "0x2971452d4fae3a4d9275abf2ff8f4347c79b414e4f267d4ed05c13c28c029499", "v": 28 }, "action": { "type": "borrowLend", "operation": "supply", "token": 0, "amount": null }, "nonce": 1768147177757, "expiresAfter": 1768147188937 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0xf26a7955ad543bb5f3e4043326516a0201e3003b48575a88963324a86c5815a0) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"borrowLend"` | | `operation` | string | Operation type: `"deposit"`, `"withdraw"`, `"borrow"`, `"repay"` | | `token` | number | Token index | | `amount` | string | Amount | ## Use Cases ### Lending Activity Tracking Monitor lending operations: ```python def process_borrowLend_action(action): operation = action.get('operation') amount = action.get('amount') print(f"Lending: {operation} {amount}") ``` ## Related Action Types - [cDeposit](./cDeposit) - Collateral deposits - [cWithdraw](./cWithdraw) - Collateral withdrawals --- ## cDeposit - Deposit Collateral # cDeposit Deposit collateral for lending operations. ## Sample Data ```json { "signature": { "r": "0x3cbb47f1325d3c32177e669cd16b34c284382c9f14baaa6aab8378c2fd5f8a6", "s": "0x36c7707a539f353132f68255a1f96defb18fcc946af9e5fbb065104c0e537d6d", "v": 28 }, "action": { "type": "cDeposit", "signatureChainId": "0xa4b1", "hyperliquidChain": "Mainnet", "wei": 783683, "nonce": 1768148050528 }, "nonce": 1768148050528 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0xb3f882d51bab1525b5720433267c0b02022b00bab6ae33f757c12e27daaeef10) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"cDeposit"` | | `wei` | number | Amount in wei | ## Related Action Types - [cWithdraw](./cWithdraw) - Withdraw collateral - [borrowLend](./borrowLend) - Lending operations --- ## cWithdraw - Withdraw Collateral # cWithdraw Withdraw collateral from lending operations. ## Sample Data ```json { "signature": { "r": "0x8c864d08b6486f6c043c8359797175b14e2b3c6d61a82ceee9bc9cf2659a4be8", "s": "0x15835b21b87a1c0b55af90bda8f830aa128514b08960fcf757fd983be93cb128", "v": 27 }, "action": { "type": "cWithdraw", "signatureChainId": "0xa4b1", "hyperliquidChain": "Mainnet", "wei": 408761850, "nonce": 1768148277854 }, "nonce": 1768148277854 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0xb0468b0b9072c7dbb1c004332686e402040300f12b75e6ad540f365e4f76a1c6) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"cWithdraw"` | | `wei` | number | Amount in wei | ## Related Action Types - [cDeposit](./cDeposit) - Deposit collateral - [borrowLend](./borrowLend) - Lending operations --- ## cancel - Cancel Orders by ID # cancel Cancel one or more existing orders by their order ID (oid). This action removes orders from the order book before they can be filled. ## Sample Data ```json { "signature": { "r": "0xb7233b2b2b0cf0eb161f86319be9a86c197f860dbcbe4d4f189e5fa757137c89", "s": "0x65e5d0ffd58b0bf7ed168a8d1a9b6f8df6050c7acf24db588fb62f9390e9a2c3", "v": 27 }, "action": { "type": "cancel", "cancels": [ { "a": 0, "o": 291379970288 } ] }, "nonce": 1768146913376 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x13ca4a9463509042154404332645010202100079fe53af14b792f5e722546a2c) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"cancel"` | | `cancels` | array | Array of cancel requests | ### Cancel Object Fields | Field | Type | Description | |-------|------|-------------| | `a` | number | Asset index of the order to cancel | | `o` | number | Order ID (oid) to cancel | ### Optional Fields | Field | Type | Description | |-------|------|-------------| | `vaultAddress` | string | Vault address if cancelling vault orders | ## Use Cases ### Order Management Systems Track cancellation activity to understand order lifecycle and fill rates: ```python def process_cancel_action(action): for cancel in action.get('cancels', []): asset = cancel['a'] order_id = cancel['o'] print(f"Order cancelled: asset={asset}, oid={order_id}") ``` ### Risk Management Monitor cancellation patterns to detect: - High cancellation rates (potential spoofing) - Emergency position exits - Market maker quote updates ### Market Making Analytics Analyze the ratio of order placements to cancellations to understand market maker behavior and quote refresh rates. ## Related Action Types - [order](./order) - Submit new orders - [cancelByCloid](./cancelByCloid) - Cancel by client order ID - [scheduleCancel](./scheduleCancel) - Schedule future cancellation --- ## cancelByCloid - Cancel Orders by Client ID # cancelByCloid Cancel orders using the client-assigned order ID (cloid) instead of the exchange-assigned order ID. This is useful for trading systems that track orders by their own identifiers. ## Sample Data ```json { "signature": { "r": "0x2a0b6667955f197d530797576107b663fa08b20397286076f1684b3112738588", "s": "0x91a7dee6fae7c212e7b3f3a6dfbec5c555ac13986c56ec39bdc361b1713b8fb", "v": 28 }, "action": { "type": "cancelByCloid", "cancels": [ { "asset": 159, "cloid": "0x00000000000007550096147985161351" }, { "asset": 1, "cloid": "0x00000000000007580071223980263264" }, { "asset": 5, "cloid": "0x00000000000007580071644980263273" } ] }, "nonce": 1768146912996, "vaultAddress": "0x621c5551678189b9a6c94d929924c225ff1d63ab" } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x7aceda261c7a7d097c4804332644dc0202eb000bb77d9bdb1e978578db7e56f4) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"cancelByCloid"` | | `cancels` | array | Array of cancel requests | ### Cancel Object Fields | Field | Type | Description | |-------|------|-------------| | `asset` | number | Asset index of the order to cancel | | `cloid` | string | Client order ID (hex string) assigned when order was placed | ### Optional Fields | Field | Type | Description | |-------|------|-------------| | `vaultAddress` | string | Vault address if cancelling vault orders | | `expiresAfter` | number | Timestamp after which the cancel request expires | ## Client Order ID Format Client order IDs are 16-byte hex strings that you assign when placing orders. A common pattern encodes: - Date/timestamp information - Sequential counter - System identifier Example: `0x20260109000000000000000000150997` - `20260109` - Date encoding (2026-01-09) - `150997` - Sequence number ## Use Cases ### Trading System Integration Use cloids to maintain order state without querying the exchange: ```python def process_cancelByCloid_action(action): for cancel in action.get('cancels', []): asset = cancel['asset'] cloid = cancel['cloid'] # Match against your order management system order = order_tracker.get_by_cloid(cloid) if order: order.mark_cancelled() ``` ### Order Lifecycle Tracking Track orders from submission to cancellation using consistent identifiers across your systems. ### Latency Analysis Compare timestamps between cancel request and block inclusion to measure execution latency. ## Related Action Types - [order](./order) - Submit orders with cloid - [cancel](./cancel) - Cancel by exchange order ID - [modify](./modify) - Modify orders --- ## claimRewards - Claim Accumulated Rewards # claimRewards Claim accumulated rewards from trading, staking, or referral programs. ## Sample Data ```json { "signature": { "r": "0x8dedb7dedab58dacf6e8ce112dc72c73ea20ea9ab5a183d2e4b6447be7f8ae85", "s": "0x45e1720d57401d213f32f37af54718429f6e536aa93e6bd7a411fcc57cdf7c64", "v": 28 }, "action": { "type": "claimRewards" }, "nonce": 1767950334968, "expiresAfter": 1767950346788 } ``` ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"claimRewards"` | ## Use Cases ### Reward Claiming Activity Track reward claims: ```python def process_claimRewards_action(action): print("Rewards claimed") ``` ## Related Action Types - [tokenDelegate](./tokenDelegate) - Stake tokens for rewards - [setReferrer](./setReferrer) - Set up referral relationships --- ## convertToMultiSigUser - Convert to Multi-Sig # convertToMultiSigUser Convert a standard single-signer account to a multi-signature account requiring multiple signers for authorization. ## Sample Data ```json { "signature": { "r": "0xa1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456", "s": "0x6543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba987", "v": 28 }, "action": { "type": "convertToMultiSigUser", "signers": [ "0x1234567890abcdef1234567890abcdef12345678", "0xabcdef1234567890abcdef1234567890abcdef12" ], "threshold": 2 }, "nonce": 1767949700000 } ``` ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"convertToMultiSigUser"` | | `signers` | array | Addresses of authorized signers | | `threshold` | number | Required number of signatures | ## Use Cases ### Security Upgrade Tracking Monitor multi-sig conversions: ```python def process_convertToMultiSigUser_action(action): signers = action.get('signers', []) threshold = action.get('threshold') print(f"Multi-sig created: {threshold}/{len(signers)} required") ``` ## Related Action Types - [multiSig](./multiSig) - Execute multi-sig operations --- ## createSubAccount - Create Sub-Account # createSubAccount Create a new sub-account under the master account. Sub-accounts allow traders to isolate capital and risk for different trading strategies. ## Sample Data ```json { "signature": { "r": "0xb1e85a19894f08da2be6a3fc59c165daf03aeb90619211ea6eb94c38de6f4189", "s": "0x5d698bf033beb7efb63c29fb95cfbd9c1e7226841f365efe415ee35f60c028f", "v": 28 }, "action": { "type": "createSubAccount", "name": "test" }, "nonce": 1768146918353 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x33b81eb4aa36b7b93531043326450502039a009a4539d68bd780ca07693a91a3) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"createSubAccount"` | | `name` | string | Human-readable name for the sub-account | ## Sub-Account Benefits - **Risk Isolation**: Each sub-account has separate margin and positions - **Strategy Separation**: Run different strategies without interference - **API Wallet Support**: Agent wallets can trade on sub-accounts - **Clean Accounting**: Easier PnL tracking per strategy ## Use Cases ### Account Structure Analysis Track sub-account creation patterns: ```python def process_createSubAccount_action(action): name = action.get('name') print(f"New sub-account created: {name}") ``` ### User Sophistication Metrics Sub-account creation indicates more sophisticated traders who segment their capital. ### Platform Growth Tracking Monitor sub-account creation as a metric of platform engagement. ## Related Action Types - [subAccountTransfer](./subAccountTransfer) - Fund sub-accounts - [subAccountModify](./subAccountModify) - Modify sub-account settings - [subAccountSpotTransfer](./subAccountSpotTransfer) - Transfer spot assets --- ## createVault - Create Trading Vault # createVault Create a new trading vault on Hyperliquid. Vaults allow users to create managed trading strategies where other users can deposit funds and share in the trading results. ## Sample Data ```json { "signature": { "r": "0x888843b89133ec3eaf8d81601a680a56fe026232233760e741e886269d6d47e4", "s": "0x26b3a835ef519f69ad117a4050658157bf9d4a6c253985b91f20c074c648ea62", "v": 28 }, "action": { "type": "createVault", "name": "TradingFXVPS", "description": "Traders seeking alpha beyond buy-and-hold crypto...", "initialUsd": 4999000000, "nonce": 1768149497821 }, "nonce": 1768149497821, "expiresAfter": 1768149511760 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x16947d46be525853180e043326c24e0201ff002c59557725ba5d28997d56323d) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"createVault"` | | `name` | string | Display name for the vault | | `description` | string | Vault description (supports markdown/text) | | `initialUsd` | number | Initial USD deposit in atomic units (divide by 10^6 for USD) | | `nonce` | number | Transaction nonce for replay protection | ### Optional Fields | Field | Type | Description | |-------|------|-------------| | `expiresAfter` | number | Timestamp after which the action expires | ## Amount Conversion The `initialUsd` field is in atomic units: - `4999000000` atomic units = $4,999.00 USD (divide by 10^6) ## Use Cases ### Vault Analytics Track vault creation activity: ```python def process_createVault_action(action): name = action.get('name') initial_usd = action.get('initialUsd', 0) initial_usd_display = initial_usd / 1_000_000 print(f"New vault created: {name}") print(f"Initial deposit: ${initial_usd_display:,.2f}") ``` ### Strategy Monitoring Identify new trading strategies being launched on the platform. ### Ecosystem Growth Analysis Track vault creation trends to measure platform adoption. ## Related Action Types - [vaultTransfer](./vaultTransfer) - Deposit or withdraw from vault - [NetChildVaultPositionsAction](./NetChildVaultPositionsAction) - Net child vault positions --- ## evmRawTx - Execute EVM Transactions # evmRawTx Execute a raw EVM transaction on HyperEVM, Hyperliquid's EVM-compatible execution layer. This enables smart contract interactions, token transfers, and other EVM operations. ## Sample Data ```json { "signature": { "r": "0xd32b8218ae5299c1421560f39d56e25ffa12ffbfa8faa38768a01850787a4ad3", "s": "0x4a6ec5bb2ab212e0851a800f6e9eff5de75fb5802662ffe59ff98c789c4c4de4", "v": 28 }, "action": { "type": "evmRawTx", "data": "0x02f8b58203e78304083a8482aef4ce8482aef4ce83032523948549fd7ffc092f8366e416e129a622ec060104ea80b844a1d6012700001b00000000000000000bf8172fda000000000046cf76b73b80500001000000000000000000000000000000000000000026f9d2b528a25fd5f2a6568f47a1c001a02a409cb47713ca174e802b23a762d9d7fec900f63443d66aba5b26ef942d016aa04e426c68c1664757c974f059c91877d4703f0447fa8e5830071e406eac8882c6" }, "nonce": 1768146670768 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0xc54a7a279607a900c6c404332644d8000085920d310ac7d26913257a550b82eb) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"evmRawTx"` | | `rawTx` | string | RLP-encoded raw EVM transaction | ## HyperEVM Overview HyperEVM is Hyperliquid's EVM-compatible execution layer that allows: - Smart contract deployment and execution - ERC-20 token operations - DeFi protocol interactions - Bridge operations between L1 and EVM ## Transaction Decoding The `rawTx` field contains an RLP-encoded Ethereum transaction. Decoding it reveals: - `to`: Destination contract or address - `value`: ETH/native token amount - `data`: Contract call data (function selector + parameters) - `gasLimit`, `gasPrice`: Gas parameters ```python from eth_account._utils.legacy_transactions import decode_transaction def decode_evm_tx(raw_tx_hex): tx_bytes = bytes.fromhex(raw_tx_hex[2:]) # Remove 0x prefix decoded = decode_transaction(tx_bytes) return decoded ``` ## Use Cases ### DeFi Activity Monitoring Track smart contract interactions on HyperEVM: ```python def process_evmRawTx_action(action): raw_tx = action.get('rawTx') # Decode and analyze the transaction print(f"EVM transaction: {raw_tx[:50]}...") ``` ### Bridge Transaction Tracking Monitor cross-layer bridge operations between Hyperliquid L1 and HyperEVM. ### Smart Contract Analytics Analyze popular contract interactions and protocol usage patterns. ## Related Action Types - [evmUserModify](./evmUserModify) - Modify EVM user settings - [withdraw3](./withdraw3) - Withdraw to external address --- ## evmUserModify - Modify EVM User Settings # evmUserModify Modify user settings for HyperEVM interactions. ## Sample Data ```json { "signature": { "r": "0xa1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456", "s": "0x6543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba987", "v": 28 }, "action": { "type": "evmUserModify", "enabled": true }, "nonce": 1767949700000 } ``` ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"evmUserModify"` | | `enabled` | boolean | EVM access enabled | ## Use Cases ### EVM Access Tracking Monitor EVM setting changes: ```python def process_evmUserModify_action(action): enabled = action.get('enabled') status = 'enabled' if enabled else 'disabled' print(f"EVM access {status}") ``` ## Related Action Types - [evmRawTx](./evmRawTx) - Execute EVM transactions --- ## modify - Modify Single Order # modify Modify a single existing order's price, size, or other parameters. This allows updating an order without cancelling and re-submitting. ## Sample Data ```json { "signature": { "r": "0xc99c77b2297349c8ab77d7a820a31e0d43646c9c938775b81b5aed101e89885f", "s": "0x881c0298616ca974aad375d044e5796ed719eac0b86cf2f1348e309f623231d", "v": 28 }, "action": { "type": "modify", "oid": 291708423670, "order": { "a": 191, "b": true, "p": "0.15042", "s": "6583", "r": false, "t": { "limit": { "tif": "Alo" } }, "c": "0x55560089921887924531768146559426" } }, "nonce": 1768146528890, "vaultAddress": "0x0bd00a003c3a494261789a9c87ff17f6e605e715" } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0xff6953a569e4b75500e304332644c201dc006b8b04e7d628a331fef828e89140) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"modify"` | | `oid` | string | Order ID (or client order ID) to modify | | `order` | object | New order parameters | ### Order Object Fields | Field | Type | Description | |-------|------|-------------| | `a` | number | Asset index | | `b` | boolean | Side: `true` for buy, `false` for sell | | `p` | string | New limit price | | `s` | string | New size | | `r` | boolean | Reduce-only flag | | `t` | object | Order type configuration | | `c` | string | Client order ID | ### Optional Fields | Field | Type | Description | |-------|------|-------------| | `vaultAddress` | string | Vault executing the modification | | `expiresAfter` | number | Expiration timestamp | ## Use Cases ### Order Update Tracking Monitor how traders adjust their orders: ```python def process_modify_action(action): oid = action.get('oid') order = action.get('order', {}) new_price = order.get('p') new_size = order.get('s') print(f"Order {oid[:10]}... modified: price={new_price}, size={new_size}") ``` ### Market Maker Analysis Track how frequently market makers update their quotes. ### Price Improvement Detection Monitor price improvements on existing orders. ## Related Action Types - [order](./order) - Submit new orders - [batchModify](./batchModify) - Modify multiple orders atomically - [cancel](./cancel) - Cancel orders --- ## multiSig - Multi-Signature Operations # multiSig Execute an action that requires multiple signatures for authorization. Multi-sig accounts require a threshold of signers to approve transactions, enhancing security for institutional or shared accounts. ## Sample Data ```json { "signature": { "r": "0xa9b99251bf412a7cf584710c1ed25328dbe8523ae65f01911211a51cd63b3072", "s": "0x27883f0ff43062e012fabc1a192d12212c9cbe7f6939a0429fffe44f1779eb52", "v": 27 }, "action": { "type": "multiSig", "signatureChainId": "0x3e7", "signatures": [ { "r": "0xae84dedfe9ad13036d95dfa84c8e47cfd8f28fd191ac582f7ebba02cdadecb6a", "s": "0x5ba85eea603c524c50b722b7b3342ed3e1eec4c6dc491b3fc9dc5769a76d1deb", "v": 28 } ], "payload": { "multiSigUser": "0x1234567890545d1df9ee64b35fdd16966e08acec", "outerSigner": "0xd2d8bc14967d340c1eebde6eec6358200278da91", "action": { "type": "perpDeploy", "setOracle": { "dex": "xyz", "oraclePxs": [["xyz:AAPL", "260.02"], ["xyz:AMD", "203.72"]] } } } }, "nonce": 1768146913280 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x08dbe3e6b517f2e30a55043326066f0201e600cc501b11b5aca48f39741bcccd) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"multiSig"` | | `signatureChainId` | string | Chain ID for EIP-712 signing | | `signatures` | array | Array of co-signer signatures | | `payload` | object | The wrapped action to execute | ### Payload Fields | Field | Type | Description | |-------|------|-------------| | `multiSigUser` | string | Address of the multi-sig account | | `outerSigner` | string | Address of the signature submitter | | `action` | object | The underlying action to execute | ## Multi-Sig Benefits - **Enhanced Security**: Requires multiple parties to authorize actions - **Institutional Control**: Enables proper governance for fund operations - **Recovery Options**: Prevents single point of failure ## Use Cases ### Institutional Activity Tracking Monitor multi-sig operations for institutional-grade accounts: ```python def process_multiSig_action(action): payload = action.get('payload', {}) multisig_user = payload.get('multiSigUser') inner_action = payload.get('action', {}) inner_type = inner_action.get('type') print(f"MultiSig: {inner_type} from {multisig_user[:10]}...") ``` ### Oracle Price Updates Many multi-sig actions are used for oracle price feeds (as shown in the sample). ### Governance Analysis Track how multi-sig accounts manage critical protocol operations. ## Related Action Types - [convertToMultiSigUser](./convertToMultiSigUser) - Convert account to multi-sig - [perpDeploy](./perpDeploy) - Deploy perpetual markets (often wrapped in multiSig) --- ## noop - No Operation # noop A no-operation action that performs no state changes. Used for heartbeats, connection maintenance, and block padding. ## Sample Data ```json { "signature": { "r": "0x5157d93e3d66571991b0a7aa9cbfd108a7fff13749c606348acc14374bbbc9cd", "s": "0x42d4ed4d0863958c8bae8df8650b6844021168eb385f0ee0c085ae897f279c70", "v": 28 }, "action": { "type": "noop" }, "nonce": 1768146879398, "vaultAddress": "0x3ac9b030594c1ef23a3e8fed9f62356b7bf98bf6" } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x7b1200a2ac5608677c8b04332643de010f001888475927391edaabf56b59e252) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"noop"` | ### Optional Fields | Field | Type | Description | |-------|------|-------------| | `vaultAddress` | string | Vault executing the noop (if vault-originated) | ## Purpose The `noop` action serves several purposes: 1. **Heartbeat**: Maintains connection activity for vaults and agents 2. **Block Padding**: Ensures blocks have minimum activity 3. **Nonce Advancement**: Advances the nonce without executing trades 4. **Timing Signals**: Can indicate scheduled activity patterns ## Use Cases ### Activity Detection Filter out noops when analyzing real trading activity: ```python def process_block_actions(actions): # Filter out noops to focus on real activity real_actions = [a for a in actions if a.get('type') != 'noop'] return real_actions ``` ### Vault Health Monitoring Track vault activity through noop patterns: ```python def monitor_vault_activity(action): if action.get('type') == 'noop': vault = action.get('vaultAddress') if vault: print(f"Vault heartbeat: {vault[:10]}...") ``` ### Block Analysis Understand block composition by tracking noop ratios. ## Related Action Types - [order](./order) - Real trading activity - [SetGlobalAction](./SetGlobalAction) - System configuration --- ## order - Submit Trading Orders # order Submit new limit or market orders on Hyperliquid. This is the most frequently occurring action type, representing the core trading functionality of the exchange. ## Sample Data ```json { "signature": { "r": "0x961237313a71a702d4ca5f870a32172f3929aa9328d80505cbc5b9b178d2e338", "s": "0x8d0bc7bb0119bf5daac5e93a9552166e4a2f10bd711c26909e206aeb81eac89", "v": 28 }, "action": { "type": "order", "orders": [ { "a": 216, "b": false, "p": "0.26832", "s": "2021", "r": false, "t": { "limit": { "tif": "Ioc" } }, "c": "0x00000000000000000b56a217a8ef1f3c" } ], "grouping": "na" }, "nonce": 1768146912522, "expiresAfter": 1768146932522 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x72715093ba5096f673eb04332644bd02015400795553b5c81639fbe6795470e1) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"order"` | | `orders` | array | Array of order objects to submit | | `grouping` | string | Order grouping strategy: `"na"` (none), `"normalTpsl"`, or `"positionTpsl"` | ### Order Object Fields | Field | Type | Description | |-------|------|-------------| | `a` | number | Asset index (e.g., 0=BTC, 1=ETH) | | `b` | boolean | `true` for buy, `false` for sell | | `p` | string | Limit price | | `s` | string | Size in base currency | | `r` | boolean | Reduce-only flag | | `t` | object | Order type configuration | | `c` | string | Client order ID (optional) | ### Order Type Configuration The `t` field specifies order execution behavior: ```json // Limit order with time-in-force { "limit": { "tif": "Gtc" } } // Good-til-canceled { "limit": { "tif": "Ioc" } } // Immediate-or-cancel { "limit": { "tif": "Alo" } } // Add-liquidity-only (post-only) // Market order { "trigger": { "isMarket": true, "triggerPx": "0", "tpsl": "tp" } } ``` ### Optional Fields | Field | Type | Description | |-------|------|-------------| | `vaultAddress` | string | Vault executing the order (if vault trading) | | `expiresAfter` | number | Expiration timestamp in milliseconds | ## Use Cases ### Order Flow Analysis Track all order submissions to understand market activity: ```python def process_order_action(action): for order in action.get('orders', []): asset = order['a'] side = 'BUY' if order['b'] else 'SELL' price = order['p'] size = order['s'] print(f"New order: {side} {size} @ {price} (asset {asset})") ``` ### Trading Bot Monitoring Monitor competitor or whale trading activity by tracking order submissions from specific addresses. ### Market Microstructure Research Analyze order placement patterns, timing, and pricing strategies across the Hyperliquid order book. ## Related Action Types - [cancel](./cancel) - Cancel orders by order ID - [cancelByCloid](./cancelByCloid) - Cancel orders by client order ID - [batchModify](./batchModify) - Modify multiple orders atomically - [modify](./modify) - Modify a single order --- ## perpDeploy - Deploy Perpetual Markets # perpDeploy Deploy new perpetual markets or update oracle price configurations. ## Sample Data ```json { "signature": { "r": "0xf07b23ce4dbff09a3b0b3c2036842b2430c9fc3b997a4cf45ba3a4d5e7b1d025", "s": "0x37991b945e9ac813aa278df339c85e22a9bd395107adf21b1ac0ac7d41efcfa3", "v": 27 }, "action": { "type": "perpDeploy", "setFundingMultipliers": [ ["vntl:ANTHROPIC", "0.003000000118"], ["vntl:OPENAI", "0.00300303706"], ["vntl:SPACEX", "0.003000000026"] ] }, "nonce": 1768146962347 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x3bbd5fc75c2f55a93d37043326474302015b00acf722747bdf860b1a1b232f93) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"perpDeploy"` | | `setFundingMultipliers` | array | Funding rate multipliers per market | | `setOracle` | object | Oracle price configurations (alternative) | ## Use Cases ### Market Configuration Tracking Monitor market deployments and updates: ```python def process_perpDeploy_action(action): if 'setFundingMultipliers' in action: markets = action['setFundingMultipliers'] print(f"Funding updated for {len(markets)} markets") ``` ## Related Action Types - [multiSig](./multiSig) - Often wrapped in multi-sig for governance --- ## registerReferrer - Register as Referrer # registerReferrer Register as a referrer to create a referral code and earn fees from referred users' trading activity. ## Sample Data ```json { "signature": { "r": "0xcb7c3ba391ec86d5ca0f6a3bc9b9d5f2f5926ed387de53c66a38d0a518f5c220", "s": "0x728624e01619451fb16400a8393e25c6ec663adfb498ce9d73145f726766e322", "v": 27 }, "action": { "type": "registerReferrer", "code": "LV88" }, "nonce": 1767949731159 } ``` ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"registerReferrer"` | | `code` | string | Referral code to register | ## Use Cases ### Referrer Registration Tracking Monitor new referrer registrations: ```python def process_registerReferrer_action(action): code = action.get('code') print(f"New referrer registered: {code}") ``` ## Related Action Types - [setReferrer](./setReferrer) - Set referrer for an account - [claimRewards](./claimRewards) - Claim referral rewards --- ## reserveRequestWeight - Reserve Request Weight # reserveRequestWeight Reserve request weight allocation for system operations. ## Sample Data ```json { "signature": { "r": "0x3eab58f491988095343c3391ac498fcc8803a3692c0c3047c8f56088ab8589ea", "s": "0xd59535932e8490a63d90d70071f033bd0b59fb4025aa5a57a65b8af57ea71ff", "v": 27 }, "action": { "type": "reserveRequestWeight", "weight": 5000 }, "nonce": 1767951014393 } ``` ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"reserveRequestWeight"` | | `weight` | number | Request weight to reserve | ## Related Action Types - [noop](./noop) - No-operation action - [SetGlobalAction](./SetGlobalAction) - Global parameters --- ## scheduleCancel - Schedule Order Cancellation # scheduleCancel Schedule automatic cancellation of all open orders at a specified future time. Acts as a dead-man's switch for trading systems, ensuring orders are cancelled if the system stops responding. ## Sample Data ```json { "signature": { "r": "0x716e2f7591f552ba784c39fa3198c71a83fc13d93d206aa650571206149cb747", "s": "0x6e021299550e2b71871f3e98acf02c45c4fe5c0a09b4fc1e613db585eb9d0150", "v": 28 }, "action": { "type": "scheduleCancel", "time": 1768146928010 }, "nonce": 1768146913010 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x6af694b1b999c8a06c7004332644bd0201680097549ce7720ebf4004789da28b) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"scheduleCancel"` | | `time` | number | UTC timestamp (milliseconds) when orders should be cancelled | ## Dead-Man's Switch Pattern Trading systems typically: 1. Submit orders with `scheduleCancel` set to T+N seconds 2. Continuously extend the cancellation time while operating normally 3. If the system fails, orders automatically cancel at the scheduled time This prevents orphaned orders from remaining on the book if a trading bot crashes. ## Use Cases ### Risk Management Monitoring Track how traders implement fail-safes: ```python def process_scheduleCancel_action(action): cancel_time = action.get('time') if cancel_time: from datetime import datetime cancel_dt = datetime.fromtimestamp(cancel_time / 1000) print(f"Orders scheduled to cancel at {cancel_dt}") ``` ### Bot Health Detection Monitor schedule cancel extensions as a proxy for bot health. ### Market Stability Analysis Track how many orders have dead-man switches configured. ## Related Action Types - [order](./order) - Submit orders - [cancel](./cancel) - Immediate order cancellation - [cancelByCloid](./cancelByCloid) - Cancel by client order ID --- ## sendAsset - Generic Asset Transfer # sendAsset Generic asset transfer supporting flexible source and destination configurations including cross-DEX transfers. ## Sample Data ```json { "signature": { "r": "0x93eef9b0e03606c293b12d43930c38dc246777cb222b3eb296396bc46d9481b5", "s": "0x295978b118626247150483ce4c462680dcaa8ba4cf1f9cc779967d8503287900", "v": 28 }, "action": { "type": "sendAsset", "signatureChainId": "0x1", "hyperliquidChain": "Mainnet", "destination": "0xf2743533df9c376a09da0b9810de8c457e28aadc", "sourceDex": "", "destinationDex": "", "token": "USDC:0x6d1e7cde53ba9467b783cb7c530ce054", "amount": "4.912352", "fromSubAccount": "", "nonce": 1768146914372 }, "nonce": 1768146914372 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x154dfe3cc1ac2f1b16c704332644d30201a300225caf4dedb916a98f80a00905) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"sendAsset"` | | `destination` | string | Recipient address | | `sourceDex` | boolean | Source is DEX (vs bridge) | | `destinationDex` | boolean | Destination is DEX (vs bridge) | | `token` | string | Token to transfer | | `amount` | string | Amount to transfer | | `fromSubAccount` | boolean | Transfer from sub-account | ## Use Cases ### Cross-Account Transfers Track asset movements: ```python def process_sendAsset_action(action): destination = action.get('destination') token = action.get('token') amount = action.get('amount') print(f"Asset transfer: {amount} {token} to {destination[:10]}...") ``` ## Related Action Types - [spotSend](./spotSend) - Send spot tokens - [usdSend](./usdSend) - Send USD --- ## setReferrer - Set Referral Code # setReferrer Set a referrer for the account using a referral code. This enables the account to participate in Hyperliquid's referral program, where the referrer earns a portion of trading fees. ## Sample Data ```json { "signature": { "r": "0xf1d1526d59598ab867931fa78f9eedf4a76bada17a90cb2a8b804222774019cb", "s": "0x1eafd4a61d38331a80841682309b981f49e777094c2affe123f5cfd59293d047", "v": 28 }, "action": { "type": "setReferrer", "code": "PLACEHOLDER" }, "nonce": 1768146913883 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0xd6f62a16e52adfa7d86f04332644cd02033900fc802dfe797abed569a42eb992) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"setReferrer"` | | `code` | string | Referral code to associate with the account | ## Referral Program Hyperliquid's referral system allows: - Referrers to earn a percentage of referred users' trading fees - New users to potentially receive fee discounts - Both parties to benefit from the relationship ## Use Cases ### Referral Analytics Track referral code adoption and distribution: ```python referral_counts = {} def process_setReferrer_action(action): code = action.get('code') referral_counts[code] = referral_counts.get(code, 0) + 1 print(f"Referral code used: {code} (total: {referral_counts[code]})") ``` ### Influencer Tracking Monitor which referral codes are most popular to identify influential promoters. ### Onboarding Analysis Track referral usage patterns to understand user acquisition channels. ## Related Action Types - [registerReferrer](./registerReferrer) - Register as a referrer - [claimRewards](./claimRewards) - Claim referral rewards --- ## spotSend - Transfer Spot Assets # spotSend Transfer spot tokens (like HYPE) to another Hyperliquid address. This action moves assets directly between accounts on the L1. ## Sample Data ```json { "signature": { "r": "0x3054da3f8b58c8eb22dbb4da6c010bd6eeda1681122fca4230e8853ea0836119", "s": "0x638265740adb334844d7825bb267a1fec5d0e45ba27ae73b09197b5f49b5148", "v": 27 }, "action": { "type": "spotSend", "signatureChainId": "0x66eee", "hyperliquidChain": "Mainnet", "destination": "0xE2a0cC663aCFE5D7A9Cb82A743383297597A8fF3", "token": "USDC:0x6d1e7cde53ba9467b783cb7c530ce054", "amount": "98.43", "time": 1768146929220 }, "nonce": 1768146929220 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x2a4dd5ab257f1c0b2bc7043326459f01ec00ed90c0723addce1680fde472f5f5) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"spotSend"` | | `signatureChainId` | string | Chain ID for EIP-712 signing | | `hyperliquidChain` | string | Target chain: `"Mainnet"` or `"Testnet"` | | `destination` | string | Recipient's Ethereum address | | `token` | string | Token identifier (symbol:contract format) | | `amount` | string | Amount to transfer (human-readable decimals) | | `time` | number | Transaction timestamp | ## Token Identifier Format Tokens are identified using the format `SYMBOL:CONTRACT_HASH`: - `HYPE:0x0d01dc56dcaaca66ad901c959b4011ec` - HYPE token - Other spot tokens follow the same pattern ## Use Cases ### Token Flow Analysis Track spot token movements across the network: ```python def process_spotSend_action(action): destination = action.get('destination') token = action.get('token') amount = action.get('amount') token_symbol = token.split(':')[0] print(f"Spot transfer: {amount} {token_symbol} to {destination[:10]}...") ``` ### Whale Tracking Monitor large token transfers to identify significant market participants. ### Exchange Flow Monitoring Track token deposits and withdrawals from exchange-related addresses. ## Related Action Types - [usdSend](./usdSend) - Transfer USD between accounts - [sendAsset](./sendAsset) - Generic asset transfer - [subAccountSpotTransfer](./subAccountSpotTransfer) - Transfer spot to sub-accounts --- ## spotUser - Spot User Configuration # spotUser Configure spot trading settings for a user account. ## Sample Data ```json { "signature": { "r": "0xfb9cd389323a6b281ee513f1b1ddd0fffc21caf970e4d621da117af34c8ae800", "s": "0x7c5d80c2e1a15f46eed277e953453e87c1f65e7ba74b621a520d779ee6766e2b", "v": 28 }, "action": { "type": "spotUser", "toggleSpotDusting": { "optOut": true } }, "nonce": 1768151177912, "expiresAfter": 1768151192082 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0xa0c634450ebcfd6ca23f0433271125020482002aa9b01c3e448edf97cdb0d757) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"spotUser"` | | `toggleSpotDusting` | object | Spot dusting settings | ## Related Action Types - [spotSend](./spotSend) - Send spot tokens --- ## subAccountModify - Modify Sub-Account Settings # subAccountModify Modify settings and permissions for an existing sub-account. ## Sample Data ```json { "signature": { "r": "0xa1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456", "s": "0x6543210fedcba9876543210fedcba9876543210fedcba9876543210fedcba987", "v": 27 }, "action": { "type": "subAccountModify", "subAccountUser": "0x1234567890abcdef1234567890abcdef12345678", "name": "Trading Bot 1" }, "nonce": 1767949700000 } ``` ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"subAccountModify"` | | `subAccountUser` | string | Sub-account address to modify | | `name` | string | New name for the sub-account | ## Use Cases ### Sub-Account Management Track sub-account modifications: ```python def process_subAccountModify_action(action): sub_account = action.get('subAccountUser') name = action.get('name') print(f"Sub-account modified: {sub_account[:10]}... -> {name}") ``` ## Related Action Types - [createSubAccount](./createSubAccount) - Create sub-accounts - [subAccountTransfer](./subAccountTransfer) - Fund sub-accounts --- ## subAccountSpotTransfer - Sub-Account Spot Transfer # subAccountSpotTransfer Transfer spot tokens between a main account and its sub-accounts. ## Sample Data ```json { "signature": { "r": "0xd37da2735026576e0cfcd347f381499e142423edae6ce9a170fe985bd99f7aaf", "s": "0x2999636e5fb176a4ae4d3cb1c4682496fcd0bd2b79e84497865340dfeb02c801", "v": 27 }, "action": { "type": "subAccountSpotTransfer", "subAccountUser": "0x9266865bb6afb4c4f618544dd3b8c970f17aa664", "isDeposit": true, "token": "BZEC:0x33b2c5252e8ea8431808129c41668129", "amount": "4.63" }, "nonce": 1767952944523 } ``` ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"subAccountSpotTransfer"` | | `subAccountUser` | string | Sub-account address | | `isDeposit` | boolean | `true` to deposit to sub-account, `false` to withdraw | | `token` | string | Token identifier | | `amount` | string | Amount to transfer | ## Use Cases ### Sub-Account Spot Funding Track spot token allocations to sub-accounts: ```python def process_subAccountSpotTransfer_action(action): sub_account = action.get('subAccountUser') token = action.get('token').split(':')[0] amount = action.get('amount') direction = 'to' if action.get('isDeposit') else 'from' print(f"Spot transfer: {amount} {token} {direction} sub-account") ``` ## Related Action Types - [subAccountTransfer](./subAccountTransfer) - USD transfers - [spotSend](./spotSend) - Direct spot transfers --- ## subAccountTransfer - Sub-Account Transfers # subAccountTransfer Transfer USD between a main account and its sub-accounts. Sub-accounts enable traders to isolate capital for different strategies while maintaining a single master account. ## Sample Data ```json { "signature": { "r": "0xda5441ff957c27e824e3540bcfb3e0bb7ccf5fba10712084981e14b6822e5d2b", "s": "0x36985abcf5691e89d37afd7f9da70453bc7abdd4f0b29c1ddd9326022c94a43c", "v": 28 }, "action": { "type": "subAccountTransfer", "subAccountUser": "0xde22d34aa3b215d225e209c906e19511465738b1", "isDeposit": true, "usd": 18000000 }, "nonce": 1768146973096 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x8b7eafe317b159a08cf804332647b702033800c8b2b478722f475b35d6b5338b) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"subAccountTransfer"` | | `subAccountUser` | string | Address of the sub-account | | `isDeposit` | boolean | `true` to transfer to sub-account, `false` to withdraw from sub-account | | `usd` | number | Amount in raw units (6 decimals, so 153000000 = 153 USD) | ## Amount Conversion The `usd` field uses 6 decimal places: - `153000000` = 153.00 USD - `1000000000` = 1,000.00 USD ## Use Cases ### Capital Allocation Tracking Monitor how traders allocate capital across sub-accounts: ```python def process_subAccountTransfer_action(action): sub_account = action.get('subAccountUser') amount = action.get('usd') / 1_000_000 direction = 'to' if action.get('isDeposit') else 'from' print(f"Transfer ${amount:,.2f} {direction} sub-account {sub_account[:10]}...") ``` ### Strategy Isolation Analysis Track how traders segment capital for different trading strategies. ### Risk Management Patterns Monitor sub-account funding to understand risk management approaches. ## Related Action Types - [createSubAccount](./createSubAccount) - Create new sub-accounts - [subAccountModify](./subAccountModify) - Modify sub-account settings - [subAccountSpotTransfer](./subAccountSpotTransfer) - Transfer spot assets to sub-accounts --- ## tokenDelegate - Stake Tokens to Validators # tokenDelegate Delegate (stake) tokens to a validator or undelegate them. This enables token holders to participate in network security and earn staking rewards. ## Sample Data ```json { "signature": { "r": "0xd3d8ea7bf5d7699274f77d6527be0a78f137cb7f41e8b90b87de639b1f4d5704", "s": "0x7041f94160b4b38e516507a201e5f65872fb7e9ce2522b901b31621048fbb653", "v": 27 }, "action": { "type": "tokenDelegate", "signatureChainId": "0xa4b1", "hyperliquidChain": "Mainnet", "validator": "0xa23b4556090260828ff3f939d2dbdd4f318b5f1f", "wei": 10000000000, "isUndelegate": false, "nonce": 1768148103446 }, "nonce": 1768148103446 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x9dc715cc0bc6509b9f400433267e8b0201fd00b1a6c96f6d418fc11ecaca2a86) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"tokenDelegate"` | | `signatureChainId` | string | Chain ID for EIP-712 signing | | `hyperliquidChain` | string | Target chain: `"Mainnet"` or `"Testnet"` | | `validator` | string | Validator address to delegate to | | `wei` | number | Amount in wei (smallest unit) | | `isUndelegate` | boolean | `true` to undelegate, `false` to delegate | | `nonce` | number | Transaction nonce | ## Amount Conversion The `wei` field is in the smallest token unit: - `14494791496000` wei = 14.49 tokens (assuming 12 decimals) ## Use Cases ### Staking Analytics Track delegation and undelegation patterns: ```python def process_tokenDelegate_action(action): validator = action.get('validator') amount_wei = action.get('wei') is_undelegate = action.get('isUndelegate') direction = 'undelegated from' if is_undelegate else 'delegated to' print(f"Tokens {direction} validator {validator[:10]}...") ``` ### Validator Monitoring Track which validators are gaining or losing stake. ### Network Security Analysis Monitor total stake and distribution across validators. ## Related Action Types - [claimRewards](./claimRewards) - Claim staking rewards - [voteAppHash](./voteAppHash) - Validator voting --- ## twapCancel - Cancel TWAP Orders # twapCancel Cancel an active TWAP (Time-Weighted Average Price) order before it completes execution. ## Sample Data ```json { "signature": { "r": "0x19049f59f4a558ebde3cd54b7fec8fa7329bed21515aafa468f08b6d283f87d5", "s": "0x701715161c404203ec40441689c4fea25894c827a8bf48d3a46a9601d859478a", "v": 27 }, "action": { "type": "twapCancel", "a": 161, "t": 1506780 }, "nonce": 1768147413037, "expiresAfter": 1768147429667 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x93986f25f267ac6b95120433265d72020334000b8d6acb3d37611a78b16b8656) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"twapCancel"` | | `a` | number | Asset index | | `t` | number | TWAP order ID to cancel | ## Use Cases ### TWAP Lifecycle Tracking Monitor TWAP order cancellations: ```python def process_twapCancel_action(action): asset = action.get('a') twap_id = action.get('t') print(f"TWAP cancelled: asset {asset}, id {twap_id}") ``` ## Related Action Types - [twapOrder](./twapOrder) - Submit TWAP orders - [cancel](./cancel) - Cancel regular orders --- ## twapOrder - Time-Weighted Average Price Orders # twapOrder Submit a Time-Weighted Average Price (TWAP) order that executes gradually over a specified time period. TWAP orders split large orders into smaller pieces to minimize market impact. ## Sample Data ```json { "signature": { "r": "0xec414de7c86d85e3c73aba1ed8496e15f48acb37ec7f9b52a1c7d76f091ccd45", "s": "0x373d79f4d9731a69b4d93ccebf3fa711eae9550be65878c9358f30b20e798e4b", "v": 28 }, "action": { "type": "twapOrder", "twap": { "a": 10260, "b": true, "s": "215.72", "r": false, "m": 1440, "t": false } }, "nonce": 1768146926099 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x65ce2950fb88ebd16747043326457a02016e0036968c0aa30996d4a3ba8cc5bc) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"twapOrder"` | | `a` | number | Asset index (e.g., 0 = BTC) | | `b` | boolean | Side: `true` for buy, `false` for sell | | `s` | string | Total size to execute | | `r` | boolean | Reduce-only flag | | `m` | number | Duration in minutes | | `t` | boolean | Randomize execution (avoid predictable patterns) | ## TWAP Execution TWAP orders: - Split total size into smaller child orders - Execute over the specified duration - Can be randomized to avoid detection - Minimize market impact for large positions ## Use Cases ### Institutional Order Detection Track TWAP order submissions for large position building: ```python def process_twapOrder_action(action): asset = action.get('a') side = 'BUY' if action.get('b') else 'SELL' size = action.get('s') duration = action.get('m') print(f"TWAP: {side} {size} of asset {asset} over {duration} minutes") ``` ### Market Impact Analysis Monitor TWAP activity to understand institutional positioning. ### Execution Quality Research Study TWAP execution patterns and slippage. ## Related Action Types - [twapCancel](./twapCancel) - Cancel TWAP orders - [order](./order) - Standard orders - [batchModify](./batchModify) - Batch modifications --- ## updateIsolatedMargin - Adjust Isolated Margin # updateIsolatedMargin Add or remove margin from an isolated position. This allows fine-tuning position risk without changing the position size or closing the trade. ## Sample Data ```json { "signature": { "r": "0xd14b53f9f6b7cb39e5289f62c453f22d21d46def6f7acbc267cb33f1d2d2668f", "s": "0x393d89fcd7835fad35ff2b06e29b6c56bd8034efc5bd9b38848c8ac7dd32fbc3", "v": 28 }, "action": { "type": "updateIsolatedMargin", "asset": 0, "isBuy": true, "ntli": -1000000 }, "nonce": 1768146925098 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0xd02fc36287650ca2d1a9043326463302037f004822682b7473f86eb54668e68d) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"updateIsolatedMargin"` | | `asset` | number | Asset index (e.g., 0 = BTC) | | `isBuy` | boolean | Position side: `true` for long, `false` for short | | `ntli` | number | Margin adjustment in raw units (negative = remove, positive = add) | ## Understanding ntli The `ntli` field represents the margin change in raw integer units: - **Positive values**: Add margin to the position (reduce liquidation risk) - **Negative values**: Remove margin from the position (increase liquidation risk) The value `-1000000` in the sample represents removing 1 USD of margin (assuming 6 decimal places for USDC). ## Use Cases ### Position Risk Monitoring Track margin adjustments to understand how traders manage position risk: ```python def process_updateIsolatedMargin_action(action): asset = action.get('asset') side = 'LONG' if action.get('isBuy') else 'SHORT' margin_change = action.get('ntli') / 1_000_000 # Convert to USD direction = 'added' if margin_change > 0 else 'removed' print(f"Margin {direction}: {abs(margin_change)} USD on {side} {asset}") ``` ### Liquidation Prevention Analysis Monitor margin additions that may indicate positions approaching liquidation. ### Capital Efficiency Tracking Track margin removals to understand how traders optimize capital usage. ## Related Action Types - [updateLeverage](./updateLeverage) - Change leverage settings - [userPortfolioMargin](./userPortfolioMargin) - Portfolio margin mode --- ## updateLeverage - Adjust Position Leverage # updateLeverage Update the leverage setting for a specific asset position. This action allows traders to adjust their risk exposure and switch between cross and isolated margin modes. ## Sample Data ```json { "signature": { "r": "0x10b0a002706afea1c9e337ac501fd52a96fb8ddad544b2b6a3a663e0c2e16e51", "s": "0x5906914d9c472e585e13b52e9435fb1d9980022d625559b566a3541c0f92d5a2", "v": 28 }, "action": { "type": "updateLeverage", "asset": 110000, "isCross": false, "leverage": 7 }, "nonce": 1768146912541 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x909ba690b7305579921504332644be02028d00765233744b346451e376342f64) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"updateLeverage"` | | `asset` | number | Asset index to update leverage for | | `isCross` | boolean | `true` for cross margin, `false` for isolated margin | | `leverage` | number | New leverage value (e.g., 2 for 2x leverage) | ## Margin Modes ### Cross Margin (`isCross: true`) - Shares margin across all positions - Unrealized PnL from other positions can prevent liquidation - More capital efficient but higher risk of cascade liquidations ### Isolated Margin (`isCross: false`) - Each position has dedicated margin - Losses are limited to the position's margin - Requires more capital but limits downside exposure ## Use Cases ### Risk Management Monitoring Track leverage changes to understand trader risk appetite: ```python def process_updateLeverage_action(action): asset = action.get('asset') leverage = action.get('leverage') margin_mode = 'cross' if action.get('isCross') else 'isolated' print(f"Leverage update: asset {asset} -> {leverage}x ({margin_mode})") ``` ### Liquidation Risk Analysis Monitor leverage increases that may indicate higher liquidation risk. ### Market Sentiment Aggregate leverage changes can indicate market sentiment: - Increasing leverage = More aggressive/bullish positioning - Decreasing leverage = More conservative/risk-off ## Related Action Types - [updateIsolatedMargin](./updateIsolatedMargin) - Adjust isolated margin amount - [userPortfolioMargin](./userPortfolioMargin) - Enable portfolio margin mode - [order](./order) - Trading orders affected by leverage settings --- ## usdClassTransfer - Transfer Between Margin Modes # usdClassTransfer Transfer USD-class assets between perpetual and spot margin modes. This allows traders to reallocate capital between different trading modes. ## Sample Data ```json { "signature": { "r": "0xb6fb726ec034a9a8d5125cc9031012a58ba10f39c380a80566b56363a2a7cabf", "s": "0x6d4bc0977c2a7cb99c5ae1a5a9fd54fd219598661c12a36e344f52b3bdb6bc6b", "v": 28 }, "action": { "type": "usdClassTransfer", "signatureChainId": "0x66eee", "hyperliquidChain": "Mainnet", "amount": "55.00000001000001", "toPerp": true, "nonce": 1768146939642 }, "nonce": 1768146939642 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x5ac4b8e201a98b1d5c3e043326462d02016100c79caca9effe8d6434c0ad6507) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"usdClassTransfer"` | | `signatureChainId` | string | Chain ID for EIP-712 signing | | `hyperliquidChain` | string | Target chain: `"Mainnet"` or `"Testnet"` | | `amount` | string | Amount to transfer (human-readable USD) | | `toPerp` | boolean | `true` to transfer to perp margin, `false` to spot margin | | `nonce` | number | Transaction nonce | ## Transfer Direction | `toPerp` Value | Direction | |----------------|-----------| | `true` | Spot margin → Perp margin | | `false` | Perp margin → Spot margin | ## Use Cases ### Capital Flow Analysis Track how traders allocate between perp and spot: ```python def process_usdClassTransfer_action(action): amount = action.get('amount') to_perp = action.get('toPerp') direction = 'spot → perp' if to_perp else 'perp → spot' print(f"Margin transfer: ${amount} ({direction})") ``` ### Market Mode Preference Monitor aggregate flows to understand market preferences between spot and perp trading. ### Arbitrage Detection Large transfers may indicate arbitrage opportunities between markets. ## Related Action Types - [usdSend](./usdSend) - Send USD to another address - [spotSend](./spotSend) - Transfer spot tokens - [subAccountTransfer](./subAccountTransfer) - Sub-account transfers --- ## usdSend - Transfer USD # usdSend Send USD to another Hyperliquid address. This is an internal transfer that moves USD-denominated assets between accounts on the L1. ## Sample Data ```json { "signature": { "r": "0x2bb37a8b0c893d0e4a2f0e28e2411aad8fd31baeccb4188fb7aa58b92478ba96", "s": "0x6b806e50eabbfa1d275a0afc9e932296df700bc9022af48ef7b87e806da9b538", "v": 27 }, "action": { "type": "usdSend", "signatureChainId": "0xa4b1", "hyperliquidChain": "Mainnet", "destination": "0x192c181edebbad21a90e3aeec3519d30528c6d60", "amount": "17.18", "time": 1768146943132 }, "nonce": 1768146943132 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x7c55ce705c37a4047dcf043326465e02013d0055f73ac2d6201e79c31b3b7def) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"usdSend"` | | `signatureChainId` | string | Chain ID for EIP-712 signing | | `hyperliquidChain` | string | Target chain: `"Mainnet"` or `"Testnet"` | | `destination` | string | Recipient's address | | `amount` | string | Amount in USD | | `time` | number | Transaction timestamp | ## Use Cases ### Internal Transfer Tracking Monitor USD movements between accounts: ```python def process_usdSend_action(action): destination = action.get('destination') amount = action.get('amount') print(f"USD transfer: ${amount} to {destination[:10]}...") ``` ## Related Action Types - [spotSend](./spotSend) - Transfer spot tokens - [usdClassTransfer](./usdClassTransfer) - Transfer between margin modes --- ## userDexAbstraction - User DEX Abstraction Settings # userDexAbstraction Configure DEX abstraction settings for a user account. ## Sample Data ```json { "signature": { "r": "0x9b539b38d3dd3c7d39d5da040409401ec0e6ac6aef40715b8d3cd60b0c2c48f6", "s": "0x3d22fd88f17177a8ebcc0bf40d3a996fea3a8f188ba0226a0f4d7776462a5ee0", "v": 28 }, "action": { "type": "userDexAbstraction", "signatureChainId": "0x2105", "hyperliquidChain": "Mainnet", "user": "0xb20088b36418bd7a3c845614c59aa9cebbec72de", "enabled": true, "nonce": 1768146986170 }, "nonce": 1768146986170 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x876d569faeaa634b88e70433264852020138008549ad821d2b3601f26dae3d36) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"userDexAbstraction"` | | `enabled` | boolean | DEX abstraction enabled | ## Use Cases ### DEX Settings Tracking Monitor DEX abstraction configuration: ```python def process_userDexAbstraction_action(action): enabled = action.get('enabled') status = 'enabled' if enabled else 'disabled' print(f"DEX abstraction {status}") ``` ## Related Action Types - [agentEnableDexAbstraction](./agentEnableDexAbstraction) - Agent DEX settings - [approveAgent](./approveAgent) - Agent authorization --- ## userPortfolioMargin - Portfolio Margin Mode # userPortfolioMargin Enable or configure portfolio margin mode for an account. Portfolio margin considers the risk of the entire portfolio rather than individual positions, allowing more capital-efficient trading. ## Sample Data ```json { "signature": { "r": "0x7e5f71ded930d4524d19dc7d6f04b2cb268355ee3a71465365017d12fccac779", "s": "0x16414434babfd4079bdedffd4c78644f66d95bee4287e4a375208b5ffe8893ea", "v": 27 }, "action": { "type": "userPortfolioMargin", "signatureChainId": "0xa4b1", "hyperliquidChain": "Mainnet", "user": "0xb714f435b61a228aa82d28fd4d975b041a88f85d", "enabled": true, "nonce": 1768147316503 }, "nonce": 1768147316503 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x79b10d620b87fc577b2a043326594b0201990047a68b1b291d79b8b4ca8bd642) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"userPortfolioMargin"` | | `signatureChainId` | string | Chain ID for signing | | `hyperliquidChain` | string | Target chain | | `user` | string | User address to configure | | `enabled` | boolean | `true` to enable, `false` to disable | | `nonce` | number | Transaction nonce | ## Use Cases ### Portfolio Margin Adoption Track portfolio margin usage: ```python def process_userPortfolioMargin_action(action): user = action.get('user') enabled = action.get('enabled') status = 'enabled' if enabled else 'disabled' print(f"Portfolio margin {status} for {user[:10]}...") ``` ## Related Action Types - [updateLeverage](./updateLeverage) - Leverage settings - [updateIsolatedMargin](./updateIsolatedMargin) - Isolated margin adjustments --- ## vaultTransfer - Vault Deposits and Withdrawals # vaultTransfer Deposit funds into or withdraw funds from a Hyperliquid vault. Vaults are shared trading accounts that allow multiple users to pool capital under a vault manager's control. ## Sample Data ```json { "signature": { "r": "0xb2eaf71a6dd711b38983c5ca9c813e6260cd11414d5b66bfc734ccf27671858c", "s": "0x77e7d3501bc1c6743787a1967dcdc0618f0f445df70bb98b99dccc66881d4b33", "v": 28 }, "action": { "type": "vaultTransfer", "vaultAddress": "0xdfc24b077bc1425ad1dea75bcb6f8158e10df303", "isDeposit": false, "usd": 500000000 }, "nonce": 1768147192344, "expiresAfter": 1768147206900 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x4bdc0ce600639cb74d5504332652ab02013700cb9b66bb89efa4b838bf6776a1) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"vaultTransfer"` | | `vaultAddress` | string | Ethereum address of the vault | | `isDeposit` | boolean | `true` for deposit, `false` for withdrawal | | `usd` | number | Amount in raw units (6 decimals, so 50000000 = 50 USD) | ### Optional Fields | Field | Type | Description | |-------|------|-------------| | `expiresAfter` | number | Timestamp after which the transfer expires | ## Amount Conversion The `usd` field uses 6 decimal places: - `50000000` = 50.00 USD - `1000000` = 1.00 USD - `1000000000` = 1,000.00 USD ## Use Cases ### Vault Flow Analysis Track capital flows into and out of vaults: ```python def process_vaultTransfer_action(action): vault = action.get('vaultAddress') amount = action.get('usd') / 1_000_000 # Convert to USD direction = 'deposit' if action.get('isDeposit') else 'withdrawal' print(f"Vault {direction}: ${amount:,.2f} to {vault[:10]}...") ``` ### Fund Manager Performance Monitor vault deposit/withdrawal patterns to understand: - Vault popularity and AUM trends - Investor confidence in vault strategies - Capital rotation between vaults ### Copy Trading Analysis Track which vaults are attracting deposits to identify successful trading strategies. ## Related Action Types - [NetChildVaultPositionsAction](./NetChildVaultPositionsAction) - Net child vault positions - [subAccountTransfer](./subAccountTransfer) - Transfer between main and sub-accounts --- ## voteAppHash - Validator State Votes # voteAppHash Validators vote on the application state hash as part of the consensus mechanism. ## Sample Data ```json { "signature": { "r": "0xccd84bb5e2f144ec741af1a81d2fc318d8ccb75eaf500371c1515c1e695b2213", "s": "0x25a8b7da621dccbd161fb61487c6bd8e369d1ba28567b26b3ac6ab647b84e270", "v": 28 }, "action": { "type": "voteAppHash", "height": 858146000, "appHash": "0x9133a75f5e126769845b4bd35e7b6b02456c1f3df72f146eb89e0e86c61415d7", "signature": { "r": "0x381dcf885e27e08f1547ded9a97f3d51eef2857d86164993d8416c2deeeb8de1", "s": "0x4ad114432fef3b53b791a568a118f99ec881922ce57fa2e2df1f4fb9272c609f", "v": 27 } }, "nonce": 1768146734574 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0xc871b17a2a660c12c9eb0433264507010b00c95fc5692ae46c3a5ccce969e5fd) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"voteAppHash"` | | `height` | number | Block height being voted on | | `appHash` | string | Application state hash | | `signature` | object | Validator's signature on the vote | ## Use Cases ### Consensus Monitoring Track validator voting activity: ```python def process_voteAppHash_action(action): height = action.get('height') app_hash = action.get('appHash') print(f"State vote: height {height}, hash {app_hash[:20]}...") ``` ## Related Action Types - [VoteEthDepositAction](./VoteEthDepositAction) - Deposit votes - [tokenDelegate](./tokenDelegate) - Token staking --- ## withdraw3 - Withdraw to External Address # withdraw3 Withdraw funds from Hyperliquid to an external Ethereum address (typically on Arbitrum). This initiates the bridge process to move assets off the L1. ## Sample Data ```json { "signature": { "r": "0xbf01efa816fdc37c8eea7ae4893999cae61ead196013d4bcb36ff8aad3058650", "s": "0x2dcc0e2d708eccdf7ab68a23b99b4142aa6eca02141623851158821d371bd610", "v": 27 }, "action": { "type": "withdraw3", "signatureChainId": "0x66eee", "hyperliquidChain": "Mainnet", "destination": "0xc2c9981b9061e533affaaf03105c561154f1ec84", "amount": "16.494002", "time": 1768146916924 }, "nonce": 1768146916924 } ``` [View this transaction on Hypurrscan →](https://hypurrscan.io/tx/0x0060497fdb8f86ee01da04332644fa0201ee00657682a5c0a428f4d29a8360d8) ## Field Reference ### Action Fields | Field | Type | Description | |-------|------|-------------| | `type` | string | Always `"withdraw3"` | | `signatureChainId` | string | Chain ID for signing (e.g., `"0xa4b1"` for Arbitrum) | | `hyperliquidChain` | string | Source chain: `"Mainnet"` or `"Testnet"` | | `destination` | string | External Ethereum address to receive funds | | `amount` | string | Amount to withdraw in USD | | `time` | number | Transaction timestamp | ## Withdrawal Process 1. User submits `withdraw3` action 2. Validators verify the withdrawal request 3. Validators sign the withdrawal ([ValidatorSignWithdrawalAction](./ValidatorSignWithdrawalAction)) 4. Bridge transaction is executed on Arbitrum 5. Funds arrive at destination address ## Use Cases ### Withdrawal Monitoring Track withdrawals leaving the platform: ```python def process_withdraw3_action(action): destination = action.get('destination') amount = action.get('amount') print(f"Withdrawal: ${amount} to {destination}") ``` ### Capital Flow Analysis Monitor net flows in and out of Hyperliquid to understand market sentiment. ### Compliance Monitoring Track withdrawal destinations for regulatory compliance. ## Related Action Types - [ValidatorSignWithdrawalAction](./ValidatorSignWithdrawalAction) - Validator withdrawal signatures - [VoteEthFinalizedWithdrawalAction](./VoteEthFinalizedWithdrawalAction) - Finalized withdrawal votes - [usdSend](./usdSend) - Internal USD transfers --- ## Hyperliquid gRPC API Dwellir provides a high-performance gRPC API for streaming real-time blockchain and trading data from Hyperliquid L1 Gateway. Built on Protocol Buffers, this service offers low-latency access to blocks, fills, and order book snapshots. :::tip Code Examples Available Complete working examples in Go, Python, and Node.js are available in our [gRPC Code Examples Repository](https://github.com/dwellir-public/gRPC-code-examples). Clone the repo to get started quickly. ::: ## Available Endpoints The gRPC API provides six distinct endpoints for accessing Hyperliquid data: | Endpoint | Type | Best For | |----------|------|----------| | [**StreamBlocks**](/hyperliquid/stream_blocks) | Streaming | Real-time blockchain monitoring, block explorers, analytics | | [**StreamFills**](/hyperliquid/stream_fills) | Streaming | Order execution tracking, trade settlement, PnL calculation | | [**StreamOrderbookSnapshots**](/hyperliquid/stream_orderbook_snapshots) | Streaming | Market depth monitoring, liquidity analysis, arbitrage | | [**GetBlock**](/hyperliquid/get_block) | Unary | Point-in-time block data, backtesting, historical analysis | | [**GetFills**](/hyperliquid/get_fills) | Unary | Point-in-time fill data, reconciliation, auditing | | [**GetOrderBookSnapshot**](/hyperliquid/get_order_book_snapshot) | Unary | Point-in-time market state, backtesting, historical analysis | ### StreamBlocks Stream continuous block data from the Hyperliquid blockchain. Each block contains transaction data, execution results, and state changes. **Ideal for:** - Block explorer backends - Blockchain analytics and metrics - Compliance and auditing systems - Real-time network monitoring [**View StreamBlocks Documentation →**](/hyperliquid/stream_blocks) ### StreamFills Stream fill data for executed orders as they occur on the network. **Ideal for:** - Order execution monitoring - Trade settlement tracking - PnL calculation systems - Execution quality analysis [**View StreamFills Documentation →**](/hyperliquid/stream_fills) ### StreamOrderbookSnapshots Stream continuous order book snapshots showing complete market depth. **Ideal for:** - Real-time market depth monitoring - Liquidity analysis - Market making strategies - Arbitrage detection [**View StreamOrderbookSnapshots Documentation →**](/hyperliquid/stream_orderbook_snapshots) ### GetBlock Retrieve a single block at a specific position. **Ideal for:** - Point-in-time blockchain analysis - Backtesting with historical block data - Auditing and compliance verification - Debugging specific transactions [**View GetBlock Documentation →**](/hyperliquid/get_block) ### GetFills Retrieve fills at a specific position. **Ideal for:** - Trade reconciliation - Historical fill analysis - PnL verification at specific points - Audit trail generation [**View GetFills Documentation →**](/hyperliquid/get_fills) ### GetOrderBookSnapshot Retrieve a single order book snapshot at a specific point in time. **Ideal for:** - Point-in-time market analysis - Backtesting trading strategies - Historical market research - Snapshot-based analytics [**View GetOrderBookSnapshot Documentation →**](/hyperliquid/get_order_book_snapshot) ## StreamBlocks Action Types The `StreamBlocks` endpoint returns blocks containing 47 different action types covering trading, transfers, permissions, staking, and more. Each block contains signed action bundles with their execution responses, allowing you to track both the actions submitted and their outcomes. [**View Action Types Reference →**](/hyperliquid/stream_blocks#action-types-reference) ## Key Features - **Low latency** - gRPC binary protocol with Protocol Buffers for efficient serialization - **Flexible positioning** - Start streams from specific timestamps or block heights - **Complete data** - Access to full block data, fills, and order book snapshots - **Real-time streaming** - Server-side push model for immediate updates - **24-hour retention** - Historical data available within the retention window ## Quick Start Get started with complete working examples in Go, Python, and Node.js from our [gRPC Code Examples Repository](https://github.com/dwellir-public/gRPC-code-examples). The repository includes connection setup, stream handling, and reconnection logic. ## Service Definition ```protobuf syntax = "proto3"; package hyperliquid_l1_gateway.v2; service HyperliquidL1Gateway { // Start a blocks stream from the given Position rpc StreamBlocks(Position) returns (stream Block) {} // Start a fills stream from the given Position rpc StreamFills(Position) returns (stream BlockFills) {} // Start an order book snapshots stream from the given Position rpc StreamOrderbookSnapshots(Position) returns (stream OrderBookSnapshot) {} // Return a single block at the requested Position rpc GetBlock(Position) returns (Block) {} // Return fills at the requested Position rpc GetFills(Position) returns (BlockFills) {} // Return an order book snapshot at the requested Timestamp rpc GetOrderBookSnapshot(Timestamp) returns (OrderBookSnapshot) {} } message Position { // Leave all fields unset or zero to target the latest data. oneof position { int64 timestamp_ms = 1; // ms since Unix epoch, inclusive int64 block_height = 2; // block height, inclusive } } message Timestamp { int64 timestamp_ms = 1; } message Block { // JSON-encoded Hyperliquid block from "replica_cmds". bytes data = 1; } message OrderBookSnapshot { // JSON-encoded Hyperliquid order book snapshot. bytes data = 1; } message BlockFills { // JSON-encoded object from "node_fills" or "node_fills_by_block". bytes data = 1; } ``` ## Connection Best Practices :::warning Implement Reconnection Logic Streams may disconnect due to network issues or server maintenance. Your client must include automatic reconnection with exponential backoff. See our [gRPC Code Examples](https://github.com/dwellir-public/gRPC-code-examples) for production-ready reconnection patterns. ::: ## Important Notes ### Current Limitations 1. **Data Retention**: The node maintains only 24 hours of historical data 2. **Position Parameter**: Supports both `timestamp_ms` and `block_height` for flexible stream positioning 3. **Historical Queries**: Historical data within the retention window can be queried using the Position message ### Testing Tools A Go testing application is available for customers who want to test the streaming functionality. This is a 16MB binary that prints stream data to the terminal. Contact our support team to obtain this testing tool. ## Resources - **[GitHub: gRPC Code Examples](https://github.com/dwellir-public/gRPC-code-examples)** - Complete working examples in Go, Python, and Node.js - **[Copy Trading Bot Example](https://github.com/dwellir-public/gRPC-code-examples/tree/main/copy-trading-bot)** - Production-ready copy trading implementation - Proto definition files available upon request ### Need Help? - **Email**: support@dwellir.com - **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com) --- *Stream real-time Hyperliquid blockchain data with Dwellir's enterprise-grade gRPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)* --- ## Archival Data - Raw Blockchain & Trade Data Complete raw Hyperliquid data in native formats, providing full blockchain state and trade execution history for replay, compliance, and research. ## Available Raw Data Archives | Archive | Available From | Format | Contents | |---------|----------------|--------|----------| | **Replica Commands** | January 2025 | `replica_cmds` | Complete blockchain state, all transactions, validator signatures | | **Node Trades** | March 22 - May 25, 2025 | `node_trades` | Basic trade execution data with both sides | | **Node Fills** | May 25 - July 27, 2025 | `node_fills` | Enhanced fills with PnL and fee tracking | | **Node Fills by Block** | July 27, 2025 - Current | `node_fills_by_block` | Block-organized fills with builder info | --- ## Replica Commands Format The `replica_cmds` format provides the most comprehensive view of Hyperliquid blockchain activity, identical to data streamed via [StreamBlocks gRPC](/hyperliquid/stream_blocks). **Available from**: January 2025 - Current ### What's Included - **Block Headers**: Height, timestamp, proposer address, hardfork version - **Signed Action Bundles**: All user-submitted transactions with cryptographic signatures - **Execution Responses**: Order statuses, fill confirmations, error messages - **State Changes**: Position updates, balance modifications, liquidations - **Consensus Data**: Validator votes, block proposals, finalization records ### Data Structure ```json { "abci_block": { "time": "2025-09-08T06:41:57.997372546", "round": 992814678, "parent_round": 992814677, "proposer": "0x5ac99df645f3414876c816caa18b2d234024b487", "hardfork": { "version": 57, "round": 990500929 }, "signed_action_bundles": [ [ "0xb4b1f5a9c233f9d90fd24b9961fd12708b36cc3d56f8fda47f32b667ee8d1227", { "signed_actions": [ { "signature": { "r": "0xd931f13565ae66c3bc41a05da4180bb795dbd9ed2d365efaf639fd23b3774ac6", "s": "0x4a7a0534bf0a4238dfe404a88d335ab4c9b8222909100d773635e328d2ab864c", "v": 27 }, "action": { "type": "order", "orders": [{ "a": 170, "b": true, "p": "0.038385", "s": "1514", "r": false, "t": { "limit": { "tif": "Ioc" } }, "c": "0x7192c49bcadb32d394e38617ea99cc09" }] }, "nonce": 1757313597362 } ], "broadcaster": "0x67e451964e0421f6e7d07be784f35c530667c2b3", "broadcaster_nonce": 1757313597367 } ] ] }, "resps": { "Full": [ [ "0xb4b1f5a9c233f9d90fd24b9961fd12708b36cc3d56f8fda47f32b667ee8d1227", [ { "user": "0xecb63caa47c7c4e77f60f1ce858cf28dc2b82b00", "res": { "status": "ok", "response": { "type": "order", "data": { "statuses": [{ "filled": { "totalSz": "1514.0", "avgPx": "0.038385", "oid": 156190414943, "cloid": "0x7192c49bcadb32d394e38617ea99cc09" } }] } } } } ] ] ] } } ``` ### Field Reference **Top-Level Fields:** - `abci_block`: Block header and transaction data - `time`: ISO-8601 timestamp with nanosecond precision - `round`: Current block number (height) - `parent_round`: Previous block number - `proposer`: Block proposer address (40 hex chars) - `hardfork`: Protocol version information - `signed_action_bundles`: Array of transaction bundles - `resps`: Execution responses for all actions - `Full`: Array matching structure of `signed_action_bundles` - Each response includes user address and result status **Action Types:** - `order`: Place limit/market orders - `cancel`: Cancel orders by order ID - `cancelByCloid`: Cancel orders by client order ID - `batchModify`: Modify multiple orders - `evmRawTx`: Execute EVM transactions For complete field documentation, see the [StreamBlocks reference](/hyperliquid/stream_blocks). ### Use Cases - **Complete Blockchain Replay**: Reconstruct full blockchain state from genesis - **Transaction Analysis**: Analyze all transaction types and execution patterns - **State Verification**: Verify blockchain state transitions - **Order Book Reconstruction**: Rebuild historical order book states - **Protocol Research**: Study consensus behavior and validator activity - **Compliance & Auditing**: Maintain complete audit trails with cryptographic signatures --- ## Node Trades Format **Available**: March 22, 2025 - May 25, 2025 The `node_trades` format captures basic trade execution data with information for both sides of each trade. ```json { "coin": "PURR", "side": "B", "time": "2025-03-22T23:00:00.000984711", "px": "0.12928", "sz": "1547.0", "hash": "0x0000000000000000000000000000000000000000000000000000000000000000", "trade_dir_override": "Na", "side_info": [ { "user": "0xa68c548f3acd23a7fe3e867cc47f302559794419", "start_pos": "2462968.0", "oid": 81305166697, "twap_id": 568722, "cloid": null }, { "user": "0xecb63caa47c7c4e77f60f1ce858cf28dc2b82b00", "start_pos": "-15493993.0", "oid": 81305141429, "twap_id": null, "cloid": "0x6640b7cba22f65c630e7fb18b18819b6" } ] } ``` **Field Descriptions:** | Field | Description | |-------|-------------| | `coin` | Trading pair symbol | | `side` | Buy (B) or Sell (A) | | `time` | Execution timestamp (ISO 8601) | | `px` | Execution price | | `sz` | Trade size | | `hash` | Transaction hash | | `trade_dir_override` | Direction override flag | | `side_info` | Array containing details for both sides | | `side_info[].user` | Wallet address | | `side_info[].start_pos` | Position before trade | | `side_info[].oid` | Order ID | | `side_info[].twap_id` | TWAP order ID (if applicable) | | `side_info[].cloid` | Client order ID | --- ## Node Fills Format **Available**: May 25, 2025 - July 27, 2025 The `node_fills` format includes comprehensive fill information with PnL calculations and fee tracking. ```json [ "0xe3b6e3443c8f2080704e7421bad9340f13950acb", { "coin": "ETH", "px": "2511.2", "sz": "0.486", "side": "B", "time": 1748183573109, "startPosition": "-946.9372", "dir": "Close Short", "closedPnl": "-2.5515", "hash": "0x71fe8c1aa48f3a43971504242beb2502023600245b77a4f664b49f10a236d9e2", "oid": 97128733943, "crossed": false, "fee": "-0.036613", "tid": 995829841758483, "cloid": "0x00000000000000002bca2ffb27459396", "feeToken": "USDC" } ] ``` **Field Descriptions:** | Field | Description | |-------|-------------| | First element | User wallet address | | `coin` | Trading pair | | `px` | Fill price | | `sz` | Fill size | | `side` | Buy (B) or Ask (A) | | `time` | Unix timestamp (milliseconds) | | `startPosition` | Position before fill | | `dir` | Trade direction (Open Long, Close Short, etc.) | | `closedPnl` | Realized PnL from closed positions | | `hash` | Transaction hash | | `oid` | Order ID | | `crossed` | Whether order crossed the spread | | `fee` | Trading fee (negative for rebate) | | `tid` | Trade ID | | `cloid` | Client order ID | | `feeToken` | Currency used for fees | --- ## Node Fills by Block Format **Available**: July 27, 2025 - Current The current `node_fills_by_block` format organizes fills within block context with builder information. ```json { "local_time": "2025-07-27T08:50:10.334741319", "block_time": "2025-07-27T08:50:10.273720809", "block_number": 676607012, "events": [ [ "0x7839e2f2c375dd2935193f2736167514efff9916", { "coin": "BTC", "px": "118136.0", "sz": "0.00009", "side": "B", "time": 1753606210273, "startPosition": "-1.41864", "dir": "Close Short", "closedPnl": "-0.003753", "hash": "0xe7822040155eaa2e737e042854342401120052bbf063906ce8c8f3babe853a79", "oid": 121670079265, "crossed": false, "fee": "-0.000212", "tid": 161270588369408, "cloid": "0x09367b9f8541c581f95b02aaf05f1508", "feeToken": "USDC", "builder": "0x49ae63056b3a0be0b166813ee687309ab653c07c", "builderFee": "0.005528" } ] ] } ``` **Field Descriptions:** | Field | Description | |-------|-------------| | `local_time` | Local server timestamp | | `block_time` | Blockchain block timestamp | | `block_number` | Block height | | `events` | Array of fill events in the block | | `events[][0]` | User wallet address | | `events[][1].coin` | Trading pair | | `events[][1].px` | Fill price | | `events[][1].sz` | Fill size | | `events[][1].side` | Buy (B) or Ask (A) | | `events[][1].time` | Unix timestamp (milliseconds) | | `events[][1].startPosition` | Position before fill | | `events[][1].dir` | Trade direction | | `events[][1].closedPnl` | Realized PnL | | `events[][1].hash` | Transaction hash | | `events[][1].oid` | Order ID | | `events[][1].crossed` | Whether order crossed spread | | `events[][1].fee` | Trading fee | | `events[][1].tid` | Trade ID | | `events[][1].cloid` | Client order ID | | `events[][1].feeToken` | Fee currency | | `events[][1].builder` | Block builder address | | `events[][1].builderFee` | Fee paid to builder | --- ## Delivery Options | Method | Status | Description | |--------|--------|-------------| | **Bulk Download** | Available | S3/GCS bucket access | | **REST API** | Coming Soon | Query-based access with filtering | ## Data Quality - **Completeness**: No gaps in data from stated availability dates - **Verification**: Data validated against on-chain state - **Format Consistency**: Native Hyperliquid formats preserved exactly ## Related Data Products | Need | Recommendation | |------|----------------| | Pre-aggregated price data | [OHLCV Data](/hyperliquid/ohlcv-data) | | Cleaned tick-by-tick trades | [Tick Data](/hyperliquid/tick-data) | | Real-time order book | [Order Book Server](/hyperliquid/order-book-server) | ## Access Contact the Dwellir team for archival data access: **Email**: ben@dwellir.com Include in your request: - Data type(s) needed (replica_cmds, node_trades, node_fills, node_fills_by_block) - Date range required - Delivery preference (bulk download or streaming) - Use case description --- ## Historical Data - Hyperliquid Market Archives # Historical Data Dwellir provides comprehensive historical data for Hyperliquid, ranging from complete blockchain archives to pre-processed market data formats optimized for specific use cases. ## Available Data Products ### Archival Data (Raw) Complete raw data in native Hyperliquid formats. | Attribute | Value | |-----------|-------| | **Available From** | January 2025 (replica_cmds), March 2025 (trade fills) | | **Formats** | replica_cmds, node_trades, node_fills, node_fills_by_block | | **Contents** | Full blockchain state, all transactions, trade fills with PnL | | **Best For** | Blockchain replay, compliance, protocol research | [View Archival Data Documentation](/hyperliquid/archival-data) --- ### OHLCV Data Pre-aggregated candlestick data for all perpetual markets. | Attribute | Value | |-----------|-------| | **Available Intervals** | 1s, 1m, 5m, 15m, 1h, 4h, 1d | | **Formats** | CSV, Parquet, JSON | | **Fields** | timestamp, open, high, low, close, volume, trades_count, vwap | | **Best For** | Technical analysis, charting, portfolio tracking | [View OHLCV Data Documentation](/hyperliquid/ohlcv-data) --- ### Tick Data Individual trade executions derived from `node_fills_by_block`. | Attribute | Value | |-----------|-------| | **Available From** | July 2025 | | **Precision** | Millisecond timestamps with block sequencing | | **Formats** | CSV, Parquet | | **Fields** | timestamp, pair, price, size, side, trade_id, user_address, block_number | | **Best For** | Backtesting, slippage analysis, market microstructure | [View Tick Data Documentation](/hyperliquid/tick-data) --- ## Choosing the Right Data Format | Use Case | Recommended Product | |----------|---------------------| | Charting and technical analysis | OHLCV Data | | Backtesting execution strategies | Tick Data | | Slippage and market impact analysis | Tick Data | | Blockchain state verification | Archival Data | | Compliance and audit trails | Archival Data | | Portfolio performance tracking | OHLCV Data | | Protocol research | Archival Data | | ML feature engineering | OHLCV Data or Tick Data | | Address tracking | Tick Data | ## Data Quality All historical data products meet Dwellir's quality standards: - **Completeness**: No gaps in data coverage - **Accuracy**: Validated against on-chain state - **Consistency**: Standardized schemas and formats - **Documentation**: Complete field references and examples ## Real-Time Data For live market data, see: - [Order Book Server](/hyperliquid/order-book-server) - Real-time L2/L4 order books and trades - [gRPC Streaming](/hyperliquid/grpc) - StreamBlocks, StreamFills, and more ## Access Contact the Dwellir team for historical data access: **Email**: ben@dwellir.com Include in your request: - Data product(s) needed - Date range - Preferred format - Use case description --- ## OHLCV Data - Aggregated Candlestick Data Pre-aggregated candlestick data (Open, High, Low, Close, Volume) for all Hyperliquid perpetual markets, optimized for charting, technical analysis, and portfolio tracking. ## What is OHLCV Data? OHLCV data aggregates individual trades into time-based intervals, providing standardized price bars used for technical analysis and charting. Each candle summarizes all trading activity within its time window. ## Available Intervals | Interval | Description | Typical Use Case | |----------|-------------|------------------| | 1s | 1 second | High-frequency strategy analysis | | 1m | 1 minute | Intraday trading, scalping | | 5m | 5 minutes | Day trading, short-term trends | | 15m | 15 minutes | Swing trade entries | | 1h | 1 hour | Intraday trend analysis | | 4h | 4 hours | Swing trading, key levels | | 1d | 1 day | Portfolio tracking, long-term trends | ## Available Markets OHLCV data covers all perpetual contracts on Hyperliquid, including: **Major Pairs** - BTC-PERP - ETH-PERP - SOL-PERP - ARB-PERP - DOGE-PERP - AVAX-PERP - MATIC-PERP - LINK-PERP - OP-PERP - APT-PERP **Full Coverage** All perpetual markets listed on Hyperliquid are available, including newly launched pairs. ## Data Schema ``` timestamp, open, high, low, close, volume, trades_count, vwap ``` | Field | Type | Description | |-------|------|-------------| | `timestamp` | ISO-8601 | Candle open time (UTC) | | `open` | decimal | First trade price in interval | | `high` | decimal | Highest trade price in interval | | `low` | decimal | Lowest trade price in interval | | `close` | decimal | Last trade price in interval | | `volume` | decimal | Total volume traded (in base currency) | | `trades_count` | integer | Number of trades in interval | | `vwap` | decimal | Volume-weighted average price | ### Example Record ```csv timestamp,open,high,low,close,volume,trades_count,vwap 2025-01-15T14:00:00Z,96543.20,96891.50,96482.10,96789.00,1247.832,8421,96672.15 2025-01-15T15:00:00Z,96789.00,97102.80,96654.30,97045.60,1532.109,9876,96912.44 ``` ```json [ { "timestamp": "2025-01-15T14:00:00Z", "open": "96543.20", "high": "96891.50", "low": "96482.10", "close": "96789.00", "volume": "1247.832", "trades_count": 8421, "vwap": "96672.15" }, { "timestamp": "2025-01-15T15:00:00Z", "open": "96789.00", "high": "97102.80", "low": "96654.30", "close": "97045.60", "volume": "1532.109", "trades_count": 9876, "vwap": "96912.44" } ] ``` ``` message ohlcv { required int64 timestamp (TIMESTAMP_MILLIS); required double open; required double high; required double low; required double close; required double volume; required int32 trades_count; required double vwap; } ``` ## Available Formats | Format | Best For | Compression | |--------|----------|-------------| | **CSV** | Quick analysis, spreadsheet import | Gzip available | | **Parquet** | Large datasets, columnar queries | Native compression | | **JSON** | API integration, web applications | Gzip available | Parquet format recommended for datasets larger than 1GB due to efficient compression and columnar query performance. ## Delivery Options | Method | Status | Description | |--------|--------|-------------| | **Bulk Download** | Available | Full historical archive with daily updates | | **REST API** | Coming Soon | Query by symbol, interval, date range | ## Use Cases ### Technical Analysis Build charts with standard candlestick patterns, moving averages, and technical indicators. The VWAP field enables institutional-grade analysis without additional computation. ### Portfolio Tracking Track portfolio performance over time with daily OHLCV data. Calculate returns, volatility, and correlation metrics across your holdings. ### ML Feature Engineering Generate features for machine learning models including price momentum, volatility regimes, and pattern recognition inputs. Multiple timeframes enable multi-scale feature construction. ### Dashboard Development Power trading dashboards and monitoring tools with consistent, pre-aggregated data. Reduce client-side computation and database load. ## Sample Data A sample dataset is available for evaluation: **Sample Contents:** - 24 hours of 1-minute data for BTC-PERP - All fields included - CSV and Parquet formats Contact ben@dwellir.com to request sample data. ## Related Data Products | Need | Recommendation | |------|----------------| | Individual trade executions | [Tick Data](/hyperliquid/tick-data) | | Complete blockchain state | [Archival Data](/hyperliquid/archival-data) | | Real-time price updates | [Order Book Server](/hyperliquid/order-book-server) | ## Data Quality - **Completeness**: Continuous data with no gaps in trading hours - **Accuracy**: Aggregated from verified tick-level trade data - **Consistency**: Standardized schema across all symbols and intervals ## Access Contact the Dwellir team for OHLCV data access: **Email**: ben@dwellir.com Include in your request: - Symbols required (or "all perpetuals") - Intervals needed - Date range - Preferred format (CSV, Parquet, JSON) - Delivery preference (API access or bulk download) --- ## Tick Data - Historical Trade Executions Every individual trade execution on Hyperliquid, derived from `node_fills_by_block` data and processed into a clean, analysis-ready format. ## What is Tick Data? Tick data captures each individual trade as it occurs on the exchange. Unlike aggregated OHLCV data, tick data preserves the exact sequence, timing, and size of every execution, providing the highest resolution view of market activity. **Available Range:** July 2025 - Current (aligned with `node_fills_by_block`) **Source Format:** Derived from [node_fills_by_block](/hyperliquid/archival-data#node-fills-by-block-format) archival data ## Source Data Format Tick data is extracted from the `node_fills_by_block` format: ```json { "local_time": "2025-07-27T08:50:10.334741319", "block_time": "2025-07-27T08:50:10.273720809", "block_number": 676607012, "events": [ [ "0x7839e2f2c375dd2935193f2736167514efff9916", { "coin": "BTC", "px": "118136.0", "sz": "0.00009", "side": "B", "time": 1753606210273, "startPosition": "-1.41864", "dir": "Close Short", "closedPnl": "-0.003753", "hash": "0xe7822040155eaa2e737e042854342401120052bbf063906ce8c8f3babe853a79", "oid": 121670079265, "crossed": false, "fee": "-0.000212", "tid": 161270588369408, "cloid": "0x09367b9f8541c581f95b02aaf05f1508", "feeToken": "USDC", "builder": "0x49ae63056b3a0be0b166813ee687309ab653c07c", "builderFee": "0.005528" } ] ] } ``` ## Processed Tick Data Schema Dwellir processes `node_fills_by_block` into a simplified tick format optimized for analysis: ``` timestamp, pair, price, size, side, trade_id, user_address, block_number ``` | Field | Type | Description | |-------|------|-------------| | `timestamp` | milliseconds | Trade execution time (from `time` field) | | `pair` | string | Trading pair (from `coin` field, e.g., BTC-PERP) | | `price` | decimal | Execution price (from `px`) | | `size` | decimal | Trade size (from `sz`) | | `side` | string | Buy (B) or Ask (A) | | `trade_id` | integer | Unique trade identifier (from `tid`) | | `user_address` | hex | User wallet address | | `block_number` | integer | Block height for sequencing | ### Timestamp Precision Timestamps are recorded in milliseconds from the source `time` field. Block-level ordering provides additional sequencing precision. ### Example Records ```csv timestamp,pair,price,size,side,trade_id,user_address,block_number 1753606210273,BTC-PERP,118136.0,0.00009,B,161270588369408,0x7839e2f2c375dd2935193f2736167514efff9916,676607012 1753606210274,BTC-PERP,118136.5,0.00025,B,161270588369409,0xa68c548f3acd23a7fe3e867cc47f302559794419,676607012 1753606210275,BTC-PERP,118135.8,0.00010,A,161270588369410,0x5ac99df645f3414876c816caa18b2d234024b487,676607013 ``` ```json [ { "timestamp": 1753606210273, "pair": "BTC-PERP", "price": "118136.0", "size": "0.00009", "side": "B", "trade_id": 161270588369408, "user_address": "0x7839e2f2c375dd2935193f2736167514efff9916", "block_number": 676607012 }, { "timestamp": 1753606210274, "pair": "BTC-PERP", "price": "118136.5", "size": "0.00025", "side": "B", "trade_id": 161270588369409, "user_address": "0xa68c548f3acd23a7fe3e867cc47f302559794419", "block_number": 676607012 } ] ``` ``` message tick_data { required int64 timestamp; required binary pair (UTF8); required double price; required double size; required binary side (UTF8); required int64 trade_id; required binary user_address (UTF8); required int64 block_number; } ``` ## Extended Fields (Optional) For advanced use cases, additional fields from the source data can be included: | Field | Description | |-------|-------------| | `dir` | Trade direction (Open Long, Close Short, etc.) | | `closedPnl` | Realized PnL from closed positions | | `fee` | Trading fee | | `crossed` | Whether order crossed the spread | | `builder` | Block builder address | | `builderFee` | Fee paid to builder | ## Data Volume Hyperliquid processes significant trading volume. Typical daily volumes: | Metric | Approximate Value | |--------|-------------------| | Daily trades | 5-15 million | | Daily file size (compressed) | 500MB - 2GB | | Peak trades per second | 10,000+ | Parquet format recommended for datasets larger than 1GB due to compression efficiency and columnar query performance. ## Available Formats | Format | Compression | Best For | |--------|-------------|----------| | **CSV** | Gzip | Quick analysis, streaming ingestion | | **Parquet** | Snappy/Zstd | Large-scale analysis, columnar queries | ## Delivery Options | Method | Status | Description | |--------|--------|-------------| | **Bulk Download** | Available | Historical archive files with daily updates | | **REST API** | Coming Soon | Query-based access with filtering | ## Use Cases ### Backtesting Execution Strategies Test execution algorithms against real historical fills. Measure expected slippage, fill rates, and execution quality at specific order sizes. ### Slippage Analysis Calculate actual slippage for different order sizes and market conditions. Build slippage models for execution cost estimation. ### Market Impact Modelling Study how order flow affects prices. Measure temporary and permanent impact for different trade sizes and market states. ### Address Tracking and Flow Analysis Identify large traders and track their activity patterns. Monitor address-level flow for market intelligence. ### Cumulative Delta Analysis Compute buy/sell volume imbalances in real-time. Track order flow momentum and divergences. ## Derived Metrics In addition to raw tick data, derived metrics are available: | Metric | Description | |--------|-------------| | **Buy/Sell Volume** | Per-interval volume breakdown by side | | **Large Trade Flags** | Trades exceeding configurable size thresholds | | **Cumulative Delta** | Running sum of signed volume | | **VWAP** | Volume-weighted average price per interval | ## Sample Data A sample dataset is available for evaluation: **Sample Contents:** - 1 hour of tick data for BTC-PERP and ETH-PERP - All fields included - CSV and Parquet formats Contact ben@dwellir.com to request sample data. ## Related Data Products | Need | Recommendation | |------|----------------| | Aggregated price bars | [OHLCV Data](/hyperliquid/ohlcv-data) | | Raw source data | [Archival Data](/hyperliquid/archival-data) | | Real-time trade stream | [Order Book Server - Trades](/hyperliquid/trades) | ## Data Quality - **Completeness**: Every fill from July 2025 onwards - **Sequence Integrity**: Trade IDs are strictly sequential within blocks - **Timestamp Accuracy**: Millisecond precision from source `time` field ## Access Contact the Dwellir team for tick data access: **Email**: ben@dwellir.com Include in your request: - Symbols required (or "all perpetuals") - Date range - Preferred format (CSV or Parquet) - Fields needed (core or extended) - Filtering requirements (optional: size thresholds, specific addresses) - Delivery preference (bulk download or streaming) --- ## Raw Data Summary - Available Archives # Raw Data Summary Dwellir provides access to Hyperliquid's complete raw data archives. This page summarizes what's available. ## Available Raw Data | Data Type | Available From | Description | |-----------|----------------|-------------| | **Replica Commands** | January 2025 - Current | Complete blockchain state, all transactions, validator signatures | | **Node Trades** | March 22 - May 25, 2025 | Basic trade records with both counterparty details | | **Node Fills** | May 25 - July 27, 2025 | Enhanced fills with PnL and fee tracking | | **Node Fills by Block** | July 27, 2025 - Current | Block-organized fills with builder info | ## Data Products ### Raw Archival Data Native Hyperliquid formats preserved exactly as recorded. Suitable for blockchain replay, compliance, and protocol research. **[View Archival Data Documentation](/hyperliquid/archival-data)** - Complete format specifications and field references. ### Processed Data Products Dwellir also offers processed data derived from raw archives: | Product | Description | Documentation | |---------|-------------|---------------| | **OHLCV Data** | Pre-aggregated candlesticks (1s to 1d intervals) | [OHLCV Data](/hyperliquid/ohlcv-data) | | **Tick Data** | Cleaned individual trade executions | [Tick Data](/hyperliquid/tick-data) | ## Quick Reference ### Replica Commands - Complete blockchain state from genesis - All transaction types with signatures - Execution responses and order statuses - Identical to StreamBlocks gRPC format ### Trade Fill Archives **Node Trades** (March - May 2025) - Both sides of each trade included - TWAP order tracking - Position data before trade **Node Fills** (May - July 2025) - Single-sided fill records - Realized PnL calculations - Fee tracking with token type **Node Fills by Block** (July 2025 - Current) - Fills organized by block number - Block timestamps (local and chain) - Builder address and builder fees - Current production format ## Access Contact the Dwellir team for data access: **Email**: ben@dwellir.com Include in your request: - Data type(s) needed - Date range - Delivery preference (bulk download or streaming) - Use case description --- ## Hyperliquid - High-Performance Trading Infrastructure # Hyperliquid - Ultra-Fast Layer 1 with EVM Support L1 gRPC Streaming API {'Stream real-time blocks, fills, and order book snapshots directly from Hyperliquid L1. Ideal for algorithmic trading, market making, and low-latency data pipelines.'} → Order Book WebSocket API {'Ultra-low latency L2 and L4 order book data over WebSocket from edge servers in Singapore and Tokyo. Built for HFT, spread monitoring, and market-depth visualization.'} → HyperEVM JSON-RPC API {'Full Ethereum-compatible RPC interface for deploying Solidity smart contracts, querying on-chain state, and integrating with standard EVM tooling like Ethers.js and Hardhat.'} → ## Why Build on Hyperliquid? Hyperliquid is a high-performance Layer 1 blockchain purpose-built for decentralized trading, offering both EVM compatibility through HyperEVM and specialized L1 features through gRPC streaming. ### **Blazing Fast Performance** - **Sub-second finality** - Near-instant transaction confirmations - **200,000 orders/second** - Unprecedented throughput for DeFi - **Predictable low fees** - Stable and minimal transaction costs ### **Dual API Architecture** - **HyperEVM** - Full EVM compatibility for Solidity smart contracts - **L1 gRPC Streaming** - Real-time order books and market data - **Native Trading Primitives** - Built-in support for spot and perpetuals ### **Trading-Optimized Infrastructure** - **Fully on-chain order books** - No off-chain components - **HyperBFT consensus** - Optimized for trading performance - **Real-time market data** - Stream fills, trades, and order updates ## Quick Start with Hyperliquid