# 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
VIDEO
Hyperliquid is available through Dwellir's dedicated nodes, offering both HyperEVM JSON-RPC and L1 gRPC streaming:
### Installation & Setup
```javascript
// Connect to HyperEVM via dedicated node
const provider = new JsonRpcProvider(
'https://YOUR_DEDICATED_NODE.hyperliquid.dwellir.com/YOUR_API_KEY'
);
// Deploy and interact with Solidity contracts
const contract = new Contract(address, abi, provider);
const result = await contract.someMethod();
```
```go
"context"
"crypto/tls"
pb "your-project/hyperliquid_l1_gateway/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
// Connect to L1 Gateway for streaming
creds := credentials.NewTLS(&tls.Config{})
conn, err := grpc.Dial(
"YOUR_DEDICATED_NODE.hyperliquid.dwellir.com:443",
grpc.WithTransportCredentials(creds),
)
client := pb.NewHyperliquidL1GatewayClient(conn)
// Get order book snapshot
response, err := client.GetOrderBookSnapshot(
context.Background(),
&pb.Timestamp{Timestamp: 0},
)
```
## Network Information
Chain ID
999
Mainnet
Block Time
< 1 second
Sub-second finality
Gas Token
HYPE
Native token
Consensus
HyperBFT
Trading-optimized
## HyperEVM JSON-RPC API
HyperEVM provides full Ethereum compatibility, supporting all standard JSON-RPC methods for smart contract deployment and interaction.
### EVM Integration Examples
```solidity
// Deploy custom trading logic on HyperEVM
contract TradingStrategy {
function executeTrade(
address tokenA,
address tokenB,
uint256 amount
) external {
// Your trading logic here
// Access Hyperliquid's native features
}
}
```
```javascript
// Read contract state and market data
const provider = new JsonRpcProvider(HYPERLIQUID_RPC);
// Get current block with trading data
const block = await provider.getBlock('latest');
console.log('Block trades:', block.transactions);
// Query contract for positions
const positions = await contract.getPositions(trader);
```
## Order Book WebSocket API
Access real-time L2 and L4 orderbook data with ultra-low latency from edge servers in Singapore and Tokyo:
{'Orderbook API Overview & Calculator →'}
{'WebSocket API Documentation →'}
## L1 gRPC Streaming API
Access Hyperliquid's native Layer 1 features through our specialized gRPC interface:
{'View Complete gRPC Reference →'}
### Available gRPC Streams
- **Order Book Snapshots** - Full depth market data
- **Block Streaming** - Real-time block updates
- **Trade Streams** - Live trade execution data
- **Fill Streams** - Order fill notifications
### Quick gRPC Example
```go
"context"
"crypto/tls"
pb "your-project/hyperliquid_l1_gateway/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
// Connect to L1 Gateway for streaming
creds := credentials.NewTLS(&tls.Config{})
conn, err := grpc.Dial(
"YOUR_DEDICATED_NODE.hyperliquid.dwellir.com:443",
grpc.WithTransportCredentials(creds),
)
client := pb.NewHyperliquidL1GatewayClient(conn)
// Get order book snapshot
response, err := client.GetOrderBookSnapshot(
context.Background(),
&pb.Timestamp{Timestamp: 0},
)
```
```python
from hyperliquid_l1_gateway_pb2 import Timestamp
from hyperliquid_l1_gateway_pb2_grpc import HyperliquidL1GatewayStub
# Create gRPC channel
channel = grpc.secure_channel(
'YOUR_DEDICATED_NODE.hyperliquid.dwellir.com:443',
grpc.ssl_channel_credentials()
)
stub = HyperliquidL1GatewayStub(channel)
# Get order book snapshot
timestamp = Timestamp(timestamp=0)
response = stub.GetOrderBookSnapshot(timestamp)
data = json.loads(response.data)
print(f"Order book snapshot: {data}")
```
## Common Integration Patterns
### **Algorithmic Trading**
Combine HyperEVM smart contracts with L1 streaming for sophisticated trading:
```javascript
// Deploy strategy contract via HyperEVM
const strategy = await deployContract(strategyABI, strategyBytecode);
// Stream blocks via gRPC for trading data
const blockStream = grpcClient.StreamBlocks();
blockStream.on('data', async (block) => {
const signal = analyzeBlockData(block);
if (signal.shouldTrade) {
await strategy.executeTrade(signal.params);
}
});
```
### **Market Making**
Provide liquidity using real-time data:
```python
# Monitor block data via gRPC
for block in stub.StreamBlocks(timestamp):
data = analyze_block(block)
if data.spread > target_spread:
# Place orders via HyperEVM
place_limit_orders(provider, spread)
```
### **DeFi Composability**
Build complex DeFi applications:
```solidity
// Leverage Hyperliquid's native features
contract YieldVault {
function harvestAndCompound() external {
// Access perpetuals for hedging
// Use spot for liquidity
// Compound yields automatically
}
}
```
## Use Cases
### **Perpetuals Trading**
Leverage Hyperliquid's native perpetuals with up to 40x leverage (BTC), fully on-chain order books, and sub-second execution.
### **Spot Trading**
Access deep liquidity for spot markets with minimal slippage and predictable fees.
### **Market Making**
Provide liquidity using HyperEVM smart contracts combined with L1 streaming for optimal spreads.
### **Cross-Chain Arbitrage**
Build bridges and arbitrage bots leveraging Hyperliquid's speed advantage over other chains.
## 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.
Install it with a single command:
```bash
npx skills add dwellir-public/hyperliquid-skills
```
Once installed, the skill automatically activates when your agent encounters Hyperliquid-related tasks. It covers HyperEVM JSON-RPC, the Info API, gRPC streaming, order book WebSocket access, and native API routing for order placement.
- [View on Skills.sh](https://skills.sh/dwellir-public/hyperliquid-skills/hyperliquid)
- [GitHub repository](https://github.com/dwellir-public/hyperliquid-skills)
## Resources & Support
### Developer Resources
- **HyperEVM JSON-RPC** - Full Ethereum-compatible RPC interface
- [L1 gRPC API Reference](/hyperliquid/grpc) - Streaming API documentation
- **Proto Files** - Available upon request for gRPC integration
- **Testing Tools** - 16MB Go binary for stream verification
### API Access
- **Dedicated Nodes** - Contact support@dwellir.com for setup
- **Custom Endpoints** - Isolated infrastructure for your application
- **Uncapped Throughput** - No rate limits on dedicated nodes
### Need Help?
- **Email**: support@dwellir.com
- **HyperEVM Docs**: Standard Ethereum JSON-RPC methods
- **L1 Streaming**: [gRPC API Reference](/hyperliquid/grpc)
- **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com)
---
*Build on Hyperliquid with Dwellir's dedicated nodes - combining HyperEVM smart contracts with L1 streaming data. [Request Access](mailto:support@dwellir.com)*
---
## activeAssetData - HyperCore Info Endpoint
# activeAssetData
Get active asset trading data for a specific user and coin, including leverage configuration, maximum trade sizes, available trading amounts, and current mark price.
## When to Use This Endpoint
The `activeAssetData` endpoint is essential for:
- **Pre-Trade Validation** — Check maximum trade sizes before placing orders
- **Leverage Monitoring** — Query current leverage settings for a user on a specific asset
- **Available Capital** — Determine how much a user can trade on a given asset
- **Price Reference** — Get the current mark price for position calculations
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"activeAssetData"` |
| `user` | `string` | Yes | User's Ethereum wallet address |
| `coin` | `string` | Yes | Asset symbol (e.g., `"BTC"`, `"ETH"`) |
### Example Request
```json
{
"type": "activeAssetData",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f",
"coin": "BTC"
}
```
## Response
### Success Response
```json
{
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f",
"coin": "BTC",
"leverage": {
"type": "cross",
"value": 5,
"rawUsd": null
},
"maxTradeSzs": ["100000.00", "100000.00"],
"availableToTrade": ["50000.00", "50000.00"],
"markPx": "45000.00"
}
```
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `user` | `string` | The queried Ethereum address |
| `coin` | `string` | The queried asset symbol |
| `leverage` | `object` | Current leverage configuration |
| `maxTradeSzs` | `array` | Maximum trade sizes [long, short] as strings |
| `availableToTrade` | `array` | Available trading amounts [long, short] as strings |
| `markPx` | `string` | Current mark price for the asset |
#### Leverage Object
| Field | Type | Description |
|-------|------|-------------|
| `type` | `string` | Leverage mode — `"cross"` or `"isolated"` |
| `value` | `number` | Leverage multiplier (e.g., `5` for 5x) |
| `rawUsd` | `number \| null` | Raw USD value for isolated leverage; `null` for cross leverage |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "activeAssetData",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f",
"coin": "BTC"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getActiveAssetData(userAddress, coin) {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'activeAssetData',
user: userAddress,
coin: coin
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const data = await getActiveAssetData('0x63E8c7C149556D5f34F833419A287bb9Ef81487f', 'BTC');
console.log(`Leverage: ${data.leverage.value}x (${data.leverage.type})`);
console.log(`Mark Price: $${data.markPx}`);
console.log(`Max Long Size: $${data.maxTradeSzs[0]}`);
console.log(`Max Short Size: $${data.maxTradeSzs[1]}`);
console.log(`Available Long: $${data.availableToTrade[0]}`);
console.log(`Available Short: $${data.availableToTrade[1]}`);
```
```python
from typing import Dict
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_active_asset_data(user_address: str, coin: str) -> Dict:
"""Get active asset trading data for a user and coin"""
response = requests.post(
ENDPOINT,
json={
'type': 'activeAssetData',
'user': user_address,
'coin': coin
},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
data = get_active_asset_data('0x63E8c7C149556D5f34F833419A287bb9Ef81487f', 'BTC')
leverage = data['leverage']
print(f"Leverage: {leverage['value']}x ({leverage['type']})")
print(f"Mark Price: ${data['markPx']}")
print(f"Max Long Size: ${data['maxTradeSzs'][0]}")
print(f"Max Short Size: ${data['maxTradeSzs'][1]}")
print(f"Available Long: ${data['availableToTrade'][0]}")
print(f"Available Short: ${data['availableToTrade'][1]}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type ActiveAssetDataRequest struct {
Type string `json:"type"`
User string `json:"user"`
Coin string `json:"coin"`
}
type Leverage struct {
Type string `json:"type"`
Value int `json:"value"`
RawUsd *float64 `json:"rawUsd"`
}
type ActiveAssetDataResponse struct {
User string `json:"user"`
Coin string `json:"coin"`
Leverage Leverage `json:"leverage"`
MaxTradeSzs []string `json:"maxTradeSzs"`
AvailableToTrade []string `json:"availableToTrade"`
MarkPx string `json:"markPx"`
}
func getActiveAssetData(userAddress, coin string) (*ActiveAssetDataResponse, error) {
reqBody, _ := json.Marshal(ActiveAssetDataRequest{
Type: "activeAssetData",
User: userAddress,
Coin: coin,
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result ActiveAssetDataResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
data, err := getActiveAssetData("0x63E8c7C149556D5f34F833419A287bb9Ef81487f", "BTC")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Leverage: %dx (%s)\n", data.Leverage.Value, data.Leverage.Type)
fmt.Printf("Mark Price: $%s\n", data.MarkPx)
fmt.Printf("Max Long Size: $%s\n", data.MaxTradeSzs[0])
fmt.Printf("Max Short Size: $%s\n", data.MaxTradeSzs[1])
fmt.Printf("Available Long: $%s\n", data.AvailableToTrade[0])
fmt.Printf("Available Short: $%s\n", data.AvailableToTrade[1])
}
```
## Common Use Cases
### 1. Pre-Trade Size Validation
Validate order size before submitting:
```javascript
async function validateTradeSize(userAddress, coin, desiredSize, side) {
const data = await getActiveAssetData(userAddress, coin);
const sideIndex = side === 'long' ? 0 : 1;
const maxSize = parseFloat(data.maxTradeSzs[sideIndex]);
const available = parseFloat(data.availableToTrade[sideIndex]);
const isValid = desiredSize <= maxSize && desiredSize <= available;
return {
valid: isValid,
desiredSize: desiredSize,
maxTradeSize: maxSize,
availableToTrade: available,
reason: !isValid
? desiredSize > maxSize
? `Exceeds max trade size ($${maxSize})`
: `Exceeds available capital ($${available})`
: null
};
}
// Usage
const validation = await validateTradeSize(
'0x63E8c7C149556D5f34F833419A287bb9Ef81487f',
'BTC',
25000,
'long'
);
if (!validation.valid) {
console.warn(`Trade rejected: ${validation.reason}`);
}
```
### 2. Leverage Dashboard
Display leverage and trading capacity for multiple assets:
```javascript
async function getLeverageDashboard(userAddress, coins) {
const results = await Promise.all(
coins.map(coin => getActiveAssetData(userAddress, coin))
);
console.log('=== Leverage Dashboard ===\n');
results.forEach(data => {
console.log(`${data.coin}:`);
console.log(` Leverage: ${data.leverage.value}x (${data.leverage.type})`);
console.log(` Mark Price: $${data.markPx}`);
console.log(` Max Long: $${data.maxTradeSzs[0]}`);
console.log(` Max Short: $${data.maxTradeSzs[1]}`);
console.log(` Available Long: $${data.availableToTrade[0]}`);
console.log(` Available Short: $${data.availableToTrade[1]}`);
console.log('');
});
return results;
}
// Usage
await getLeverageDashboard(
'0x63E8c7C149556D5f34F833419A287bb9Ef81487f',
['BTC', 'ETH', 'SOL']
);
```
### 3. Trading Capacity Monitor
Track available trading capacity over time:
```javascript
class TradingCapacityMonitor {
constructor(userAddress, coin) {
this.userAddress = userAddress;
this.coin = coin;
this.history = [];
}
async snapshot() {
const data = await getActiveAssetData(this.userAddress, this.coin);
const record = {
timestamp: new Date().toISOString(),
availableLong: parseFloat(data.availableToTrade[0]),
availableShort: parseFloat(data.availableToTrade[1]),
markPx: parseFloat(data.markPx),
leverage: data.leverage.value
};
this.history.push(record);
return record;
}
getUtilization() {
if (this.history.length === 0) return null;
const latest = this.history[this.history.length - 1];
const first = this.history[0];
return {
currentAvailableLong: latest.availableLong,
currentAvailableShort: latest.availableShort,
changeLong: latest.availableLong - first.availableLong,
changeShort: latest.availableShort - first.availableShort,
snapshots: this.history.length
};
}
}
// Usage
const monitor = new TradingCapacityMonitor(
'0x63E8c7C149556D5f34F833419A287bb9Ef81487f',
'BTC'
);
await monitor.snapshot();
```
### 4. Smart Order Sizing
Calculate optimal order size based on available capacity:
```javascript
async function getOptimalOrderSize(userAddress, coin, side, targetPercent = 0.5) {
const data = await getActiveAssetData(userAddress, coin);
const sideIndex = side === 'long' ? 0 : 1;
const available = parseFloat(data.availableToTrade[sideIndex]);
const maxSize = parseFloat(data.maxTradeSzs[sideIndex]);
const markPrice = parseFloat(data.markPx);
const targetNotional = available * targetPercent;
const clampedNotional = Math.min(targetNotional, maxSize);
const orderSizeInCoin = clampedNotional / markPrice;
return {
coin: coin,
side: side,
orderSizeUsd: clampedNotional.toFixed(2),
orderSizeCoin: orderSizeInCoin.toFixed(6),
markPrice: markPrice,
leverage: data.leverage.value,
percentUsed: ((clampedNotional / available) * 100).toFixed(1)
};
}
// Usage
const order = await getOptimalOrderSize(
'0x63E8c7C149556D5f34F833419A287bb9Ef81487f',
'BTC',
'long',
0.25 // use 25% of available capital
);
console.log(`Order: ${order.orderSizeCoin} ${order.coin} ($${order.orderSizeUsd})`);
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `400 Bad Request` | Missing or invalid parameters | Ensure valid address and coin symbol |
| `422 Unprocessable Entity` | Invalid coin symbol | Check that the coin is listed on Hyperliquid |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Missing required parameter: coin",
"code": "MISSING_PARAMETER"
}
```
### Robust Error Handling
```javascript
async function safeGetActiveAssetData(userAddress, coin, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getActiveAssetData(userAddress, coin);
} catch (error) {
if (error.response?.status === 429) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (error.response?.status === 400) {
throw new Error('Invalid user address or coin symbol');
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Query before trading** — Always check available trade sizes before placing orders
2. **Cache mark prices briefly** — Mark prices change frequently, cache for seconds not minutes
3. **Validate coin symbols** — Use the [meta](./meta) endpoint to get valid coin symbols
4. **Handle both sides** — `maxTradeSzs` and `availableToTrade` arrays contain [long, short] values
5. **Monitor leverage changes** — Leverage mode affects available capital calculations
## Related Endpoints
- [**clearinghouseState**](./clearinghouse-state) — Get full account state with all positions
- [**meta**](./meta) — Get trading pair metadata and valid coin symbols
- [**openOrders**](./open-orders) — Get user's open orders for the asset
- [**userAbstraction**](./user-abstraction) — Check account abstraction mode
---
*Query real-time trading capacity with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## batchClearinghouseStates - HyperCore Info Endpoint
# batchClearinghouseStates
:::tip Custom Endpoint
Batch query perpetual account states for multiple users in a single request. This is a custom endpoint exclusive to Dwellir's HyperCore REST API — it is not available on standard Hyperliquid nodes.
:::
## When to Use This Endpoint
The `batchClearinghouseStates` endpoint is designed for applications that need account state for many users at once. It fans out individual `clearinghouseState` calls concurrently and aggregates the results, so you don't need to manage your own fan-out and error handling.
- **Portfolio Dashboards** — Fetch account states for all tracked wallets in one call
- **Risk Monitoring** — Monitor margin health across a fleet of trading accounts
- **Fund Management** — Aggregate position data across multiple sub-accounts or strategies
- **Multi-DEX Analytics** — Query all DEXes for each user with a single `ALL_DEXES` request
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"batchClearinghouseStates"` |
| `users` | `string[]` | Yes | Non-empty list of wallet addresses |
| `dex` | `string` | No | DEX name. Omit for native DEX. Set to `"ALL_DEXES"` to query all DEXes. |
### User Limits
| Mode | Max Users | Description |
|------|-----------|-------------|
| Single-DEX (no `dex` or a named DEX) | 1000 (default) | One upstream call per user |
| `ALL_DEXES` | 100 (default) | Lower limit because total calls = users × DEXes |
### Example Requests
**Native DEX** (no `dex` field):
```json
{
"type": "batchClearinghouseStates",
"users": [
"0x00f2548cf639e54420e501a35346e8458989e6bd",
"0x010461c14e146ac35fe42271bdc1134ee31c703a",
"0x02159593e155250288a7a1dd5257fc217601ceee"
]
}
```
**Named DEX:**
```json
{
"type": "batchClearinghouseStates",
"users": [
"0x00f2548cf639e54420e501a35346e8458989e6bd",
"0x010461c14e146ac35fe42271bdc1134ee31c703a"
],
"dex": "xyz"
}
```
**All DEXes:**
```json
{
"type": "batchClearinghouseStates",
"users": [
"0x00f2548cf639e54420e501a35346e8458989e6bd",
"0x010461c14e146ac35fe42271bdc1134ee31c703a"
],
"dex": "ALL_DEXES"
}
```
## Response — Single DEX
Both fields are always present. Order matches input order.
| Field | Type | Description |
|-------|------|-------------|
| `successful_states` | `[address, state][]` | Array of two-element tuples. `address` is the wallet address; `state` is the raw upstream `clearinghouseState` object. |
| `failed_wallets` | `string[]` | Addresses whose upstream call failed (timeout, non-200, etc.). |
### Success Response
```json
{
"successful_states": [
[
"0x00f2548cf639e54420e501a35346e8458989e6bd",
{
"marginSummary": {
"accountValue": "0.0",
"totalNtlPos": "0.0",
"totalRawUsd": "0.0",
"totalMarginUsed": "0.0"
},
"crossMarginSummary": {
"accountValue": "0.0",
"totalNtlPos": "0.0",
"totalRawUsd": "0.0",
"totalMarginUsed": "0.0"
},
"crossMaintenanceMarginUsed": "0.0",
"withdrawable": "0.0",
"assetPositions": [],
"time": 1771587392044
}
],
[
"0x010461c14e146ac35fe42271bdc1134ee31c703a",
{
"marginSummary": {
"accountValue": "0.0",
"totalNtlPos": "0.0",
"totalRawUsd": "0.0",
"totalMarginUsed": "0.0"
},
"crossMarginSummary": {
"accountValue": "0.0",
"totalNtlPos": "0.0",
"totalRawUsd": "0.0",
"totalMarginUsed": "0.0"
},
"crossMaintenanceMarginUsed": "0.0",
"withdrawable": "0.0",
"assetPositions": [],
"time": 1771587392044
}
]
],
"failed_wallets": []
}
```
### Partial Failure Response
If some calls fail, those addresses appear in `failed_wallets`:
```json
{
"successful_states": [
[
"0x00f2548cf639e54420e501a35346e8458989e6bd",
{
"marginSummary": { "accountValue": "0.0", "totalNtlPos": "0.0", "totalRawUsd": "0.0", "totalMarginUsed": "0.0" },
"crossMarginSummary": { "accountValue": "0.0", "totalNtlPos": "0.0", "totalRawUsd": "0.0", "totalMarginUsed": "0.0" },
"crossMaintenanceMarginUsed": "0.0",
"withdrawable": "0.0",
"assetPositions": [],
"time": 1771587392044
}
]
],
"failed_wallets": ["0x010461c14e146ac35fe42271bdc1134ee31c703a"]
}
```
## Response — ALL_DEXES
When `dex` is set to `"ALL_DEXES"`, the response shape changes. Each user's state is an object keyed by DEX name.
| Field | Type | Description |
|-------|------|-------------|
| `successful_states` | `[address, dex_map][]` | Array of two-element tuples. `dex_map` is an object keyed by DEX name, each value being the `clearinghouseState` for that DEX. |
| `failed_wallets` | `string[]` | Addresses where **all** DEX calls failed. |
Key semantics:
- The native DEX appears under the key `"native"`.
- **Partial success**: if some DEX calls succeed and others fail for a user, the user is included in `successful_states` with only the DEXes that responded. They do **not** appear in `failed_wallets`.
- **DEX truncation**: if the chain reports more DEXes than `max_dexes`, the list is silently truncated. The response may not cover every DEX on the chain.
### ALL_DEXES Response Example
```json
{
"successful_states": [
[
"0x00f2548cf639e54420e501a35346e8458989e6bd",
{
"native": {
"marginSummary": { "accountValue": "0.0", "totalNtlPos": "0.0", "totalRawUsd": "0.0", "totalMarginUsed": "0.0" },
"crossMarginSummary": { "accountValue": "0.0", "totalNtlPos": "0.0", "totalRawUsd": "0.0", "totalMarginUsed": "0.0" },
"crossMaintenanceMarginUsed": "0.0",
"withdrawable": "0.0",
"assetPositions": [],
"time": 1771587392044
},
"xyz": {
"marginSummary": { "accountValue": "0.0", "totalNtlPos": "0.0", "totalRawUsd": "0.0", "totalMarginUsed": "0.0" },
"crossMarginSummary": { "accountValue": "0.0", "totalNtlPos": "0.0", "totalRawUsd": "0.0", "totalMarginUsed": "0.0" },
"crossMaintenanceMarginUsed": "0.0",
"withdrawable": "0.0",
"assetPositions": [],
"time": 1771587392044
}
}
]
],
"failed_wallets": ["0x010461c14e146ac35fe42271bdc1134ee31c703a"]
}
```
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "batchClearinghouseStates",
"users": [
"0x00f2548cf639e54420e501a35346e8458989e6bd",
"0x010461c14e146ac35fe42271bdc1134ee31c703a",
"0x02159593e155250288a7a1dd5257fc217601ceee"
]
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getBatchClearinghouseStates(users, dex) {
const payload = {
type: 'batchClearinghouseStates',
users
};
if (dex) payload.dex = dex;
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Single-DEX usage
const result = await getBatchClearinghouseStates([
'0x00f2548cf639e54420e501a35346e8458989e6bd',
'0x010461c14e146ac35fe42271bdc1134ee31c703a'
]);
console.log(`Successful: ${result.successful_states.length}`);
console.log(`Failed: ${result.failed_wallets.length}`);
for (const [address, state] of result.successful_states) {
console.log(`${address}: $${state.marginSummary.accountValue}`);
}
// ALL_DEXES usage
const allDexResult = await getBatchClearinghouseStates(
['0x00f2548cf639e54420e501a35346e8458989e6bd'],
'ALL_DEXES'
);
for (const [address, dexMap] of allDexResult.successful_states) {
for (const [dexName, state] of Object.entries(dexMap)) {
console.log(`${address} [${dexName}]: $${state.marginSummary.accountValue}`);
}
}
```
```python
from typing import Dict, List, Optional
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_batch_clearinghouse_states(
users: List[str],
dex: Optional[str] = None
) -> Dict:
"""Get clearinghouse states for multiple users in one request"""
payload = {
'type': 'batchClearinghouseStates',
'users': users
}
if dex:
payload['dex'] = dex
response = requests.post(
ENDPOINT,
json=payload,
headers={
'Content-Type': 'application/json'
},
timeout=30
)
response.raise_for_status()
return response.json()
# Single-DEX usage
result = get_batch_clearinghouse_states([
'0x00f2548cf639e54420e501a35346e8458989e6bd',
'0x010461c14e146ac35fe42271bdc1134ee31c703a'
])
print(f"Successful: {len(result['successful_states'])}")
print(f"Failed: {len(result['failed_wallets'])}")
for address, state in result['successful_states']:
margin = state['marginSummary']
print(f"{address}: ${margin['accountValue']}")
# ALL_DEXES usage
all_dex_result = get_batch_clearinghouse_states(
['0x00f2548cf639e54420e501a35346e8458989e6bd'],
dex='ALL_DEXES'
)
for address, dex_map in all_dex_result['successful_states']:
for dex_name, state in dex_map.items():
print(f"{address} [{dex_name}]: ${state['marginSummary']['accountValue']}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type BatchClearinghouseRequest struct {
Type string `json:"type"`
Users []string `json:"users"`
Dex string `json:"dex,omitempty"`
}
type BatchClearinghouseResponse struct {
SuccessfulStates []json.RawMessage `json:"successful_states"`
FailedWallets []string `json:"failed_wallets"`
}
func getBatchClearinghouseStates(users []string, dex string) (*BatchClearinghouseResponse, error) {
reqBody, _ := json.Marshal(BatchClearinghouseRequest{
Type: "batchClearinghouseStates",
Users: users,
Dex: dex,
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result BatchClearinghouseResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
result, err := getBatchClearinghouseStates(
[]string{
"0x00f2548cf639e54420e501a35346e8458989e6bd",
"0x010461c14e146ac35fe42271bdc1134ee31c703a",
},
"", // empty for native DEX
)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Successful: %d\n", len(result.SuccessfulStates))
fmt.Printf("Failed: %d\n", len(result.FailedWallets))
}
```
## Common Use Cases
### 1. Multi-Account Dashboard
Fetch and display account states for a set of tracked wallets:
```javascript
async function getMultiAccountDashboard(wallets) {
const result = await getBatchClearinghouseStates(wallets);
const dashboard = result.successful_states.map(([address, state]) => ({
address,
accountValue: parseFloat(state.marginSummary.accountValue),
marginUsed: parseFloat(state.marginSummary.totalMarginUsed),
withdrawable: parseFloat(state.marginSummary.withdrawable),
positions: state.assetPositions.length
}));
const totalValue = dashboard.reduce((sum, a) => sum + a.accountValue, 0);
console.log(`Total across ${dashboard.length} accounts: $${totalValue.toFixed(2)}`);
if (result.failed_wallets.length > 0) {
console.warn(`Failed to fetch: ${result.failed_wallets.join(', ')}`);
}
return dashboard;
}
```
### 2. Cross-DEX Position Aggregation
Query all DEXes for a set of users and aggregate positions:
```javascript
async function getCrossDexPositions(wallets) {
const result = await getBatchClearinghouseStates(wallets, 'ALL_DEXES');
for (const [address, dexMap] of result.successful_states) {
console.log(`\n=== ${address} ===`);
for (const [dexName, state] of Object.entries(dexMap)) {
const value = parseFloat(state.marginSummary.accountValue);
const positions = state.assetPositions.length;
console.log(` ${dexName}: $${value.toFixed(2)} (${positions} positions)`);
}
}
}
```
### 3. Batch Risk Monitoring
Monitor margin utilization across many accounts and flag those at risk:
```javascript
async function batchRiskCheck(wallets) {
const result = await getBatchClearinghouseStates(wallets);
const alerts = [];
for (const [address, state] of result.successful_states) {
const margin = state.marginSummary;
const accountValue = parseFloat(margin.accountValue);
const marginUsed = parseFloat(margin.totalMarginUsed);
const utilization = accountValue > 0 ? (marginUsed / accountValue) * 100 : 0;
if (utilization > 80) {
alerts.push({ address, utilization: utilization.toFixed(2), accountValue });
}
}
// Also flag wallets that failed to respond
for (const address of result.failed_wallets) {
alerts.push({ address, error: 'Failed to fetch state' });
}
return alerts;
}
```
## Error Handling
### Errors Specific to This Endpoint
| Condition | Status | Body |
|-----------|--------|------|
| Invalid JSON body | 400 | `{"error":"invalid JSON body"}` |
| Missing or empty `users` | 400 | `{"error":"users must not be empty"}` |
| Too many users (single-DEX) | 413 | `{"error":"too many users"}` |
| Too many users (ALL_DEXES) | 413 | `{"error":"too many users for ALL_DEXES"}` |
| `perpDexs` upstream timeout | 504 | `{"error":"upstream timeout"}` |
| `perpDexs` upstream failure | 502 | `{"error":"upstream unavailable"}` |
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `403 Forbidden` | Type denied in server config | Contact support — this type may be disabled |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
### Robust Error Handling
```javascript
async function safeBatchQuery(users, dex, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getBatchClearinghouseStates(users, dex);
} catch (error) {
if (error.message.includes('413')) {
// Too many users — split into smaller batches
throw new Error(`Reduce batch size. Limit is ${dex === 'ALL_DEXES' ? 100 : 1000} users.`);
} else if (error.message.includes('429')) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Related Endpoints
- [**clearinghouseState**](./clearinghouse-state) — Get account state for a single user
- [**spotClearinghouseState**](./spot-clearinghouse-state) — Get spot trading account state
- [**openOrders**](./open-orders) — Get user's open orders
- [**meta**](./meta) — Get trading pair metadata
---
*Batch query Hyperliquid account states with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## clearinghouseState - HyperCore Info Endpoint
# clearinghouseState
Get comprehensive account state for perpetual trading, including margin summary, open positions, unrealized PnL, and liquidation prices.
> **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 Endpoint
The `clearinghouseState` endpoint is essential for derivatives traders, portfolio managers, and trading platforms who need to:
- **Monitor Account Health** — Track account value, margin usage, and withdrawable balance
- **Risk Management** — Monitor liquidation prices and position exposure
- **Portfolio Analytics** — Calculate unrealized PnL across all positions
- **Trading Bots** — Make automated trading decisions based on account state
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"clearinghouseState"` |
| `user` | `string` | Yes | User's Ethereum wallet address |
| `dex` | `string` | No | Specific DEX identifier (optional) |
### Example Request
```json
{
"type": "clearinghouseState",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}
```
## Response
### Success Response
```json
{
"marginSummary": {
"accountValue": "10000.50",
"totalNtlPos": "5000.25",
"totalRawUsd": "10000.00",
"totalMarginUsed": "2000.00",
"withdrawable": "8000.50"
},
"crossMarginSummary": {
"accountValue": "10000.50",
"totalNtlPos": "5000.25",
"totalRawUsd": "10000.00"
},
"assetPositions": [
{
"position": {
"coin": "BTC",
"szi": "0.5",
"leverage": {
"type": "cross",
"value": 5
},
"entryPx": "40000.00",
"positionValue": "20000.00",
"unrealizedPnl": "500.00",
"liquidationPx": "35000.00"
}
}
]
}
```
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `marginSummary` | `object` | Overall margin information |
| `crossMarginSummary` | `object` | Cross-margin specific summary |
| `assetPositions` | `array` | List of open positions with details |
#### Margin Summary Object
| Field | Type | Description |
|-------|------|-------------|
| `accountValue` | `string` | Total account value in USD |
| `totalNtlPos` | `string` | Total notional position value |
| `totalRawUsd` | `string` | Raw USD balance |
| `totalMarginUsed` | `string` | Total margin currently in use |
| `withdrawable` | `string` | Amount available for withdrawal |
#### Cross Margin Summary Object
| Field | Type | Description |
|-------|------|-------------|
| `accountValue` | `string` | Account value for cross margin |
| `totalNtlPos` | `string` | Total notional position value |
| `totalRawUsd` | `string` | Raw USD balance |
#### Asset Position Object
| Field | Type | Description |
|-------|------|-------------|
| `position` | `object` | Position details |
#### Position Details
| Field | Type | Description |
|-------|------|-------------|
| `coin` | `string` | Asset symbol (e.g., "BTC", "ETH") |
| `szi` | `string` | Signed position size (positive for long, negative for short) |
| `leverage` | `object` | Leverage information with `type` ("cross" or "isolated") and `value` |
| `entryPx` | `string` | Average entry price |
| `positionValue` | `string` | Current position value in USD |
| `unrealizedPnl` | `string` | Unrealized profit and loss |
| `liquidationPx` | `string` | Liquidation price |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "clearinghouseState",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getClearinghouseState(userAddress) {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'clearinghouseState',
user: userAddress
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const state = await getClearinghouseState('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log(`Account Value: $${state.marginSummary.accountValue}`);
console.log(`Margin Used: $${state.marginSummary.totalMarginUsed}`);
console.log(`Withdrawable: $${state.marginSummary.withdrawable}`);
console.log(`Open Positions: ${state.assetPositions.length}`);
// Calculate total unrealized PnL
const totalPnl = state.assetPositions.reduce((sum, pos) => {
return sum + parseFloat(pos.position.unrealizedPnl);
}, 0);
console.log(`Total Unrealized PnL: $${totalPnl.toFixed(2)}`);
```
```python
from typing import Dict
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_clearinghouse_state(user_address: str) -> Dict:
"""Get user's perpetual account state"""
response = requests.post(
ENDPOINT,
json={
'type': 'clearinghouseState',
'user': user_address
},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
state = get_clearinghouse_state('0x63E8c7C149556D5f34F833419A287bb9Ef81487f')
margin = state['marginSummary']
print(f"Account Value: ${margin['accountValue']}")
print(f"Margin Used: ${margin['totalMarginUsed']}")
print(f"Withdrawable: ${margin['withdrawable']}")
print(f"Open Positions: {len(state['assetPositions'])}")
# Calculate total unrealized PnL
total_pnl = sum(
float(pos['position']['unrealizedPnl'])
for pos in state['assetPositions']
)
print(f"Total Unrealized PnL: ${total_pnl:.2f}")
# List all positions
for pos in state['assetPositions']:
p = pos['position']
side = "LONG" if float(p['szi']) > 0 else "SHORT"
print(f"{p['coin']}: {side} {abs(float(p['szi']))} @ ${p['entryPx']} | PnL: ${p['unrealizedPnl']}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type ClearinghouseRequest struct {
Type string `json:"type"`
User string `json:"user"`
}
type MarginSummary struct {
AccountValue string `json:"accountValue"`
TotalNtlPos string `json:"totalNtlPos"`
TotalRawUsd string `json:"totalRawUsd"`
TotalMarginUsed string `json:"totalMarginUsed"`
Withdrawable string `json:"withdrawable"`
}
type Leverage struct {
Type string `json:"type"`
Value int `json:"value"`
}
type Position struct {
Coin string `json:"coin"`
Szi string `json:"szi"`
Leverage Leverage `json:"leverage"`
EntryPx string `json:"entryPx"`
PositionValue string `json:"positionValue"`
UnrealizedPnl string `json:"unrealizedPnl"`
LiquidationPx string `json:"liquidationPx"`
}
type AssetPosition struct {
Position Position `json:"position"`
}
type ClearinghouseState struct {
MarginSummary MarginSummary `json:"marginSummary"`
CrossMarginSummary MarginSummary `json:"crossMarginSummary"`
AssetPositions []AssetPosition `json:"assetPositions"`
}
func getClearinghouseState(userAddress string) (*ClearinghouseState, error) {
reqBody, _ := json.Marshal(ClearinghouseRequest{
Type: "clearinghouseState",
User: userAddress,
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result ClearinghouseState
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
state, err := getClearinghouseState("0x63E8c7C149556D5f34F833419A287bb9Ef81487f")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Account Value: $%s\n", state.MarginSummary.AccountValue)
fmt.Printf("Margin Used: $%s\n", state.MarginSummary.TotalMarginUsed)
fmt.Printf("Withdrawable: $%s\n", state.MarginSummary.Withdrawable)
fmt.Printf("Open Positions: %d\n", len(state.AssetPositions))
for _, assetPos := range state.AssetPositions {
pos := assetPos.Position
fmt.Printf("%s: %s @ $%s | PnL: $%s\n",
pos.Coin, pos.Szi, pos.EntryPx, pos.UnrealizedPnl)
}
}
```
## Common Use Cases
### 1. Check Account Health
Monitor account health and margin utilization:
```javascript
async function checkAccountHealth(userAddress) {
const state = await getClearinghouseState(userAddress);
const margin = state.marginSummary;
const marginUsed = parseFloat(margin.totalMarginUsed);
const accountValue = parseFloat(margin.accountValue);
const utilizationRate = (marginUsed / accountValue) * 100;
return {
healthy: utilizationRate < 80,
utilizationRate: utilizationRate.toFixed(2),
accountValue: accountValue,
marginUsed: marginUsed,
withdrawable: parseFloat(margin.withdrawable)
};
}
// Usage
const health = await checkAccountHealth('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
if (!health.healthy) {
console.warn(`High margin usage: ${health.utilizationRate}%`);
}
```
### 2. Monitor Liquidation Risk
Track liquidation prices for all positions:
```javascript
async function getLiquidationRisks(userAddress, currentPrices) {
const state = await getClearinghouseState(userAddress);
return state.assetPositions.map(pos => {
const position = pos.position;
const currentPrice = currentPrices[position.coin];
const liquidationPrice = parseFloat(position.liquidationPx);
const isLong = parseFloat(position.szi) > 0;
const distance = isLong
? ((currentPrice - liquidationPrice) / currentPrice) * 100
: ((liquidationPrice - currentPrice) / currentPrice) * 100;
return {
coin: position.coin,
side: isLong ? 'LONG' : 'SHORT',
currentPrice: currentPrice,
liquidationPrice: liquidationPrice,
distancePercent: distance.toFixed(2),
risk: distance < 10 ? 'HIGH' : distance < 25 ? 'MEDIUM' : 'LOW'
};
});
}
```
### 3. Calculate Portfolio Metrics
Compute portfolio-wide metrics:
```javascript
async function getPortfolioMetrics(userAddress) {
const state = await getClearinghouseState(userAddress);
const totalPnl = state.assetPositions.reduce((sum, pos) => {
return sum + parseFloat(pos.position.unrealizedPnl);
}, 0);
const totalPositionValue = state.assetPositions.reduce((sum, pos) => {
return sum + parseFloat(pos.position.positionValue);
}, 0);
const accountValue = parseFloat(state.marginSummary.accountValue);
const pnlPercent = (totalPnl / accountValue) * 100;
return {
accountValue: accountValue,
totalPnl: totalPnl,
pnlPercent: pnlPercent.toFixed(2),
positionCount: state.assetPositions.length,
totalPositionValue: totalPositionValue,
leverage: (totalPositionValue / accountValue).toFixed(2)
};
}
```
### 4. Position Summary Report
Generate a detailed position summary:
```javascript
async function getPositionSummary(userAddress) {
const state = await getClearinghouseState(userAddress);
console.log('\n=== Account Summary ===');
console.log(`Account Value: $${state.marginSummary.accountValue}`);
console.log(`Margin Used: $${state.marginSummary.totalMarginUsed}`);
console.log(`Withdrawable: $${state.marginSummary.withdrawable}`);
console.log('\n=== Open Positions ===');
state.assetPositions.forEach(pos => {
const p = pos.position;
const side = parseFloat(p.szi) > 0 ? 'LONG' : 'SHORT';
const size = Math.abs(parseFloat(p.szi));
console.log(`\n${p.coin} ${side}`);
console.log(` Size: ${size}`);
console.log(` Entry Price: $${p.entryPx}`);
console.log(` Position Value: $${p.positionValue}`);
console.log(` Unrealized PnL: $${p.unrealizedPnl}`);
console.log(` Liquidation Price: $${p.liquidationPx}`);
console.log(` Leverage: ${p.leverage.value}x (${p.leverage.type})`);
});
}
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `400 Bad Request` | Missing or invalid user address | Ensure valid Ethereum address format |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Missing required parameter: user",
"code": "MISSING_PARAMETER"
}
```
### Robust Error Handling
```javascript
async function safeGetClearinghouseState(userAddress, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getClearinghouseState(userAddress);
} catch (error) {
if (error.response?.status === 429) {
// Rate limit - exponential backoff
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (error.response?.status === 400) {
throw new Error('Invalid user address');
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Poll responsibly** — Don't poll more frequently than needed (every 5-10 seconds is usually sufficient)
2. **Handle empty positions** — Account may have no open positions
3. **Validate addresses** — Ensure user addresses are valid Ethereum addresses
4. **Monitor liquidation risk** — Set alerts when positions approach liquidation
5. **Cache when appropriate** — Cache data briefly to reduce API calls for dashboards
## Related Endpoints
- [**openOrders**](./open-orders) — Get user's open orders
- [**userFees**](./user-fees) — Get user fee rates and volume
- [**spotClearinghouseState**](./spot-clearinghouse-state) — Get spot trading account state
- [**meta**](./meta) — Get trading pair metadata for validation
---
*Access real-time Hyperliquid account state with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## delegations - HyperCore Info Endpoint
# delegations
Get detailed staking delegation information for a user, including validator assignments, amounts, and delegation history.
## When to Use This Endpoint
The `delegations` endpoint is essential for:
- **Staking Management** — View detailed delegation information
- **Validator Tracking** — Monitor which validators you're delegating to
- **Rewards Analysis** — Track delegation performance and returns
- **Portfolio Optimization** — Analyze and rebalance delegation strategy
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"delegations"` |
| `user` | `string` | Yes | User's Ethereum wallet address |
### Example Request
```json
{
"type": "delegations",
"user": "0x420a4ed7b6bb361da586868adec2f2bb9ab75e66"
}
```
## Response
### Success Response
```json
[
{
"validator": "0x420a4ed7b6bb361da586868adec2f2bb9ab75e66",
"amount": "12505.32462249",
"lockedUntilTimestamp": 1762449026533
}
]
```
### Response Fields
The response is an array of delegation objects. Each delegation contains:
| Field | Type | Description |
|-------|------|-------------|
| `validator` | `string` | Ethereum address of the validator |
| `amount` | `string` | Amount of tokens delegated |
| `lockedUntilTimestamp` | `integer` | Unix timestamp (milliseconds) when delegation unlocks |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "delegations",
"user": "0x420a4ed7b6bb361da586868adec2f2bb9ab75e66"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getDelegations(userAddress) {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'delegations',
user: userAddress
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const delegations = await getDelegations('0x420a4ed7b6bb361da586868adec2f2bb9ab75e66');
console.log(`Total delegations: ${delegations.length}`);
// Display delegation details
delegations.forEach(d => {
console.log(`Validator: ${d.validator}`);
console.log(`Amount: ${d.amount}`);
console.log(`Unlocks: ${new Date(d.lockedUntilTimestamp).toISOString()}`);
});
```
```python
from typing import Dict
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_delegations(user_address: str) -> Dict:
"""Get user delegation information"""
response = requests.post(
ENDPOINT,
json={
'type': 'delegations',
'user': user_address
},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
delegations = get_delegations('0x420a4ed7b6bb361da586868adec2f2bb9ab75e66')
print(f"Total delegations: {len(delegations['delegations'])}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type DelegationsRequest struct {
Type string `json:"type"`
User string `json:"user"`
}
type DelegationsResponse struct {
Delegations []interface{} `json:"delegations"`
}
func getDelegations(userAddress string) (*DelegationsResponse, error) {
reqBody, _ := json.Marshal(DelegationsRequest{
Type: "delegations",
User: userAddress,
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result DelegationsResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
delegations, err := getDelegations("0x420a4ed7b6bb361da586868adec2f2bb9ab75e66")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Total delegations: %d\n", len(delegations.Delegations))
}
```
## Common Use Cases
### 1. View Delegation Portfolio
Display all active delegations:
```javascript
async function viewDelegationPortfolio(userAddress) {
const data = await getDelegations(userAddress);
console.log('=== Delegation Portfolio ===\n');
console.log(`Total delegations: ${data.delegations.length}`);
if (data.delegations.length === 0) {
console.log('No active delegations');
} else {
console.log('Delegation details available');
}
}
// Usage
await viewDelegationPortfolio('0x420a4ed7b6bb361da586868adec2f2bb9ab75e66');
```
### 2. Monitor Delegation Status
Track delegation changes over time:
```javascript
async function monitorDelegationStatus(userAddress) {
const data = await getDelegations(userAddress);
return {
delegationCount: data.delegations.length,
hasActiveDelegations: data.delegations.length > 0,
timestamp: new Date().toISOString()
};
}
// Usage
const status = await monitorDelegationStatus('0x420a4ed7b6bb361da586868adec2f2bb9ab75e66');
console.log('Delegation status:', status);
```
### 3. Build Staking Dashboard
Create a comprehensive staking dashboard:
```javascript
async function getStakingDashboard(userAddress) {
try {
const data = await getDelegations(userAddress);
return {
status: 'success',
delegations: data.delegations,
totalDelegations: data.delegations.length,
isStaking: data.delegations.length > 0,
lastUpdated: new Date().toISOString()
};
} catch (error) {
return {
status: 'error',
error: error.message
};
}
}
// Usage
const dashboard = await getStakingDashboard('0x420a4ed7b6bb361da586868adec2f2bb9ab75e66');
console.log('Staking Dashboard:', dashboard);
```
### 4. Check Delegation Diversity
Analyze delegation distribution:
```javascript
async function analyzeDelegationDiversity(userAddress) {
const data = await getDelegations(userAddress);
const analysis = {
totalDelegations: data.delegations.length,
isDiversified: data.delegations.length > 1,
delegationStatus: data.delegations.length > 0 ? 'active' : 'none'
};
if (analysis.isDiversified) {
console.log('Portfolio is diversified across multiple validators');
} else if (analysis.totalDelegations === 1) {
console.log('Portfolio concentrated in single validator');
} else {
console.log('No active delegations');
}
return analysis;
}
```
### 5. Track Delegation History
Monitor delegation changes:
```javascript
class DelegationTracker {
constructor(userAddress) {
this.userAddress = userAddress;
this.history = [];
}
async recordSnapshot() {
const data = await getDelegations(this.userAddress);
const snapshot = {
timestamp: Date.now(),
delegationCount: data.delegations.length,
delegations: data.delegations
};
this.history.push(snapshot);
return snapshot;
}
getHistory() {
return this.history;
}
detectChanges() {
if (this.history.length < 2) return null;
const latest = this.history[this.history.length - 1];
const previous = this.history[this.history.length - 2];
return {
countChange: latest.delegationCount - previous.delegationCount,
timestamp: latest.timestamp
};
}
}
// Usage
const tracker = new DelegationTracker('0x420a4ed7b6bb361da586868adec2f2bb9ab75e66');
await tracker.recordSnapshot();
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `400 Bad Request` | Missing or invalid user address | Ensure valid Ethereum address format |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Missing required parameter: user",
"code": "MISSING_PARAMETER"
}
```
### Robust Error Handling
```javascript
async function safeGetDelegations(userAddress, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getDelegations(userAddress);
} catch (error) {
if (error.response?.status === 429) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (error.response?.status === 400) {
throw new Error('Invalid user address');
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Validate addresses** — Ensure user addresses are valid Ethereum addresses
2. **Cache strategically** — Cache delegation data for several minutes
3. **Handle empty states** — Account for users with no delegations
4. **Monitor regularly** — Track changes for portfolio management
5. **Compare snapshots** — Store historical data to detect changes
## Related Endpoints
- [**delegatorSummary**](./delegator-summary) — Get delegation summary
- [**validatorL1Votes**](./validator-l1-votes) — Get validator voting information
- [**clearinghouseState**](./clearinghouse-state) — Get account state
- [**userFees**](./user-fees) — Get user fee information
---
*Access real-time Hyperliquid delegation data with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## delegatorSummary - HyperCore Info Endpoint
# delegatorSummary
Get comprehensive delegation summary for a delegator, including staking positions, rewards, and validator relationships.
## When to Use This Endpoint
The `delegatorSummary` endpoint is essential for:
- **Staking Portfolio** — View all delegations for a delegator
- **Rewards Tracking** — Monitor staking rewards across validators
- **Delegation Analysis** — Analyze delegation strategy and distribution
- **Validator Selection** — Evaluate current validator relationships
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"delegatorSummary"` |
| `user` | `string` | Yes | User's Ethereum wallet address |
### Example Request
```json
{
"type": "delegatorSummary",
"user": "0x420a4ed7b6bb361da586868adec2f2bb9ab75e66"
}
```
## Response
### Success Response
```json
{
"delegated": "12505.32462249",
"undelegated": "10689.31366593",
"totalPendingWithdrawal": "0.0",
"nPendingWithdrawals": 0
}
```
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `delegated` | `string` | Total amount of tokens currently delegated |
| `undelegated` | `string` | Total amount of tokens not delegated |
| `totalPendingWithdrawal` | `string` | Total amount pending withdrawal |
| `nPendingWithdrawals` | `integer` | Number of pending withdrawal requests |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "delegatorSummary",
"user": "0x420a4ed7b6bb361da586868adec2f2bb9ab75e66"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getDelegatorSummary(userAddress) {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'delegatorSummary',
user: userAddress
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const summary = await getDelegatorSummary('0x420a4ed7b6bb361da586868adec2f2bb9ab75e66');
console.log(`Delegated: ${summary.delegated}`);
console.log(`Undelegated: ${summary.undelegated}`);
console.log(`Pending withdrawals: ${summary.nPendingWithdrawals}`);
```
```python
from typing import Dict
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_delegator_summary(user_address: str) -> Dict:
"""Get delegator summary information"""
response = requests.post(
ENDPOINT,
json={
'type': 'delegatorSummary',
'user': user_address
},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
summary = get_delegator_summary('0x420a4ed7b6bb361da586868adec2f2bb9ab75e66')
print(f"Total delegations: {len(summary['delegations'])}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type DelegatorSummaryRequest struct {
Type string `json:"type"`
User string `json:"user"`
}
type DelegatorSummaryResponse struct {
Delegations []interface{} `json:"delegations"`
}
func getDelegatorSummary(userAddress string) (*DelegatorSummaryResponse, error) {
reqBody, _ := json.Marshal(DelegatorSummaryRequest{
Type: "delegatorSummary",
User: userAddress,
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result DelegatorSummaryResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
summary, err := getDelegatorSummary("0x420a4ed7b6bb361da586868adec2f2bb9ab75e66")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Total delegations: %d\n", len(summary.Delegations))
}
```
## Common Use Cases
### 1. View Staking Portfolio
Display all delegations for a user:
```javascript
async function viewStakingPortfolio(userAddress) {
const summary = await getDelegatorSummary(userAddress);
console.log('=== Staking Portfolio ===\n');
console.log(`Total delegations: ${summary.delegations.length}`);
if (summary.delegations.length === 0) {
console.log('No active delegations');
}
}
// Usage
await viewStakingPortfolio('0x420a4ed7b6bb361da586868adec2f2bb9ab75e66');
```
### 2. Track Delegation Changes
Monitor changes in delegation status:
```javascript
async function trackDelegations(userAddress) {
const summary = await getDelegatorSummary(userAddress);
return {
delegationCount: summary.delegations.length,
hasActiveDelegations: summary.delegations.length > 0,
timestamp: new Date().toISOString()
};
}
// Usage
const status = await trackDelegations('0x420a4ed7b6bb361da586868adec2f2bb9ab75e66');
console.log('Delegation status:', status);
```
### 3. Build Staking Dashboard
Create a comprehensive staking dashboard:
```javascript
async function getStakingDashboard(userAddress) {
try {
const summary = await getDelegatorSummary(userAddress);
return {
status: 'success',
delegations: summary.delegations,
totalDelegations: summary.delegations.length,
lastUpdated: new Date().toISOString()
};
} catch (error) {
return {
status: 'error',
error: error.message
};
}
}
```
### 4. Compare Delegation Strategies
Analyze delegation distribution:
```javascript
async function analyzeDelegationStrategy(userAddress) {
const summary = await getDelegatorSummary(userAddress);
const analysis = {
totalDelegations: summary.delegations.length,
isDiversified: summary.delegations.length > 1,
delegationStatus: summary.delegations.length > 0 ? 'active' : 'inactive'
};
console.log('Delegation Analysis:', analysis);
return analysis;
}
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `400 Bad Request` | Missing or invalid user address | Ensure valid Ethereum address format |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Missing required parameter: user",
"code": "MISSING_PARAMETER"
}
```
### Robust Error Handling
```javascript
async function safeGetDelegatorSummary(userAddress, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getDelegatorSummary(userAddress);
} catch (error) {
if (error.response?.status === 429) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (error.response?.status === 400) {
throw new Error('Invalid user address');
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Validate addresses** — Ensure user addresses are valid Ethereum addresses
2. **Cache data** — Cache delegation data for several minutes to reduce API calls
3. **Handle empty states** — Account for users with no delegations
4. **Monitor regularly** — Track delegation changes for portfolio management
5. **Implement pagination** — For users with many delegations, display in batches
## Related Endpoints
- [**delegations**](./delegations) — Get detailed staking delegation information
- [**validatorL1Votes**](./validator-l1-votes) — Get validator voting information
- [**clearinghouseState**](./clearinghouse-state) — Get account trading state
- [**userFees**](./user-fees) — Get user fee information
---
*Access real-time Hyperliquid delegation data with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## exchangeStatus - HyperCore Info Endpoint
# exchangeStatus
Get current Hyperliquid exchange status and timestamp for health monitoring and data freshness verification.
## When to Use This Endpoint
The `exchangeStatus` endpoint is essential for:
- **Health Monitoring** — Verify exchange is operational
- **Data Freshness** — Check timestamp for data staleness
- **Maintenance Detection** — Monitor for special statuses
- **Uptime Tracking** — Build status dashboards
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"exchangeStatus"` |
### Example Request
```json
{
"type": "exchangeStatus"
}
```
## Response
### Success Response
```json
{
"time": 1704067200000,
"specialStatuses": []
}
```
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `time` | `integer` | Unix timestamp in milliseconds |
| `specialStatuses` | `array` | Array of special status strings (empty during normal operation) |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{"type":"exchangeStatus"}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getExchangeStatus() {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ type: 'exchangeStatus' })
});
return await response.json();
}
// Usage
const status = await getExchangeStatus();
const date = new Date(status.time);
console.log(`Exchange time: ${date.toISOString()}`);
console.log(`Special statuses: ${status.specialStatuses.length === 0 ? 'None' : status.specialStatuses.join(', ')}`);
```
```python
from datetime import datetime
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_exchange_status():
response = requests.post(
ENDPOINT,
json={'type': 'exchangeStatus'},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
status = get_exchange_status()
exchange_time = datetime.fromtimestamp(status['time'] / 1000)
print(f"Exchange time: {exchange_time.isoformat()}")
print(f"Special statuses: {status['specialStatuses'] or 'None'}")
```
## Common Use Cases
### 1. Check Data Freshness
```javascript
async function checkDataFreshness(maxAgeSeconds = 60) {
const status = await getExchangeStatus();
const now = Date.now();
const age = (now - status.time) / 1000; // Convert to seconds
if (age > maxAgeSeconds) {
console.warn(`Warning: Exchange data is ${age.toFixed(1)}s old`);
return false;
}
return true;
}
// Usage
const isFresh = await checkDataFreshness(30);
if (!isFresh) {
console.log('Consider retrying or alerting');
}
```
### 2. Build Health Check Monitor
```javascript
class ExchangeHealthMonitor {
constructor(checkIntervalMs = 30000) {
this.checkIntervalMs = checkIntervalMs;
this.isHealthy = true;
this.lastCheck = null;
}
async start() {
while (true) {
try {
const status = await getExchangeStatus();
this.lastCheck = Date.now();
const age = (Date.now() - status.time) / 1000;
this.isHealthy = age < 60 && status.specialStatuses.length === 0;
if (!this.isHealthy) {
console.error('Exchange unhealthy:', {
dataAge: age,
specialStatuses: status.specialStatuses
});
}
} catch (error) {
console.error('Health check failed:', error);
this.isHealthy = false;
}
await new Promise(r => setTimeout(r, this.checkIntervalMs));
}
}
getStatus() {
return {
isHealthy: this.isHealthy,
lastCheck: this.lastCheck
};
}
}
// Usage
const monitor = new ExchangeHealthMonitor();
monitor.start();
```
### 3. Status Dashboard Endpoint
```javascript
async function getDashboardStatus() {
const status = await getExchangeStatus();
const now = Date.now();
const latency = now - status.time;
return {
status: status.specialStatuses.length === 0 ? 'operational' : 'maintenance',
latency: `${latency}ms`,
specialStatuses: status.specialStatuses,
lastUpdate: new Date(status.time).toISOString()
};
}
```
### 4. Alert on Special Statuses
```javascript
async function checkForAlerts() {
const status = await getExchangeStatus();
if (status.specialStatuses.length > 0) {
// Send alert
console.error('ALERT: Special statuses detected:', status.specialStatuses);
await sendAlert({
title: 'Hyperliquid Special Status',
message: `Statuses: ${status.specialStatuses.join(', ')}`,
timestamp: status.time
});
}
}
```
## Best Practices
1. **Poll regularly** (every 30-60 seconds) for monitoring dashboards
2. **Check freshness** before processing critical data
3. **Alert on special statuses** to catch maintenance periods
4. **Monitor latency** between your server time and exchange time
5. **Implement circuit breakers** when exchange is unhealthy
## Performance Tips
### Lightweight Health Check
```javascript
// Minimal health check for high-frequency monitoring
async function quickHealthCheck() {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);
const status = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ type: 'exchangeStatus' }),
signal: controller.signal
});
clearTimeout(timeout);
return status.ok;
} catch {
return false;
}
}
```
## Error Handling
```javascript
async function safeGetExchangeStatus(maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getExchangeStatus();
} catch (error) {
if (i === maxRetries - 1) {
throw new Error('Exchange status unavailable after retries');
}
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
}
}
}
```
## Related Endpoints
- [**meta**](./meta) — Get trading pair metadata
- [**spotMeta**](./spot-meta) — Get spot trading metadata
---
*Monitor Hyperliquid exchange health with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## extraAgents - HyperCore Info Endpoint
# extraAgents
Get information about extra agents configured for a user, including trading agents, permissions, and delegated access settings.
## When to Use This Endpoint
The `extraAgents` endpoint is essential for:
- **Agent Management** — View all agents with access to the account
- **Permission Tracking** — Monitor agent permissions and access levels
- **Security Auditing** — Verify authorized agents and delegated access
- **Access Control** — Manage who can trade on behalf of the account
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"extraAgents"` |
| `user` | `string` | Yes | User's Ethereum wallet address |
### Example Request
```json
{
"type": "extraAgents",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}
```
## Response
### Success Response
```json
[
{
"name": "pampit",
"address": "0xd0621288b7f42151d326442a950bb829703a343a",
"validUntil": 1785838333108
},
{
"name": "pampit2",
"address": "0x846d88dafbccd9524d674c1a6ac5d470273ff041",
"validUntil": 1778073895185
}
]
```
### Response Fields
The response is an array of agent objects. Each agent contains:
| Field | Type | Description |
|-------|------|-------------|
| `name` | `string` | Agent name/identifier |
| `address` | `string` | Ethereum address of the agent |
| `validUntil` | `integer` | Unix timestamp (milliseconds) when agent access expires |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "extraAgents",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getExtraAgents(userAddress) {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'extraAgents',
user: userAddress
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const agents = await getExtraAgents('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log(`Total agents: ${agents.agents.length}`);
```
```python
from typing import Dict
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_extra_agents(user_address: str) -> Dict:
"""Get extra agent information"""
response = requests.post(
ENDPOINT,
json={
'type': 'extraAgents',
'user': user_address
},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
agents = get_extra_agents('0x63E8c7C149556D5f34F833419A287bb9Ef81487f')
print(f"Total agents: {len(agents['agents'])}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type ExtraAgentsRequest struct {
Type string `json:"type"`
User string `json:"user"`
}
type ExtraAgentsResponse struct {
Agents []interface{} `json:"agents"`
}
func getExtraAgents(userAddress string) (*ExtraAgentsResponse, error) {
reqBody, _ := json.Marshal(ExtraAgentsRequest{
Type: "extraAgents",
User: userAddress,
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result ExtraAgentsResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
agents, err := getExtraAgents("0x63E8c7C149556D5f34F833419A287bb9Ef81487f")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Total agents: %d\n", len(agents.Agents))
}
```
## Common Use Cases
### 1. List All Agents
Display all agents with access to the account:
```javascript
async function listAgents(userAddress) {
const data = await getExtraAgents(userAddress);
console.log('=== Account Agents ===\n');
console.log(`Total agents: ${data.agents.length}`);
if (data.agents.length === 0) {
console.log('No extra agents configured');
} else {
console.log('Agents have access to this account');
}
}
// Usage
await listAgents('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
```
### 2. Security Audit
Audit agent access for security:
```javascript
async function auditAgentAccess(userAddress) {
const data = await getExtraAgents(userAddress);
const audit = {
timestamp: new Date().toISOString(),
agentCount: data.agents.length,
hasAgents: data.agents.length > 0,
securityStatus: data.agents.length === 0 ? 'no-agents' : 'agents-configured'
};
console.log('=== Security Audit ===\n');
console.log(`Agent count: ${audit.agentCount}`);
console.log(`Status: ${audit.securityStatus}`);
return audit;
}
// Usage
const audit = await auditAgentAccess('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
```
### 3. Monitor Agent Changes
Track changes in agent configuration:
```javascript
class AgentMonitor {
constructor(userAddress) {
this.userAddress = userAddress;
this.lastKnownCount = null;
}
async checkForChanges() {
const data = await getExtraAgents(this.userAddress);
const currentCount = data.agents.length;
if (this.lastKnownCount !== null) {
const change = currentCount - this.lastKnownCount;
if (change > 0) {
console.log(`⚠️ ${change} new agent(s) added`);
} else if (change < 0) {
console.log(`✓ ${Math.abs(change)} agent(s) removed`);
}
}
this.lastKnownCount = currentCount;
return {
currentCount: currentCount,
changed: this.lastKnownCount !== null && currentCount !== this.lastKnownCount
};
}
}
// Usage
const monitor = new AgentMonitor('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
setInterval(() => monitor.checkForChanges(), 60000); // Check every minute
```
### 4. Build Agent Dashboard
Create agent management dashboard:
```javascript
async function getAgentDashboard(userAddress) {
try {
const data = await getExtraAgents(userAddress);
return {
status: 'success',
agents: data.agents,
totalAgents: data.agents.length,
hasAgents: data.agents.length > 0,
lastUpdated: new Date().toISOString()
};
} catch (error) {
return {
status: 'error',
error: error.message,
agents: []
};
}
}
// Usage
const dashboard = await getAgentDashboard('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log('Agent Dashboard:', dashboard);
```
### 5. Verify Agent Authorization
Check if agents are properly authorized:
```javascript
async function verifyAgentAuthorization(userAddress) {
const data = await getExtraAgents(userAddress);
const verification = {
isConfigured: data.agents.length > 0,
agentCount: data.agents.length,
status: data.agents.length > 0 ? 'agents-active' : 'no-agents',
recommendation: data.agents.length > 0
? 'Review agent permissions regularly'
: 'No agents configured'
};
console.log('Agent Authorization:', verification);
return verification;
}
// Usage
const verification = await verifyAgentAuthorization('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `400 Bad Request` | Missing or invalid user address | Ensure valid Ethereum address format |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Missing required parameter: user",
"code": "MISSING_PARAMETER"
}
```
### Robust Error Handling
```javascript
async function safeGetExtraAgents(userAddress, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getExtraAgents(userAddress);
} catch (error) {
if (error.response?.status === 429) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (error.response?.status === 400) {
throw new Error('Invalid user address');
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Validate addresses** — Ensure user addresses are valid Ethereum addresses
2. **Cache data** — Cache agent data for several minutes
3. **Monitor changes** — Track agent additions/removals for security
4. **Regular audits** — Periodically review agent access for security
5. **Handle empty states** — Account for users without extra agents
## Security Considerations
### Regular Security Checks
```javascript
class SecurityChecker {
constructor(userAddress, checkIntervalMs = 300000) {
this.userAddress = userAddress;
this.checkIntervalMs = checkIntervalMs; // 5 minutes
}
async performSecurityCheck() {
const data = await getExtraAgents(this.userAddress);
const securityReport = {
timestamp: new Date().toISOString(),
agentCount: data.agents.length,
status: data.agents.length === 0 ? 'secure-no-agents' : 'review-required'
};
if (data.agents.length > 0) {
console.log(`⚠️ Security Review: ${data.agents.length} agent(s) have access`);
} else {
console.log('✓ Security Check: No extra agents');
}
return securityReport;
}
async startMonitoring() {
// Initial check
await this.performSecurityCheck();
// Periodic checks
setInterval(() => this.performSecurityCheck(), this.checkIntervalMs);
}
}
```
## Related Endpoints
- [**subAccounts**](./sub-accounts) — Get sub-account information
- [**userRole**](./user-role) — Get user role information
- [**clearinghouseState**](./clearinghouse-state) — Get account state
- [**openOrders**](./open-orders) — Get orders placed by agents
---
*Manage agent access and permissions with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## frontendOpenOrders - HyperCore Info Endpoint
# frontendOpenOrders
Get open orders formatted specifically for frontend display, with optimized data structure for UI rendering.
## When to Use This Endpoint
The `frontendOpenOrders` endpoint is essential for:
- **UI Development** — Build trading interfaces with pre-formatted order data
- **Order Display** — Show orders in user-friendly format
- **Real-time Updates** — Refresh order books in trading applications
- **Frontend Optimization** — Use data already structured for display
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"frontendOpenOrders"` |
| `user` | `string` | Yes | User's Ethereum wallet address |
### Example Request
```json
{
"type": "frontendOpenOrders",
"user": "0x31ca8395cf837de08b24da3f660e77761dfb974b"
}
```
## Response
### Success Response
Returns open orders formatted for frontend display.
```json
{
"orders": []
}
```
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `orders` | `array` | Array of order objects optimized for frontend display |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "frontendOpenOrders",
"user": "0x31ca8395cf837de08b24da3f660e77761dfb974b"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getFrontendOpenOrders(userAddress) {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'frontendOpenOrders',
user: userAddress
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const orders = await getFrontendOpenOrders('0x31ca8395cf837de08b24da3f660e77761dfb974b');
console.log(`Open orders: ${orders.orders.length}`);
```
```python
from typing import Dict
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_frontend_open_orders(user_address: str) -> Dict:
"""Get frontend-formatted open orders"""
response = requests.post(
ENDPOINT,
json={
'type': 'frontendOpenOrders',
'user': user_address
},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
orders = get_frontend_open_orders('0x31ca8395cf837de08b24da3f660e77761dfb974b')
print(f"Open orders: {len(orders['orders'])}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type FrontendOpenOrdersRequest struct {
Type string `json:"type"`
User string `json:"user"`
}
type FrontendOpenOrdersResponse struct {
Orders []interface{} `json:"orders"`
}
func getFrontendOpenOrders(userAddress string) (*FrontendOpenOrdersResponse, error) {
reqBody, _ := json.Marshal(FrontendOpenOrdersRequest{
Type: "frontendOpenOrders",
User: userAddress,
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result FrontendOpenOrdersResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
orders, err := getFrontendOpenOrders("0x31ca8395cf837de08b24da3f660e77761dfb974b")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Open orders: %d\n", len(orders.Orders))
}
```
## Common Use Cases
### 1. Display Open Orders in UI
Render orders in a trading interface:
```javascript
async function displayOpenOrders(userAddress) {
const data = await getFrontendOpenOrders(userAddress);
console.log('=== Open Orders ===\n');
if (data.orders.length === 0) {
console.log('No open orders');
} else {
console.log(`${data.orders.length} open order(s)`);
// Render orders in UI
}
}
// Usage
await displayOpenOrders('0x31ca8395cf837de08b24da3f660e77761dfb974b');
```
### 2. Real-time Order Updates
Poll for order updates:
```javascript
class OrderUpdateManager {
constructor(userAddress, updateIntervalMs = 5000) {
this.userAddress = userAddress;
this.updateIntervalMs = updateIntervalMs;
this.onUpdate = null;
}
async start(callback) {
this.onUpdate = callback;
while (true) {
try {
const orders = await getFrontendOpenOrders(this.userAddress);
if (this.onUpdate) {
this.onUpdate(orders);
}
} catch (error) {
console.error('Failed to fetch orders:', error);
}
await new Promise(r => setTimeout(r, this.updateIntervalMs));
}
}
}
// Usage
const manager = new OrderUpdateManager('0x31ca8395cf837de08b24da3f660e77761dfb974b');
manager.start((orders) => {
console.log(`Updated: ${orders.orders.length} orders`);
// Update UI
});
```
### 3. Build Order Management Panel
Create order management interface:
```javascript
async function getOrderPanel(userAddress) {
try {
const data = await getFrontendOpenOrders(userAddress);
return {
status: 'success',
orders: data.orders,
totalOrders: data.orders.length,
hasOrders: data.orders.length > 0,
lastUpdated: new Date().toISOString()
};
} catch (error) {
return {
status: 'error',
error: error.message,
orders: []
};
}
}
// Usage
const panel = await getOrderPanel('0x31ca8395cf837de08b24da3f660e77761dfb974b');
console.log('Order Panel:', panel);
```
### 4. Monitor Order Count
Track changes in order count:
```javascript
async function monitorOrderCount(userAddress) {
let previousCount = null;
const check = async () => {
const data = await getFrontendOpenOrders(userAddress);
const currentCount = data.orders.length;
if (previousCount !== null && currentCount !== previousCount) {
const change = currentCount - previousCount;
console.log(`Order count changed: ${change > 0 ? '+' : ''}${change}`);
}
previousCount = currentCount;
return currentCount;
};
return check;
}
// Usage
const checkOrders = await monitorOrderCount('0x31ca8395cf837de08b24da3f660e77761dfb974b');
setInterval(checkOrders, 10000); // Check every 10 seconds
```
### 5. Order Status Dashboard
Create comprehensive order status view:
```javascript
async function getOrderStatusDashboard(userAddress) {
const data = await getFrontendOpenOrders(userAddress);
return {
totalOrders: data.orders.length,
status: data.orders.length > 0 ? 'active' : 'no-orders',
timestamp: new Date().toISOString(),
orders: data.orders
};
}
// Usage
const dashboard = await getOrderStatusDashboard('0x31ca8395cf837de08b24da3f660e77761dfb974b');
console.log('Order Dashboard:', dashboard);
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `400 Bad Request` | Missing or invalid user address | Ensure valid Ethereum address format |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Missing required parameter: user",
"code": "MISSING_PARAMETER"
}
```
### Robust Error Handling
```javascript
async function safeGetFrontendOpenOrders(userAddress, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getFrontendOpenOrders(userAddress);
} catch (error) {
if (error.response?.status === 429) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (error.response?.status === 400) {
throw new Error('Invalid user address');
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Poll efficiently** — Update every 3-10 seconds for active trading UIs
2. **Handle empty states** — Display appropriate message when no orders exist
3. **Optimize rendering** — Only re-render when order data changes
4. **Validate addresses** — Ensure user addresses are valid before requests
5. **Implement caching** — Cache briefly (1-5 seconds) to reduce redundant calls
## Performance Tips
### Efficient Polling Strategy
```javascript
class SmartOrderPoller {
constructor(userAddress, baseInterval = 5000) {
this.userAddress = userAddress;
this.baseInterval = baseInterval;
this.lastData = null;
}
async poll() {
const data = await getFrontendOpenOrders(this.userAddress);
// Only notify if data changed
const hasChanged = JSON.stringify(data) !== JSON.stringify(this.lastData);
this.lastData = data;
return {
data: data,
changed: hasChanged
};
}
}
```
## Related Endpoints
- [**openOrders**](./open-orders) — Get standard open orders format
- [**clearinghouseState**](./clearinghouse-state) — Get account state
- [**userFees**](./user-fees) — Get fee information for orders
- [**meta**](./meta) — Get trading pair metadata
---
*Build powerful trading interfaces with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## HyperCore Info Endpoint
Dwellir's HyperCore Info Endpoint provides comprehensive access to Hyperliquid exchange data through a simple HTTP JSON API. Query market metadata, user account information, vault data, and exchange status with a single POST request.
> **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).
## Key Benefits
### Higher Rate Limits
Unlike public Hyperliquid endpoints, Dwellir's HyperCore Info Endpoint provides significantly higher rate limits based on your subscription plan. This enables you to build production-grade applications without worrying about hitting rate limit restrictions.
**Rate limits scale with your plan:**
- Free tier: Standard public limits
- Growth tier: 10x higher limits
- Enterprise tier: Custom rate limits tailored to your needs
### Single Endpoint Architecture
All info endpoints are accessible through a single URL with different request types. This simplifies integration and reduces connection overhead.
**Base URL:** `https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info`
### Custom REST API Development
We're actively developing additional REST API endpoints for Hyperliquid. If you need custom endpoints or specialized data access patterns not covered by the standard Info Endpoint, [contact our team](https://dashboard.dwellir.com) to discuss your requirements.
## Available Endpoint Categories
### Market Metadata
Access trading pair information, leverage limits, and exchange status.
| Endpoint | Purpose |
|----------|---------|
| [**meta**](./meta) | Get trading pair metadata including leverage limits |
| [**spotMeta**](./spot-meta) | Get spot trading asset metadata |
| [**exchangeStatus**](./exchange-status) | Monitor exchange health and status |
| [**perpDexs**](./perp-dexs) | Get all deployed perpetual DEXs with assets and configuration |
### User Accounts
Query account states, positions, orders, and fee information.
| Endpoint | Purpose |
|----------|---------|
| [**clearinghouseState**](./clearinghouse-state) | Get perpetual trading account state |
| [**batchClearinghouseStates**](./batch-clearinghouse-states) | Batch query account states for multiple users |
| [**openOrders**](./open-orders) | Retrieve all open orders for a user |
| [**spotClearinghouseState**](./spot-clearinghouse-state) | Get spot trading account balances |
| [**userFees**](./user-fees) | Get user fee rates and volume data |
| [**userAbstraction**](./user-abstraction) | Get account abstraction mode (unified, portfolio margin, etc.) |
| [**activeAssetData**](./active-asset-data) | Get leverage, max trade sizes, and available capital for a user and coin |
### Vaults
Access vault performance data and user positions.
| Endpoint | Purpose |
|----------|---------|
| [**leadingVaults**](./leading-vaults) | Get top performing vaults |
| [**vaultSummaries**](./vault-summaries) | Get summary data for all vaults |
| [**userVaultEquities**](./user-vault-equities) | Get user's vault positions |
### Validators
Query validator and delegation information.
| Endpoint | Purpose |
|----------|---------|
| [**validatorL1Votes**](./validator-l1-votes) | Get validator voting data |
| [**delegatorSummary**](./delegator-summary) | Get delegation summary for a user |
### Advanced Endpoints
Specialized endpoints for advanced use cases.
| Endpoint | Purpose |
|----------|---------|
| [**userRateLimit**](./user-rate-limit) | Get rate limit information |
| [**delegations**](./delegations) | Get staking delegation data |
| [**subAccounts**](./sub-accounts) | Get sub-account information |
| [**frontendOpenOrders**](./frontend-open-orders) | Get orders formatted for UI display |
| [**liquidatable**](./liquidatable) | Check liquidation status |
| [**webData2**](./web-data-2) | Get comprehensive web interface data |
| [**extraAgents**](./extra-agents) | Get extra agent information |
| [**userRole**](./user-role) | Get user role information |
| [**maxBuilderFee**](./max-builder-fee) | Get maximum builder fee |
| [**maxMarketOrderNtls**](./max-market-order-ntls) | Get maximum market order notionals |
## Quick Start
### Authentication
All requests require an API key included in the URL path:
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{"type":"meta"}'
```
### Request Format
All endpoints follow the same pattern:
```json
{
"type": "ENDPOINT_TYPE",
"param1": "value1",
"param2": "value2"
}
```
### Example: Get Exchange Metadata
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{"type":"meta"}'
```
### Example: Get User Account State
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "clearinghouseState",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}'
```
## Error Handling
### HTTP Status Codes
| Code | Description | Solution |
|------|-------------|----------|
| `200` | Success | Request completed successfully |
| `400` | Bad Request | Check request format and parameters |
| `401` | Unauthorized | Verify API key is correct |
| `422` | Unprocessable Entity | Check parameter values |
| `429` | Rate Limit | Implement backoff or upgrade plan |
| `500` | Server Error | Retry with exponential backoff |
### Error Response Format
```json
{
"error": "Error message description",
"code": "ERROR_CODE"
}
```
## Best Practices
### 1. Implement Proper Error Handling
Always include retry logic with exponential backoff:
```javascript
async function queryEndpoint(payload, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch(
'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload)
}
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (error) {
if (i === maxRetries - 1) throw error;
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
}
}
}
```
### 2. Cache Appropriately
Cache metadata endpoints to reduce API calls:
```javascript
// Cache meta data for 1 hour
const metaCache = new Map();
const META_TTL = 3600000; // 1 hour in ms
async function getMeta() {
const cached = metaCache.get('meta');
if (cached && Date.now() - cached.timestamp < META_TTL) {
return cached.data;
}
const data = await queryEndpoint({ type: 'meta' });
metaCache.set('meta', { data, timestamp: Date.now() });
return data;
}
```
### 3. Monitor Rate Limits
Check response headers to track rate limit usage:
```javascript
const response = await fetch(url, options);
const remaining = response.headers.get('X-RateLimit-Remaining');
const reset = response.headers.get('X-RateLimit-Reset');
if (parseInt(remaining) < 10) {
console.warn('Approaching rate limit');
}
```
### 4. Use Timeouts
Set reasonable timeouts for all requests:
```javascript
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 10000); // 10s timeout
try {
const response = await fetch(url, {
...options,
signal: controller.signal
});
return await response.json();
} finally {
clearTimeout(timeout);
}
```
## Code Examples
### Python
```python
from typing import Dict, Any
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def query_info_endpoint(endpoint_type: str, params: Dict[str, Any] = None) -> Dict:
"""Query the HyperCore Info Endpoint"""
payload = {"type": endpoint_type}
if params:
payload.update(params)
headers = {
'Content-Type': 'application/json',
}
response = requests.post(ENDPOINT, json=payload, headers=headers, timeout=10)
response.raise_for_status()
return response.json()
# Get metadata
meta = query_info_endpoint('meta')
print(f"Available pairs: {len(meta['universe'])}")
# Get user account state
user_state = query_info_endpoint(
'clearinghouseState',
{'user': '0x63E8c7C149556D5f34F833419A287bb9Ef81487f'}
)
print(f"Account value: {user_state['marginSummary']['accountValue']}")
```
### JavaScript/TypeScript
```typescript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
interface InfoRequest {
type: string;
[key: string]: any;
}
async function queryInfoEndpoint(request: InfoRequest): Promise {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(request)
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Get metadata
const meta = await queryInfoEndpoint({ type: 'meta' });
console.log(`Available pairs: ${meta.universe.length}`);
// Get user state
const userState = await queryInfoEndpoint({
type: 'clearinghouseState',
user: '0x63E8c7C149556D5f34F833419A287bb9Ef81487f'
});
console.log(`Account value: ${userState.marginSummary.accountValue}`);
```
## Support
Need help with the HyperCore Info Endpoint?
- **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com)
- **Email**: support@dwellir.com
- **Documentation**: [docs.dwellir.com](https://docs.dwellir.com)
For custom endpoint development or enterprise solutions, [contact our team](https://dashboard.dwellir.com).
---
*Access comprehensive Hyperliquid exchange data with Dwellir's enterprise-grade infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## leadingVaults - HyperCore Info Endpoint
# leadingVaults
Get information about leading vaults on the platform, including performance metrics, total value locked (TVL), and annual percentage yield (APY).
> **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 Endpoint
The `leadingVaults` endpoint is essential for investors, vault aggregators, and analytics platforms who need to:
- **Discover Top Performers** — Find the best-performing vaults based on returns
- **Compare Vault Strategies** — Analyze different vault strategies and their performance
- **Track Vault Rankings** — Monitor vault leaderboard and relative performance
- **Build Vault Aggregators** — Create vault discovery and comparison tools
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"leadingVaults"` |
### Example Request
```json
{
"type": "leadingVaults"
}
```
## Response
### Success Response
```json
[
{
"vaultAddress": "0x1234567890abcdef1234567890abcdef12345678",
"name": "Alpha Strategy Vault",
"tvl": "5000000.00",
"apy": "45.2",
"monthlyReturn": "3.5",
"weeklyReturn": "0.8",
"sharpeRatio": "2.1",
"maxDrawdown": "12.5",
"performanceFee": "20",
"managementFee": "2"
},
{
"vaultAddress": "0xabcdef1234567890abcdef1234567890abcdef12",
"name": "Delta Neutral Vault",
"tvl": "3500000.00",
"apy": "28.7",
"monthlyReturn": "2.3",
"weeklyReturn": "0.5",
"sharpeRatio": "1.8",
"maxDrawdown": "8.2",
"performanceFee": "15",
"managementFee": "1.5"
}
]
```
### Response Fields
The response is an array of vault objects, each containing:
| Field | Type | Description |
|-------|------|-------------|
| `vaultAddress` | `string` | Ethereum address of the vault contract |
| `name` | `string` | Name of the vault |
| `tvl` | `string` | Total value locked in USD |
| `apy` | `string` | Annual percentage yield |
| `monthlyReturn` | `string` | Monthly return percentage |
| `weeklyReturn` | `string` | Weekly return percentage |
| `sharpeRatio` | `string` | Risk-adjusted return metric |
| `maxDrawdown` | `string` | Maximum drawdown percentage |
| `performanceFee` | `string` | Performance fee percentage |
| `managementFee` | `string` | Management fee percentage |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "leadingVaults"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getLeadingVaults() {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'leadingVaults'
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const vaults = await getLeadingVaults();
console.log(`Found ${vaults.length} leading vaults`);
// Sort by APY
const topByApy = [...vaults].sort((a, b) =>
parseFloat(b.apy) - parseFloat(a.apy)
);
console.log('\n=== Top 5 Vaults by APY ===');
topByApy.slice(0, 5).forEach((vault, index) => {
console.log(`${index + 1}. ${vault.name}`);
console.log(` APY: ${vault.apy}%`);
console.log(` TVL: $${parseFloat(vault.tvl).toLocaleString()}`);
console.log(` Sharpe Ratio: ${vault.sharpeRatio}`);
});
```
```python
from typing import List, Dict
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_leading_vaults() -> List[Dict]:
"""Get leading vaults on Hyperliquid"""
response = requests.post(
ENDPOINT,
json={'type': 'leadingVaults'},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
vaults = get_leading_vaults()
print(f"Found {len(vaults)} leading vaults\n")
# Sort by APY
vaults_by_apy = sorted(vaults, key=lambda v: float(v['apy']), reverse=True)
print("=== Top 5 Vaults by APY ===")
for i, vault in enumerate(vaults_by_apy[:5], 1):
print(f"\n{i}. {vault['name']}")
print(f" APY: {vault['apy']}%")
print(f" TVL: ${float(vault['tvl']):,.2f}")
print(f" Monthly Return: {vault['monthlyReturn']}%")
print(f" Sharpe Ratio: {vault['sharpeRatio']}")
print(f" Max Drawdown: {vault['maxDrawdown']}%")
# Calculate total TVL
total_tvl = sum(float(v['tvl']) for v in vaults)
print(f"\n=== Total TVL across leading vaults: ${total_tvl:,.2f} ===")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"sort"
"strconv"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type LeadingVaultsRequest struct {
Type string `json:"type"`
}
type Vault struct {
VaultAddress string `json:"vaultAddress"`
Name string `json:"name"`
TVL string `json:"tvl"`
APY string `json:"apy"`
MonthlyReturn string `json:"monthlyReturn"`
WeeklyReturn string `json:"weeklyReturn"`
SharpeRatio string `json:"sharpeRatio"`
MaxDrawdown string `json:"maxDrawdown"`
PerformanceFee string `json:"performanceFee"`
ManagementFee string `json:"managementFee"`
}
func getLeadingVaults() ([]Vault, error) {
reqBody, _ := json.Marshal(LeadingVaultsRequest{
Type: "leadingVaults",
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var vaults []Vault
if err := json.Unmarshal(body, &vaults); err != nil {
return nil, err
}
return vaults, nil
}
func main() {
vaults, err := getLeadingVaults()
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Found %d leading vaults\n\n", len(vaults))
// Sort by APY
sort.Slice(vaults, func(i, j int) bool {
apyI, _ := strconv.ParseFloat(vaults[i].APY, 64)
apyJ, _ := strconv.ParseFloat(vaults[j].APY, 64)
return apyI > apyJ
})
fmt.Println("=== Top 5 Vaults by APY ===")
for i, vault := range vaults {
if i >= 5 {
break
}
fmt.Printf("\n%d. %s\n", i+1, vault.Name)
fmt.Printf(" APY: %s%%\n", vault.APY)
fmt.Printf(" TVL: $%s\n", vault.TVL)
fmt.Printf(" Sharpe Ratio: %s\n", vault.SharpeRatio)
fmt.Printf(" Max Drawdown: %s%%\n", vault.MaxDrawdown)
}
}
```
## Common Use Cases
### 1. Find Best Performing Vaults
Identify vaults with the highest returns:
```javascript
async function findBestPerformers(minTvl = 1000000) {
const vaults = await getLeadingVaults();
// Filter by minimum TVL and sort by APY
const qualifiedVaults = vaults
.filter(v => parseFloat(v.tvl) >= minTvl)
.sort((a, b) => parseFloat(b.apy) - parseFloat(a.apy));
return qualifiedVaults.map(v => ({
name: v.name,
apy: parseFloat(v.apy),
tvl: parseFloat(v.tvl),
sharpeRatio: parseFloat(v.sharpeRatio),
riskAdjustedReturn: parseFloat(v.apy) / parseFloat(v.maxDrawdown)
}));
}
// Usage
const topVaults = await findBestPerformers(1000000);
console.log('Top performers with >$1M TVL:', topVaults.slice(0, 5));
```
### 2. Compare Vault Risk Profiles
Analyze risk-adjusted returns:
```javascript
async function analyzeVaultRisk() {
const vaults = await getLeadingVaults();
const riskAnalysis = vaults.map(v => {
const apy = parseFloat(v.apy);
const sharpe = parseFloat(v.sharpeRatio);
const maxDrawdown = parseFloat(v.maxDrawdown);
let riskLevel;
if (maxDrawdown < 10 && sharpe > 2) {
riskLevel = 'LOW';
} else if (maxDrawdown < 20 && sharpe > 1.5) {
riskLevel = 'MEDIUM';
} else {
riskLevel = 'HIGH';
}
return {
name: v.name,
apy: apy,
sharpe: sharpe,
maxDrawdown: maxDrawdown,
riskLevel: riskLevel,
score: (apy * sharpe) / maxDrawdown // Risk-adjusted score
};
});
// Sort by risk-adjusted score
return riskAnalysis.sort((a, b) => b.score - a.score);
}
// Usage
const analysis = await analyzeVaultRisk();
console.log('\n=== Risk-Adjusted Rankings ===');
analysis.forEach((v, i) => {
console.log(`${i + 1}. ${v.name} (${v.riskLevel} RISK)`);
console.log(` APY: ${v.apy}% | Sharpe: ${v.sharpe} | Max DD: ${v.maxDrawdown}%`);
});
```
### 3. Calculate Total Market Metrics
Compute aggregate vault statistics:
```javascript
async function getMarketMetrics() {
const vaults = await getLeadingVaults();
const metrics = {
totalVaults: vaults.length,
totalTVL: vaults.reduce((sum, v) => sum + parseFloat(v.tvl), 0),
avgAPY: vaults.reduce((sum, v) => sum + parseFloat(v.apy), 0) / vaults.length,
avgSharpe: vaults.reduce((sum, v) => sum + parseFloat(v.sharpeRatio), 0) / vaults.length,
avgDrawdown: vaults.reduce((sum, v) => sum + parseFloat(v.maxDrawdown), 0) / vaults.length,
highestAPY: Math.max(...vaults.map(v => parseFloat(v.apy))),
lowestDrawdown: Math.min(...vaults.map(v => parseFloat(v.maxDrawdown)))
};
return {
...metrics,
totalTVL: metrics.totalTVL.toFixed(2),
avgAPY: metrics.avgAPY.toFixed(2),
avgSharpe: metrics.avgSharpe.toFixed(2),
avgDrawdown: metrics.avgDrawdown.toFixed(2)
};
}
// Usage
const metrics = await getMarketMetrics();
console.log('Vault Market Metrics:');
console.log(`Total TVL: $${parseFloat(metrics.totalTVL).toLocaleString()}`);
console.log(`Average APY: ${metrics.avgAPY}%`);
console.log(`Average Sharpe Ratio: ${metrics.avgSharpe}`);
```
### 4. Filter Vaults by Strategy Type
Find vaults matching specific criteria:
```javascript
async function findVaultsByStrategy(criteria) {
const vaults = await getLeadingVaults();
return vaults.filter(v => {
const apy = parseFloat(v.apy);
const sharpe = parseFloat(v.sharpeRatio);
const drawdown = parseFloat(v.maxDrawdown);
const tvl = parseFloat(v.tvl);
// Conservative strategy
if (criteria === 'conservative') {
return drawdown < 10 && sharpe > 2 && tvl > 1000000;
}
// Aggressive strategy
if (criteria === 'aggressive') {
return apy > 40 && tvl > 500000;
}
// Balanced strategy
if (criteria === 'balanced') {
return apy > 25 && drawdown < 15 && sharpe > 1.5;
}
return false;
});
}
// Usage
const conservative = await findVaultsByStrategy('conservative');
console.log(`Found ${conservative.length} conservative vaults`);
const aggressive = await findVaultsByStrategy('aggressive');
console.log(`Found ${aggressive.length} aggressive vaults`);
```
### 5. Build Vault Leaderboard
Create a comprehensive vault ranking:
```javascript
async function buildLeaderboard() {
const vaults = await getLeadingVaults();
// Calculate composite score
const leaderboard = vaults.map(v => {
const apy = parseFloat(v.apy);
const sharpe = parseFloat(v.sharpeRatio);
const tvl = parseFloat(v.tvl);
const drawdown = parseFloat(v.maxDrawdown);
// Weighted scoring: APY (40%), Sharpe (30%), TVL (20%), Low Drawdown (10%)
const score = (
(apy / 100) * 0.4 +
(sharpe / 3) * 0.3 +
(Math.log10(tvl) / 10) * 0.2 +
((100 - drawdown) / 100) * 0.1
) * 100;
return {
rank: 0, // Will be assigned after sorting
name: v.name,
vaultAddress: v.vaultAddress,
score: score.toFixed(2),
apy: apy,
tvl: tvl,
sharpe: sharpe,
drawdown: drawdown
};
}).sort((a, b) => parseFloat(b.score) - parseFloat(a.score));
// Assign ranks
leaderboard.forEach((vault, index) => {
vault.rank = index + 1;
});
return leaderboard;
}
// Usage
const leaderboard = await buildLeaderboard();
console.log('\n=== Vault Leaderboard ===');
leaderboard.slice(0, 10).forEach(v => {
console.log(`\n#${v.rank} ${v.name}`);
console.log(`Score: ${v.score} | APY: ${v.apy}% | TVL: $${v.tvl.toLocaleString()}`);
});
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Rate limit exceeded",
"code": "RATE_LIMIT_EXCEEDED"
}
```
### Robust Error Handling
```javascript
async function safeGetLeadingVaults(maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getLeadingVaults();
} catch (error) {
if (error.response?.status === 429) {
// Rate limit - exponential backoff
const delay = Math.pow(2, i) * 1000;
await new Promise(r => setTimeout(r, delay));
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Cache appropriately** — Leading vaults data can be cached for 5-15 minutes
2. **Compare holistically** — Don't focus only on APY; consider risk metrics
3. **Monitor trends** — Track vault performance over time, not just snapshots
4. **Validate fees** — Account for performance and management fees in returns
5. **Check TVL** — Larger TVL often indicates more established vaults
## Related Endpoints
- [**vaultSummaries**](./vault-summaries) — Get summary information for all vaults
- [**userVaultEquities**](./user-vault-equities) — Get user's vault positions
- [**clearinghouseState**](./clearinghouse-state) — Get user's perpetual account state
---
*Access Hyperliquid's leading vaults data with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## liquidatable - HyperCore Info Endpoint
# liquidatable
Check if a user's positions are at risk of liquidation, providing critical risk management information.
## When to Use This Endpoint
The `liquidatable` endpoint is essential for:
- **Risk Monitoring** — Check liquidation risk for positions
- **Margin Management** — Monitor account health and safety
- **Liquidation Alerts** — Build alert systems for position risk
- **Portfolio Safety** — Ensure positions are within safe margins
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"liquidatable"` |
| `user` | `string` | Yes | User's Ethereum wallet address |
### Example Request
```json
{
"type": "liquidatable",
"user": "0x420a4ed7b6bb361da586868adec2f2bb9ab75e66"
}
```
## Response
### Success Response
Returns liquidation status for the user's positions.
```json
{
"liquidatable": false
}
```
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `liquidatable` | `boolean` | Whether the user's positions are currently liquidatable |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "liquidatable",
"user": "0x420a4ed7b6bb361da586868adec2f2bb9ab75e66"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function checkLiquidatable(userAddress) {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'liquidatable',
user: userAddress
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const status = await checkLiquidatable('0x420a4ed7b6bb361da586868adec2f2bb9ab75e66');
console.log(`Liquidatable: ${status.liquidatable ? 'YES - AT RISK' : 'No'}`);
```
```python
from typing import Dict
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def check_liquidatable(user_address: str) -> Dict:
"""Check if user positions are liquidatable"""
response = requests.post(
ENDPOINT,
json={
'type': 'liquidatable',
'user': user_address
},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
status = check_liquidatable('0x420a4ed7b6bb361da586868adec2f2bb9ab75e66')
print(f"Liquidatable: {'YES - AT RISK' if status['liquidatable'] else 'No'}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type LiquidatableRequest struct {
Type string `json:"type"`
User string `json:"user"`
}
type LiquidatableResponse struct {
Liquidatable bool `json:"liquidatable"`
}
func checkLiquidatable(userAddress string) (*LiquidatableResponse, error) {
reqBody, _ := json.Marshal(LiquidatableRequest{
Type: "liquidatable",
User: userAddress,
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result LiquidatableResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
status, err := checkLiquidatable("0x420a4ed7b6bb361da586868adec2f2bb9ab75e66")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
if status.Liquidatable {
fmt.Println("Liquidatable: YES - AT RISK")
} else {
fmt.Println("Liquidatable: No")
}
}
```
## Common Use Cases
### 1. Liquidation Risk Monitor
Monitor liquidation risk continuously:
```javascript
async function monitorLiquidationRisk(userAddress) {
const status = await checkLiquidatable(userAddress);
console.log('=== Liquidation Risk Monitor ===\n');
if (status.liquidatable) {
console.error('⚠️ CRITICAL: Positions are liquidatable!');
console.error('Action required: Add margin or reduce position size');
} else {
console.log('✓ Positions are safe from liquidation');
}
return status.liquidatable;
}
// Usage
const atRisk = await monitorLiquidationRisk('0x420a4ed7b6bb361da586868adec2f2bb9ab75e66');
```
### 2. Build Liquidation Alert System
Create automated liquidation alerts:
```javascript
class LiquidationAlertSystem {
constructor(userAddress, checkIntervalMs = 30000) {
this.userAddress = userAddress;
this.checkIntervalMs = checkIntervalMs;
this.wasLiquidatable = false;
}
async start(onAlert) {
while (true) {
try {
const status = await checkLiquidatable(this.userAddress);
if (status.liquidatable && !this.wasLiquidatable) {
// Just became liquidatable - send alert
onAlert({
severity: 'critical',
message: 'Positions now liquidatable!',
timestamp: new Date().toISOString()
});
} else if (!status.liquidatable && this.wasLiquidatable) {
// No longer liquidatable - send recovery alert
onAlert({
severity: 'info',
message: 'Positions no longer liquidatable',
timestamp: new Date().toISOString()
});
}
this.wasLiquidatable = status.liquidatable;
} catch (error) {
console.error('Alert system error:', error);
}
await new Promise(r => setTimeout(r, this.checkIntervalMs));
}
}
}
// Usage
const alertSystem = new LiquidationAlertSystem('0x420a4ed7b6bb361da586868adec2f2bb9ab75e66');
alertSystem.start((alert) => {
console.log(`[${alert.severity.toUpperCase()}] ${alert.message}`);
// Send notification via email, SMS, etc.
});
```
### 3. Risk Dashboard
Create a risk management dashboard:
```javascript
async function getRiskDashboard(userAddress) {
try {
const status = await checkLiquidatable(userAddress);
return {
status: 'success',
liquidationRisk: status.liquidatable ? 'HIGH' : 'LOW',
isLiquidatable: status.liquidatable,
recommendation: status.liquidatable
? 'Immediate action required: Add margin or close positions'
: 'Positions are within safe margins',
lastChecked: new Date().toISOString()
};
} catch (error) {
return {
status: 'error',
error: error.message
};
}
}
// Usage
const dashboard = await getRiskDashboard('0x420a4ed7b6bb361da586868adec2f2bb9ab75e66');
console.log('Risk Dashboard:', dashboard);
```
### 4. Pre-Trade Risk Check
Check liquidation risk before opening new positions:
```javascript
async function preTradeRiskCheck(userAddress) {
const status = await checkLiquidatable(userAddress);
if (status.liquidatable) {
return {
canTrade: false,
reason: 'Existing positions are liquidatable',
recommendation: 'Resolve liquidation risk before opening new positions'
};
}
return {
canTrade: true,
reason: 'Account health is good',
recommendation: 'Safe to proceed with new trades'
};
}
// Usage
const riskCheck = await preTradeRiskCheck('0x420a4ed7b6bb361da586868adec2f2bb9ab75e66');
if (riskCheck.canTrade) {
console.log('✓ Safe to open new positions');
} else {
console.error(`✗ Cannot trade: ${riskCheck.reason}`);
}
```
### 5. Continuous Risk Monitoring
Monitor risk with logging:
```javascript
async function continuousRiskMonitoring(userAddress, logInterval = 60000) {
const riskLog = [];
const monitor = async () => {
const status = await checkLiquidatable(userAddress);
const logEntry = {
timestamp: new Date().toISOString(),
liquidatable: status.liquidatable,
riskLevel: status.liquidatable ? 'CRITICAL' : 'SAFE'
};
riskLog.push(logEntry);
console.log(`[${logEntry.timestamp}] Risk: ${logEntry.riskLevel}`);
if (status.liquidatable) {
console.error('⚠️ ALERT: Liquidation risk detected!');
}
};
// Run immediately and then at intervals
await monitor();
setInterval(monitor, logInterval);
return riskLog;
}
// Usage
const riskLog = await continuousRiskMonitoring(
'0x420a4ed7b6bb361da586868adec2f2bb9ab75e66',
60000 // Check every minute
);
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `400 Bad Request` | Missing or invalid user address | Ensure valid Ethereum address format |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Missing required parameter: user",
"code": "MISSING_PARAMETER"
}
```
### Robust Error Handling
```javascript
async function safeCheckLiquidatable(userAddress, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await checkLiquidatable(userAddress);
} catch (error) {
if (error.response?.status === 429) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (error.response?.status === 400) {
throw new Error('Invalid user address');
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Check frequently** — Monitor every 30-60 seconds for active positions
2. **Set up alerts** — Implement immediate notifications for liquidation risk
3. **Act quickly** — Respond immediately when positions become liquidatable
4. **Combine with margin data** — Use with clearinghouseState for full context
5. **Log history** — Track risk over time for pattern analysis
## Performance Considerations
### Efficient Risk Monitoring
```javascript
class EfficientRiskMonitor {
constructor(userAddress) {
this.userAddress = userAddress;
this.cache = null;
this.cacheTime = 0;
this.cacheDuration = 10000; // 10 seconds
}
async check(forceRefresh = false) {
const now = Date.now();
if (!forceRefresh && this.cache && (now - this.cacheTime) < this.cacheDuration) {
return this.cache;
}
const status = await checkLiquidatable(this.userAddress);
this.cache = status;
this.cacheTime = now;
return status;
}
}
```
## Related Endpoints
- [**clearinghouseState**](./clearinghouse-state) — Get detailed margin and position data
- [**openOrders**](./open-orders) — View orders that may affect liquidation risk
- [**userFees**](./user-fees) — Understand fee impact on margin
- [**meta**](./meta) — Get liquidation price calculations
---
*Protect your positions with real-time liquidation monitoring via Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## maxBuilderFee - HyperCore Info Endpoint
# maxBuilderFee
Get maximum builder fee information on Hyperliquid, including fee limits and builder incentive structures.
## When to Use This Endpoint
The `maxBuilderFee` endpoint is essential for:
- **Builder Operations** — Understand maximum allowable builder fees
- **Fee Calculations** — Calculate builder incentives and costs
- **MEV Strategies** — Plan maximum extractable value strategies
- **Cost Estimation** — Estimate total transaction costs including builder fees
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"maxBuilderFee"` |
### Example Request
```json
{
"type": "maxBuilderFee"
}
```
## Response
### Success Response
Returns maximum builder fee information.
```json
{
"maxFee": "0.001"
}
```
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `maxFee` | `string` | Maximum builder fee as a decimal value |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{"type":"maxBuilderFee"}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getMaxBuilderFee() {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'maxBuilderFee'
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const feeData = await getMaxBuilderFee();
console.log(`Maximum builder fee: ${feeData.maxFee}`);
```
```python
from typing import Dict
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_max_builder_fee() -> Dict:
"""Get maximum builder fee information"""
response = requests.post(
ENDPOINT,
json={'type': 'maxBuilderFee'},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
fee_data = get_max_builder_fee()
print(f"Maximum builder fee: {fee_data['maxFee']}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type MaxBuilderFeeRequest struct {
Type string `json:"type"`
}
type MaxBuilderFeeResponse struct {
MaxFee string `json:"maxFee"`
}
func getMaxBuilderFee() (*MaxBuilderFeeResponse, error) {
reqBody, _ := json.Marshal(MaxBuilderFeeRequest{
Type: "maxBuilderFee",
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result MaxBuilderFeeResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
feeData, err := getMaxBuilderFee()
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Maximum builder fee: %s\n", feeData.MaxFee)
}
```
## Common Use Cases
### 1. Check Maximum Builder Fee
Display current maximum builder fee:
```javascript
async function checkMaxBuilderFee() {
const feeData = await getMaxBuilderFee();
console.log('=== Maximum Builder Fee ===\n');
console.log(`Max fee: ${feeData.maxFee}`);
const feePercent = parseFloat(feeData.maxFee) * 100;
console.log(`As percentage: ${feePercent}%`);
}
// Usage
await checkMaxBuilderFee();
```
### 2. Calculate Builder Fee for Transaction
Estimate builder fee for a transaction:
```javascript
async function calculateBuilderFee(transactionValue) {
const feeData = await getMaxBuilderFee();
const maxFeeRate = parseFloat(feeData.maxFee);
const estimatedFee = transactionValue * maxFeeRate;
return {
transactionValue: transactionValue,
maxFeeRate: maxFeeRate,
estimatedFee: estimatedFee,
feePercent: maxFeeRate * 100
};
}
// Usage
const fee = await calculateBuilderFee(10000); // $10,000 transaction
console.log(`Estimated builder fee: $${fee.estimatedFee.toFixed(2)}`);
console.log(`Fee rate: ${fee.feePercent}%`);
```
### 3. Compare to Transaction Costs
Compare builder fee to total costs:
```javascript
async function analyzeTotalCosts(transactionValue, tradingFee = 0.0002) {
const feeData = await getMaxBuilderFee();
const builderFeeRate = parseFloat(feeData.maxFee);
const builderFee = transactionValue * builderFeeRate;
const tradingFeeCost = transactionValue * tradingFee;
const totalCost = builderFee + tradingFeeCost;
return {
transactionValue: transactionValue,
builderFee: builderFee,
tradingFee: tradingFeeCost,
totalCost: totalCost,
builderFeePercent: (builderFee / totalCost) * 100
};
}
// Usage
const costs = await analyzeTotalCosts(10000);
console.log(`Builder fee: $${costs.builderFee.toFixed(2)}`);
console.log(`Trading fee: $${costs.tradingFee.toFixed(2)}`);
console.log(`Total cost: $${costs.totalCost.toFixed(2)}`);
```
### 4. Builder Fee Monitor
Monitor changes in maximum builder fee:
```javascript
class BuilderFeeMonitor {
constructor(checkIntervalMs = 300000) {
this.checkIntervalMs = checkIntervalMs; // 5 minutes
this.lastFee = null;
}
async start() {
const check = async () => {
const feeData = await getMaxBuilderFee();
const currentFee = parseFloat(feeData.maxFee);
if (this.lastFee !== null && currentFee !== this.lastFee) {
const change = ((currentFee - this.lastFee) / this.lastFee) * 100;
console.log(`Builder fee changed: ${change > 0 ? '+' : ''}${change.toFixed(2)}%`);
}
this.lastFee = currentFee;
console.log(`Current max builder fee: ${currentFee}`);
};
await check();
setInterval(check, this.checkIntervalMs);
}
}
// Usage
const monitor = new BuilderFeeMonitor();
monitor.start();
```
### 5. Fee Comparison Tool
Compare builder fees across scenarios:
```javascript
async function compareBuilderFees(transactionValues) {
const feeData = await getMaxBuilderFee();
const feeRate = parseFloat(feeData.maxFee);
const comparisons = transactionValues.map(value => ({
value: value,
builderFee: value * feeRate,
feePercent: feeRate * 100
}));
console.log('=== Builder Fee Comparison ===\n');
comparisons.forEach(comp => {
console.log(`Transaction: $${comp.value.toLocaleString()}`);
console.log(`Builder fee: $${comp.builderFee.toFixed(2)}`);
console.log('---');
});
return comparisons;
}
// Usage
await compareBuilderFees([1000, 5000, 10000, 50000]);
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Invalid request",
"code": "INVALID_REQUEST"
}
```
### Robust Error Handling
```javascript
async function safeGetMaxBuilderFee(maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getMaxBuilderFee();
} catch (error) {
if (error.response?.status === 429) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Cache appropriately** — Builder fee changes infrequently, cache for 5-10 minutes
2. **Include in cost calculations** — Always factor builder fees into total costs
3. **Monitor changes** — Track fee changes for cost projections
4. **Display clearly** — Show builder fees separately in UI for transparency
5. **Use precise decimals** — Maintain precision for accurate fee calculations
## Performance Tips
### Cached Fee Retrieval
```javascript
class CachedBuilderFeeService {
constructor(cacheDurationMs = 300000) {
this.cache = null;
this.cacheTime = 0;
this.cacheDurationMs = cacheDurationMs; // 5 minutes
}
async getMaxFee() {
const now = Date.now();
if (this.cache && (now - this.cacheTime) < this.cacheDurationMs) {
return this.cache;
}
const feeData = await getMaxBuilderFee();
this.cache = feeData;
this.cacheTime = now;
return feeData;
}
invalidate() {
this.cache = null;
this.cacheTime = 0;
}
}
// Usage
const feeService = new CachedBuilderFeeService();
const feeData = await feeService.getMaxFee();
```
## Related Endpoints
- [**userFees**](./user-fees) — Get user trading fees
- [**maxMarketOrderNtls**](./max-market-order-ntls) — Get maximum market order sizes
- [**meta**](./meta) — Get trading pair metadata
- [**exchangeStatus**](./exchange-status) — Get exchange status
---
*Access builder fee information with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## maxMarketOrderNtls - HyperCore Info Endpoint
# maxMarketOrderNtls
Get maximum market order notional values for trading pairs on Hyperliquid, helping traders understand order size limits.
## When to Use This Endpoint
The `maxMarketOrderNtls` endpoint is essential for:
- **Order Validation** — Check if order size is within allowed limits
- **Trading Strategy** — Plan large orders based on market constraints
- **Risk Management** — Understand maximum position sizes
- **Market Impact** — Estimate potential market impact of large orders
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"maxMarketOrderNtls"` |
### Example Request
```json
{
"type": "maxMarketOrderNtls"
}
```
## Response
### Success Response
Returns maximum market order notional values for trading pairs.
```json
{
"limits": {}
}
```
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `limits` | `object` | Object mapping trading pairs to their maximum market order notional values |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{"type":"maxMarketOrderNtls"}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getMaxMarketOrderNtls() {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'maxMarketOrderNtls'
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const limits = await getMaxMarketOrderNtls();
console.log('Market order limits loaded');
```
```python
from typing import Dict
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_max_market_order_ntls() -> Dict:
"""Get maximum market order notional values"""
response = requests.post(
ENDPOINT,
json={'type': 'maxMarketOrderNtls'},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
limits = get_max_market_order_ntls()
print("Market order limits loaded")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type MaxMarketOrderNtlsRequest struct {
Type string `json:"type"`
}
type MaxMarketOrderNtlsResponse struct {
Limits map[string]interface{} `json:"limits"`
}
func getMaxMarketOrderNtls() (*MaxMarketOrderNtlsResponse, error) {
reqBody, _ := json.Marshal(MaxMarketOrderNtlsRequest{
Type: "maxMarketOrderNtls",
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result MaxMarketOrderNtlsResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
limits, err := getMaxMarketOrderNtls()
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Println("Market order limits loaded")
}
```
## Common Use Cases
### 1. Check Maximum Order Size
Verify if an order size is within limits:
```javascript
async function checkOrderSize(asset, orderValue) {
const data = await getMaxMarketOrderNtls();
const maxNotional = data.limits[asset];
if (!maxNotional) {
console.log(`No limit data for ${asset}`);
return null;
}
const isValid = orderValue <= parseFloat(maxNotional);
console.log(`Order size: $${orderValue.toLocaleString()}`);
console.log(`Maximum allowed: $${parseFloat(maxNotional).toLocaleString()}`);
console.log(`Valid: ${isValid ? 'Yes' : 'No - exceeds limit'}`);
return isValid;
}
// Usage
await checkOrderSize('BTC', 50000);
```
### 2. Validate Order Before Submission
Pre-validate orders against limits:
```javascript
async function validateMarketOrder(asset, orderValue) {
const data = await getMaxMarketOrderNtls();
const maxNotional = parseFloat(data.limits[asset] || 0);
if (orderValue > maxNotional) {
return {
valid: false,
reason: `Order size $${orderValue} exceeds maximum $${maxNotional}`,
maxAllowed: maxNotional
};
}
return {
valid: true,
reason: 'Order size within limits',
maxAllowed: maxNotional
};
}
// Usage
const validation = await validateMarketOrder('ETH', 100000);
if (!validation.valid) {
console.error(`Cannot place order: ${validation.reason}`);
}
```
### 3. Calculate Maximum Position Size
Determine maximum position that can be opened:
```javascript
async function getMaxPositionSize(asset, currentPrice) {
const data = await getMaxMarketOrderNtls();
const maxNotional = parseFloat(data.limits[asset] || 0);
const maxPositionSize = maxNotional / currentPrice;
return {
asset: asset,
currentPrice: currentPrice,
maxNotionalValue: maxNotional,
maxPositionSize: maxPositionSize,
unit: asset
};
}
// Usage
const maxPosition = await getMaxPositionSize('BTC', 45000);
console.log(`Maximum position: ${maxPosition.maxPositionSize.toFixed(4)} ${maxPosition.unit}`);
console.log(`Notional value: $${maxPosition.maxNotionalValue.toLocaleString()}`);
```
### 4. Build Order Size Calculator
Create an order size calculator with validation:
```javascript
async function calculateOrderSizes(asset, currentPrice) {
const data = await getMaxMarketOrderNtls();
const maxNotional = parseFloat(data.limits[asset] || 0);
const suggestions = [0.25, 0.5, 0.75, 1.0].map(percent => {
const notionalValue = maxNotional * percent;
const positionSize = notionalValue / currentPrice;
return {
percentage: percent * 100,
notionalValue: notionalValue,
positionSize: positionSize
};
});
console.log(`=== Order Size Suggestions for ${asset} ===\n`);
suggestions.forEach(s => {
console.log(`${s.percentage}% of max: ${s.positionSize.toFixed(4)} ${asset} ($${s.notionalValue.toLocaleString()})`);
});
return suggestions;
}
// Usage
await calculateOrderSizes('BTC', 45000);
```
### 5. Monitor Limit Changes
Track changes in order limits:
```javascript
class OrderLimitMonitor {
constructor(checkIntervalMs = 300000) {
this.checkIntervalMs = checkIntervalMs; // 5 minutes
this.lastLimits = null;
}
async start() {
const check = async () => {
const data = await getMaxMarketOrderNtls();
if (this.lastLimits) {
for (const [asset, limit] of Object.entries(data.limits)) {
const lastLimit = this.lastLimits[asset];
if (lastLimit && lastLimit !== limit) {
console.log(`Limit changed for ${asset}: ${lastLimit} -> ${limit}`);
}
}
}
this.lastLimits = data.limits;
};
await check();
setInterval(check, this.checkIntervalMs);
}
}
// Usage
const monitor = new OrderLimitMonitor();
monitor.start();
```
### 6. Split Large Orders
Suggest order splitting for sizes exceeding limits:
```javascript
async function splitLargeOrder(asset, desiredValue) {
const data = await getMaxMarketOrderNtls();
const maxNotional = parseFloat(data.limits[asset] || 0);
if (desiredValue <= maxNotional) {
return {
needsSplit: false,
message: 'Order within limits',
orders: [{ value: desiredValue }]
};
}
const numOrders = Math.ceil(desiredValue / maxNotional);
const orderSize = desiredValue / numOrders;
const orders = Array(numOrders).fill(null).map((_, i) => ({
orderNumber: i + 1,
value: orderSize
}));
return {
needsSplit: true,
message: `Split into ${numOrders} orders`,
totalValue: desiredValue,
maxPerOrder: maxNotional,
orders: orders
};
}
// Usage
const split = await splitLargeOrder('BTC', 200000);
if (split.needsSplit) {
console.log(`Order needs splitting: ${split.message}`);
split.orders.forEach(order => {
console.log(`Order ${order.orderNumber}: $${order.value.toLocaleString()}`);
});
}
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Invalid request",
"code": "INVALID_REQUEST"
}
```
### Robust Error Handling
```javascript
async function safeGetMaxMarketOrderNtls(maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getMaxMarketOrderNtls();
} catch (error) {
if (error.response?.status === 429) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Cache limits** — Order limits change infrequently, cache for 5-10 minutes
2. **Validate before submission** — Always check limits before placing orders
3. **Handle missing data** — Some assets may not have limit data
4. **Use buffer** — Stay 5-10% below maximum to account for price fluctuations
5. **Monitor changes** — Track limit changes that may affect trading strategies
## Performance Tips
### Cached Limit Service
```javascript
class CachedOrderLimitService {
constructor(cacheDurationMs = 300000) {
this.cache = null;
this.cacheTime = 0;
this.cacheDurationMs = cacheDurationMs; // 5 minutes
}
async getLimits() {
const now = Date.now();
if (this.cache && (now - this.cacheTime) < this.cacheDurationMs) {
return this.cache;
}
const data = await getMaxMarketOrderNtls();
this.cache = data;
this.cacheTime = now;
return data;
}
async getLimitForAsset(asset) {
const data = await this.getLimits();
return parseFloat(data.limits[asset] || 0);
}
invalidate() {
this.cache = null;
this.cacheTime = 0;
}
}
// Usage
const limitService = new CachedOrderLimitService();
const btcLimit = await limitService.getLimitForAsset('BTC');
```
## Related Endpoints
- [**meta**](./meta) — Get trading pair metadata
- [**openOrders**](./open-orders) — View current orders
- [**clearinghouseState**](./clearinghouse-state) — Check account capacity
- [**maxBuilderFee**](./max-builder-fee) — Get builder fee limits
---
*Optimize your trading with order limit information from Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## meta - HyperCore Info Endpoint
# meta
Get metadata for all available **perpetual futures trading pairs** on Hyperliquid, including leverage limits, decimal precision, and margin requirements.
:::info Perpetual Futures Metadata
This endpoint returns metadata for **perpetual futures markets**. For spot trading metadata, see [**spotMeta**](./spot-meta).
:::
> **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 Endpoint
The `meta` endpoint is essential for derivatives traders, trading platforms, and market data providers who need to:
- **Validate Order Parameters** — Ensure orders comply with leverage and size requirements
- **Build Trading Interfaces** — Display available markets with correct decimal precision
- **Market Discovery** — List all tradeable perpetual contracts
- **Risk Management** — Monitor leverage limits and margin requirements
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"meta"` |
| `dex` | `string` | No | HIP3 perp DEX identifier. Valid values: `"xyz"`, `"flx"`, `"vntl"`, `"hyna"`, `"cash"`. Omit for Hyperliquid mainnet perpetuals. |
### Example Requests
**Hyperliquid Mainnet Perpetuals:**
```json
{
"type": "meta"
}
```
**HIP3 Perp DEX (e.g., xyz):**
```json
{
"type": "meta",
"dex": "xyz"
}
```
:::tip HIP3 Perp DEXs
HIP3 (Hyperliquid Improvement Proposal 3) enables permissionless perpetual futures DEXs built on Hyperliquid. Use the `dex` parameter to query metadata from specific HIP3 perp DEXs:
- **xyz** - XYZ perpetuals DEX
- **flx** - FLX perpetuals DEX
- **vntl** - VNTL perpetuals DEX
- **hyna** - HYNA perpetuals DEX
- **cash** - CASH perpetuals DEX
Omit the `dex` parameter to query Hyperliquid's mainnet perpetual markets.
:::
## Response
### Hyperliquid Mainnet Response
```json
{
"universe": [
{
"szDecimals": 5,
"name": "BTC",
"maxLeverage": 40,
"marginTableId": 56
},
{
"szDecimals": 4,
"name": "ETH",
"maxLeverage": 25,
"marginTableId": 55
},
{
"szDecimals": 2,
"name": "SOL",
"maxLeverage": 20,
"marginTableId": 54
},
{
"szDecimals": 1,
"name": "MATIC",
"maxLeverage": 20,
"marginTableId": 20,
"isDelisted": true
}
],
"marginTables": [
[
56,
{
"description": "tiered 40x",
"marginTiers": [
{
"lowerBound": "0.0",
"maxLeverage": 40
},
{
"lowerBound": "150000000.0",
"maxLeverage": 20
}
]
}
]
],
"collateralToken": 0
}
```
### HIP3 DEX Response (e.g., xyz)
```json
{
"universe": [
{
"szDecimals": 4,
"name": "xyz:XYZ100",
"maxLeverage": 25,
"marginTableId": 25,
"onlyIsolated": true,
"marginMode": "noCross",
"growthMode": "enabled",
"lastGrowthModeChangeTime": "2025-11-23T17:37:10.033211662"
},
{
"szDecimals": 3,
"name": "xyz:TSLA",
"maxLeverage": 10,
"marginTableId": 10,
"onlyIsolated": true,
"marginMode": "strictIsolated",
"growthMode": "enabled",
"lastGrowthModeChangeTime": "2025-11-23T17:37:10.033211662"
},
{
"szDecimals": 4,
"name": "xyz:GOLD",
"maxLeverage": 20,
"marginTableId": 20,
"onlyIsolated": true,
"marginMode": "noCross"
}
],
"marginTables": [
[
50,
{
"description": "",
"marginTiers": [
{
"lowerBound": "0.0",
"maxLeverage": 50
}
]
}
]
],
"collateralToken": 0
}
```
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `universe` | `array` | Array of trading pair objects |
| `marginTables` | `array` | Array of margin table definitions with tier structures |
| `collateralToken` | `integer` | Collateral token ID |
#### Trading Pair Object (Hyperliquid Mainnet)
| Field | Type | Description |
|-------|------|-------------|
| `szDecimals` | `integer` | Decimal places for position size |
| `name` | `string` | Asset symbol (e.g., "BTC", "ETH", "SOL") |
| `maxLeverage` | `integer` | Maximum allowed leverage for this asset |
| `marginTableId` | `integer` | ID referencing the margin table for this asset |
| `isDelisted` | `boolean` | *(Optional)* `true` if the asset is delisted |
| `onlyIsolated` | `boolean` | *(Optional)* `true` if only isolated margin is allowed |
#### Trading Pair Object (HIP3 DEX)
HIP3 DEX responses include additional fields:
| Field | Type | Description |
|-------|------|-------------|
| `szDecimals` | `integer` | Decimal places for position size |
| `name` | `string` | Asset symbol with DEX prefix (e.g., "xyz:TSLA", "xyz:GOLD") |
| `maxLeverage` | `integer` | Maximum allowed leverage for this asset |
| `marginTableId` | `integer` | ID referencing the margin table for this asset |
| `onlyIsolated` | `boolean` | `true` if only isolated margin is allowed |
| `marginMode` | `string` | Margin mode: `"noCross"`, `"strictIsolated"` |
| `growthMode` | `string` | *(Optional)* Growth mode status (e.g., `"enabled"`) |
| `lastGrowthModeChangeTime` | `string` | *(Optional)* ISO 8601 timestamp of last growth mode change |
| `isDelisted` | `boolean` | *(Optional)* `true` if the asset is delisted |
#### Margin Table Entry
Each margin table entry is a tuple `[tableId, tableData]`:
| Field | Type | Description |
|-------|------|-------------|
| `tableId` | `integer` | Unique identifier for this margin table |
| `tableData` | `object` | Margin table configuration |
**Table Data Object:**
| Field | Type | Description |
|-------|------|-------------|
| `description` | `string` | Human-readable description of the margin table |
| `marginTiers` | `array` | Array of margin tier objects defining leverage limits by position size |
**Margin Tier Object:**
| Field | Type | Description |
|-------|------|-------------|
| `lowerBound` | `string` | Minimum notional position size for this tier |
| `maxLeverage` | `integer` | Maximum leverage allowed at this tier |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{"type":"meta"}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getMeta() {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ type: 'meta' })
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const meta = await getMeta();
console.log(`Available markets: ${meta.universe.length}`);
// Find specific market
const btcMeta = meta.universe.find(m => m.name === 'BTC');
console.log(`BTC max leverage: ${btcMeta.maxLeverage}x`);
```
```python
from typing import Dict, List
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_meta() -> Dict:
"""Get trading pair metadata"""
response = requests.post(
ENDPOINT,
json={'type': 'meta'},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
meta = get_meta()
print(f"Available markets: {len(meta['universe'])}")
# Find specific market
btc_meta = next(m for m in meta['universe'] if m['name'] == 'BTC')
print(f"BTC max leverage: {btc_meta['maxLeverage']}x")
print(f"BTC size decimals: {btc_meta['szDecimals']}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type MetaRequest struct {
Type string `json:"type"`
}
type TradingPair struct {
Name string `json:"name"`
SzDecimals int `json:"szDecimals"`
MaxLeverage int `json:"maxLeverage"`
OnlyIsolated bool `json:"onlyIsolated"`
}
type MetaResponse struct {
Universe []TradingPair `json:"universe"`
}
func getMeta() (*MetaResponse, error) {
reqBody, _ := json.Marshal(MetaRequest{Type: "meta"})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result MetaResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
meta, err := getMeta()
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Available markets: %d\n", len(meta.Universe))
// Find BTC
for _, pair := range meta.Universe {
if pair.Name == "BTC" {
fmt.Printf("BTC max leverage: %dx\n", pair.MaxLeverage)
break
}
}
}
```
## Common Use Cases
### 1. Validate Order Leverage
Check if an order's leverage is within allowed limits:
```javascript
async function validateLeverage(asset, leverage) {
const meta = await getMeta();
const assetMeta = meta.universe.find(m => m.name === asset);
if (!assetMeta) {
throw new Error(`Asset ${asset} not found`);
}
if (leverage > assetMeta.maxLeverage) {
throw new Error(
`Leverage ${leverage}x exceeds maximum ${assetMeta.maxLeverage}x for ${asset}`
);
}
return true;
}
```
### 2. Format Position Sizes
Format position sizes with correct decimal precision:
```javascript
function formatSize(asset, size, meta) {
const assetMeta = meta.universe.find(m => m.name === asset);
if (!assetMeta) return size.toString();
return size.toFixed(assetMeta.szDecimals);
}
// Usage
const meta = await getMeta();
console.log(formatSize('BTC', 0.123456, meta)); // "0.12345"
console.log(formatSize('ETH', 1.23456, meta)); // "1.2346"
```
### 3. Build Market Selector UI
Create a market selector with leverage information:
```javascript
async function getMarketList() {
const meta = await getMeta();
return meta.universe.map(market => ({
symbol: market.name,
maxLeverage: market.maxLeverage,
marginType: market.onlyIsolated ? 'Isolated Only' : 'Cross/Isolated',
decimals: market.szDecimals
}));
}
// Usage
const markets = await getMarketList();
markets.forEach(m => {
console.log(`${m.symbol}: ${m.maxLeverage}x leverage (${m.marginType})`);
});
```
### 4. Cache Metadata
Cache metadata to reduce API calls:
```javascript
class MetaCache {
constructor(ttl = 3600000) { // 1 hour default
this.cache = null;
this.timestamp = 0;
this.ttl = ttl;
}
async get() {
const now = Date.now();
if (this.cache && (now - this.timestamp) < this.ttl) {
return this.cache;
}
this.cache = await getMeta();
this.timestamp = now;
return this.cache;
}
invalidate() {
this.cache = null;
this.timestamp = 0;
}
}
const metaCache = new MetaCache();
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `429 Too Many Requests` | Rate limit exceeded | Implement caching and backoff |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Invalid API key",
"code": "UNAUTHORIZED"
}
```
### Robust Error Handling
```javascript
async function safeGetMeta(maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getMeta();
} catch (error) {
if (error.response?.status === 429) {
// Rate limit - exponential backoff
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Cache metadata** for at least 1 hour as it changes infrequently
2. **Validate leverage** before submitting orders to avoid rejections
3. **Use correct decimals** when formatting position sizes
4. **Handle errors gracefully** with retry logic and fallbacks
5. **Monitor rate limits** to avoid service interruptions
## Related Endpoints
- [**spotMeta**](./spot-meta) — Get spot trading asset metadata
- [**exchangeStatus**](./exchange-status) — Check exchange health and status
- [**clearinghouseState**](./clearinghouse-state) — Get user account state with positions
---
*Access real-time Hyperliquid market metadata with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## openOrders - HyperCore Info Endpoint
# openOrders
Get all open limit orders for a user on Hyperliquid perpetual markets.
> **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 Endpoint
The `openOrders` endpoint is essential for traders, trading platforms, and market makers who need to:
- **Order Management** — Monitor and manage active limit orders
- **Trading Bots** — Track order status and execution
- **Market Making** — Monitor spread and order book participation
- **Portfolio Management** — Track pending orders across multiple markets
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"openOrders"` |
| `user` | `string` | Yes | User's Ethereum wallet address |
### Example Request
```json
{
"type": "openOrders",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}
```
## Response
### Success Response
```json
[
{
"coin": "BTC",
"side": "B",
"limitPx": "69043.0",
"sz": "0.29596",
"oid": 316509475419,
"timestamp": 1770639841704,
"origSz": "0.29596",
"cloid": "0x00000000000000000000019c4151ce32"
},
{
"coin": "ETH",
"side": "A",
"limitPx": "2034.3",
"sz": "12.1703",
"oid": 316509474405,
"timestamp": 1770639841704,
"origSz": "12.1703",
"cloid": "0x00000000000000000000019c4151ce2f"
}
]
```
### Response Fields
The response is an array of order objects. Each order contains:
| Field | Type | Description |
|-------|------|-------------|
| `coin` | `string` | Trading pair symbol (e.g., "BTC", "ETH") |
| `side` | `string` | Order side: `"B"` for buy, `"A"` for ask/sell |
| `limitPx` | `string` | Limit price for the order |
| `sz` | `string` | Current remaining order size |
| `oid` | `integer` | Unique order ID |
| `timestamp` | `integer` | Order creation timestamp in milliseconds |
| `origSz` | `string` | Original order size when placed |
| `cloid` | `string` | Client order ID (hexadecimal string) |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "openOrders",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getOpenOrders(userAddress) {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'openOrders',
user: userAddress
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const orders = await getOpenOrders('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log(`Total open orders: ${orders.length}`);
// Display orders
orders.forEach(order => {
const side = order.side === 'B' ? 'BUY' : 'SELL';
const filled = ((parseFloat(order.origSz) - parseFloat(order.sz)) / parseFloat(order.origSz)) * 100;
console.log(
`${side} ${order.sz}/${order.origSz} ${order.coin} @ $${order.limitPx} (${filled.toFixed(1)}% filled)`
);
});
```
```python
from typing import List, Dict
from datetime import datetime
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_open_orders(user_address: str) -> List[Dict]:
"""Get all open orders for a user"""
response = requests.post(
ENDPOINT,
json={
'type': 'openOrders',
'user': user_address
},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
orders = get_open_orders('0x63E8c7C149556D5f34F833419A287bb9Ef81487f')
print(f"Total open orders: {len(orders)}")
# Display orders
for order in orders:
side = "BUY" if order['side'] == 'B' else "SELL"
filled_pct = ((float(order['origSz']) - float(order['sz'])) / float(order['origSz'])) * 100
timestamp = datetime.fromtimestamp(order['timestamp'] / 1000)
print(f"{side} {order['sz']}/{order['origSz']} {order['coin']} @ ${order['limitPx']}")
print(f" Order ID: {order['oid']}")
print(f" Filled: {filled_pct:.1f}%")
print(f" Created: {timestamp}")
print()
# Group by market
from collections import defaultdict
by_market = defaultdict(list)
for order in orders:
by_market[order['coin']].append(order)
for market, market_orders in by_market.items():
print(f"{market}: {len(market_orders)} orders")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type OpenOrdersRequest struct {
Type string `json:"type"`
User string `json:"user"`
}
type Order struct {
Coin string `json:"coin"`
Side string `json:"side"`
LimitPx string `json:"limitPx"`
Sz string `json:"sz"`
Oid int64 `json:"oid"`
Timestamp int64 `json:"timestamp"`
OrigSz string `json:"origSz"`
}
func getOpenOrders(userAddress string) ([]Order, error) {
reqBody, _ := json.Marshal(OpenOrdersRequest{
Type: "openOrders",
User: userAddress,
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var orders []Order
if err := json.Unmarshal(body, &orders); err != nil {
return nil, err
}
return orders, nil
}
func main() {
orders, err := getOpenOrders("0x63E8c7C149556D5f34F833419A287bb9Ef81487f")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Total open orders: %d\n\n", len(orders))
for _, order := range orders {
side := "BUY"
if order.Side == "A" {
side = "SELL"
}
timestamp := time.Unix(order.Timestamp/1000, 0)
fmt.Printf("%s %s %s @ $%s\n", side, order.Sz, order.Coin, order.LimitPx)
fmt.Printf(" Order ID: %d\n", order.Oid)
fmt.Printf(" Original Size: %s\n", order.OrigSz)
fmt.Printf(" Created: %s\n\n", timestamp.Format(time.RFC3339))
}
}
```
## Common Use Cases
### 1. Monitor Order Fill Progress
Track how much of each order has been filled:
```javascript
async function getOrderFillProgress(userAddress) {
const orders = await getOpenOrders(userAddress);
return orders.map(order => {
const orig = parseFloat(order.origSz);
const remaining = parseFloat(order.sz);
const filled = orig - remaining;
const fillPercent = (filled / orig) * 100;
return {
orderId: order.oid,
coin: order.coin,
side: order.side === 'B' ? 'BUY' : 'SELL',
price: parseFloat(order.limitPx),
originalSize: orig,
remainingSize: remaining,
filledSize: filled,
fillPercent: fillPercent.toFixed(2),
isPartiallyFilled: fillPercent > 0 && fillPercent < 100
};
});
}
// Usage
const progress = await getOrderFillProgress('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
const partialFills = progress.filter(o => o.isPartiallyFilled);
console.log(`${partialFills.length} partially filled orders`);
```
### 2. Calculate Total Order Book Exposure
Calculate total capital committed in open orders:
```javascript
async function calculateOrderExposure(userAddress) {
const orders = await getOpenOrders(userAddress);
const totalExposure = orders.reduce((sum, order) => {
const size = parseFloat(order.sz);
const price = parseFloat(order.limitPx);
return sum + (size * price);
}, 0);
const byMarket = orders.reduce((acc, order) => {
const size = parseFloat(order.sz);
const price = parseFloat(order.limitPx);
const exposure = size * price;
if (!acc[order.coin]) {
acc[order.coin] = { buy: 0, sell: 0, total: 0 };
}
if (order.side === 'B') {
acc[order.coin].buy += exposure;
} else {
acc[order.coin].sell += exposure;
}
acc[order.coin].total += exposure;
return acc;
}, {});
return {
totalExposure: totalExposure,
byMarket: byMarket,
orderCount: orders.length
};
}
```
### 3. Find Stale Orders
Identify orders that have been open for a long time:
```javascript
async function findStaleOrders(userAddress, hoursThreshold = 24) {
const orders = await getOpenOrders(userAddress);
const now = Date.now();
const thresholdMs = hoursThreshold * 60 * 60 * 1000;
const staleOrders = orders.filter(order => {
return (now - order.timestamp) > thresholdMs;
});
return staleOrders.map(order => ({
orderId: order.oid,
coin: order.coin,
side: order.side === 'B' ? 'BUY' : 'SELL',
price: order.limitPx,
size: order.sz,
ageHours: ((now - order.timestamp) / (1000 * 60 * 60)).toFixed(1)
}));
}
// Usage
const stale = await findStaleOrders('0x63E8c7C149556D5f34F833419A287bb9Ef81487f', 48);
console.log(`${stale.length} orders older than 48 hours`);
stale.forEach(o => {
console.log(`${o.coin} ${o.side} @ $${o.price} (${o.ageHours}h old)`);
});
```
### 4. Group Orders by Market
Organize orders by trading pair:
```javascript
async function groupOrdersByMarket(userAddress) {
const orders = await getOpenOrders(userAddress);
const grouped = orders.reduce((acc, order) => {
if (!acc[order.coin]) {
acc[order.coin] = {
buy: [],
sell: [],
totalBuySize: 0,
totalSellSize: 0
};
}
const side = order.side === 'B' ? 'buy' : 'sell';
acc[order.coin][side].push(order);
if (side === 'buy') {
acc[order.coin].totalBuySize += parseFloat(order.sz);
} else {
acc[order.coin].totalSellSize += parseFloat(order.sz);
}
return acc;
}, {});
return grouped;
}
// Usage
const byMarket = await groupOrdersByMarket('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
Object.entries(byMarket).forEach(([coin, data]) => {
console.log(`\n${coin}:`);
console.log(` ${data.buy.length} buy orders (${data.totalBuySize} total)`);
console.log(` ${data.sell.length} sell orders (${data.totalSellSize} total)`);
});
```
### 5. Order Management Dashboard
Create a comprehensive order dashboard:
```javascript
async function getOrderDashboard(userAddress) {
const orders = await getOpenOrders(userAddress);
const now = Date.now();
const stats = {
totalOrders: orders.length,
buyOrders: orders.filter(o => o.side === 'B').length,
sellOrders: orders.filter(o => o.side === 'A').length,
markets: [...new Set(orders.map(o => o.coin))],
partiallyFilled: orders.filter(o => o.sz !== o.origSz).length,
averageAge: orders.reduce((sum, o) => sum + (now - o.timestamp), 0) / orders.length / (1000 * 60 * 60)
};
console.log('=== Order Dashboard ===');
console.log(`Total Orders: ${stats.totalOrders}`);
console.log(` Buy: ${stats.buyOrders}`);
console.log(` Sell: ${stats.sellOrders}`);
console.log(`Markets: ${stats.markets.join(', ')}`);
console.log(`Partially Filled: ${stats.partiallyFilled}`);
console.log(`Average Age: ${stats.averageAge.toFixed(1)} hours`);
return stats;
}
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `400 Bad Request` | Missing or invalid user address | Ensure valid Ethereum address format |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Missing required parameter: user",
"code": "MISSING_PARAMETER"
}
```
### Robust Error Handling
```javascript
async function safeGetOpenOrders(userAddress, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getOpenOrders(userAddress);
} catch (error) {
if (error.response?.status === 429) {
// Rate limit - exponential backoff
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (error.response?.status === 400) {
throw new Error('Invalid user address');
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Poll at appropriate intervals** — Poll every 5-10 seconds for active trading, less frequently for monitoring
2. **Handle empty arrays** — User may have no open orders
3. **Validate addresses** — Ensure user addresses are valid Ethereum addresses
4. **Track order IDs** — Use order IDs to track specific orders across polls
5. **Monitor fill rates** — Alert when orders are partially filled
## Related Endpoints
- [**clearinghouseState**](./clearinghouse-state) — Get account state with positions
- [**userFees**](./user-fees) — Get user fee rates
- [**frontendOpenOrders**](./frontend-open-orders) — Get formatted orders for frontend display
- [**meta**](./meta) — Get trading pair metadata
---
*Access real-time Hyperliquid order data with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## perpDexs - HyperCore Info Endpoint
# perpDexs
Get all third-party perpetual DEXs deployed on Hyperliquid's infrastructure, including their listed assets, open interest caps, funding parameters, and deployer configuration.
## When to Use This Endpoint
The `perpDexs` endpoint is essential for:
- **DEX Discovery** — Enumerate all perpetual DEXs deployed on Hyperliquid
- **Asset Listing** — Find which assets are available on each DEX and their open interest caps
- **Funding Analysis** — Query funding multipliers and interest rates across DEXs
- **Deployer Verification** — Verify deployer addresses and fee recipients for each DEX
- **Permission Auditing** — Inspect sub-deployer permissions and capabilities
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"perpDexs"` |
### Example Request
```json
{
"type": "perpDexs"
}
```
## Response
### Success Response
Returns an array of DEX objects. The array may contain `null` entries at certain indices.
```json
[
null,
{
"name": "xyz",
"fullName": "XYZ",
"deployer": "0x88806a71d74ad0a510b350545c9ae490912f0888",
"oracleUpdater": null,
"feeRecipient": "0x9cd0a696c7cbb9d44de99268194cb08e5684e5fe",
"assetToStreamingOiCap": [
["xyz:AAPL", "50000000.0"],
["xyz:GOLD", "500000000.0"],
["xyz:NVDA", "200000000.0"]
],
"subDeployers": [
["registerAsset", ["0x7d16f116d252db609c56d27d6c9605eb03e16657"]],
["setOracle", ["0x1234567890545d1df9ee64b35fdd16966e08acec"]]
],
"deployerFeeScale": "1.0",
"lastDeployerFeeScaleChangeTime": "1970-01-01T00:00:00",
"assetToFundingMultiplier": [
["xyz:AAPL", "0.5"],
["xyz:GOLD", "0.5"]
],
"assetToFundingInterestRate": []
}
]
```
### Response Fields
The response is an array where each non-null element is a DEX object.
#### DEX Object
| Field | Type | Description |
|-------|------|-------------|
| `name` | `string` | Short identifier for the DEX (e.g., `"xyz"`, `"flx"`) |
| `fullName` | `string` | Display name of the DEX (e.g., `"XYZ"`, `"Felix Exchange"`) |
| `deployer` | `string` | Ethereum address of the DEX deployer |
| `oracleUpdater` | `string \| null` | Address authorized to update oracles, or `null` |
| `feeRecipient` | `string \| null` | Address that receives trading fees, or `null` |
| `assetToStreamingOiCap` | `array` | List of `[assetName, capValue]` pairs |
| `subDeployers` | `array` | List of `[permission, [addresses]]` pairs |
| `deployerFeeScale` | `string` | Fee scale multiplier for the deployer |
| `lastDeployerFeeScaleChangeTime` | `string` | ISO 8601 timestamp of last fee scale change |
| `assetToFundingMultiplier` | `array` | List of `[assetName, multiplier]` pairs |
| `assetToFundingInterestRate` | `array` | List of `[assetName, rate]` pairs |
#### Asset Streaming OI Cap Entry
Each entry in `assetToStreamingOiCap` is a two-element array:
| Index | Type | Description |
|-------|------|-------------|
| `0` | `string` | Asset name prefixed with DEX name (e.g., `"xyz:GOLD"`) |
| `1` | `string` | Maximum open interest cap in USD |
#### Sub-Deployer Entry
Each entry in `subDeployers` is a two-element array:
| Index | Type | Description |
|-------|------|-------------|
| `0` | `string` | Permission type (e.g., `"registerAsset"`, `"setOracle"`, `"setOpenInterestCaps"`) |
| `1` | `array` | List of Ethereum addresses granted this permission |
#### Known Permission Types
| Permission | Description |
|------------|-------------|
| `registerAsset` | Register new trading assets |
| `setOracle` | Configure oracle sources |
| `insertMarginTable` | Insert margin table configurations |
| `haltTrading` | Halt trading on specific assets |
| `setMarginTableIds` | Assign margin table IDs to assets |
| `setOpenInterestCaps` | Set open interest limits |
| `setFundingMultipliers` | Configure funding rate multipliers |
| `setMarginModes` | Set margin mode options |
| `setFeeRecipient` | Change fee recipient address |
| `setFeeScale` | Adjust fee scaling |
| `setGrowthModes` | Configure growth modes |
| `setFundingInterestRates` | Set funding interest rates |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "perpDexs"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getPerpDexs() {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'perpDexs'
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const dexs = await getPerpDexs();
const activeDexs = dexs.filter(d => d !== null);
console.log(`Total DEXs: ${activeDexs.length}`);
activeDexs.forEach(dex => {
console.log(`${dex.fullName} (${dex.name}): ${dex.assetToStreamingOiCap.length} assets`);
});
```
```python
from typing import List, Optional, Dict
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_perp_dexs() -> List[Optional[Dict]]:
"""Get all perpetual DEXs deployed on Hyperliquid"""
response = requests.post(
ENDPOINT,
json={
'type': 'perpDexs'
},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
dexs = get_perp_dexs()
active_dexs = [d for d in dexs if d is not None]
print(f"Total DEXs: {len(active_dexs)}")
for dex in active_dexs:
asset_count = len(dex['assetToStreamingOiCap'])
print(f"{dex['fullName']} ({dex['name']}): {asset_count} assets")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type PerpDexsRequest struct {
Type string `json:"type"`
}
type PerpDex struct {
Name string `json:"name"`
FullName string `json:"fullName"`
Deployer string `json:"deployer"`
OracleUpdater *string `json:"oracleUpdater"`
FeeRecipient *string `json:"feeRecipient"`
AssetToStreamingOiCap [][2]string `json:"assetToStreamingOiCap"`
SubDeployers []json.RawMessage `json:"subDeployers"`
DeployerFeeScale string `json:"deployerFeeScale"`
LastDeployerFeeScaleChangeTime string `json:"lastDeployerFeeScaleChangeTime"`
AssetToFundingMultiplier [][2]string `json:"assetToFundingMultiplier"`
AssetToFundingInterestRate [][2]string `json:"assetToFundingInterestRate"`
}
func getPerpDexs() ([]*PerpDex, error) {
reqBody, _ := json.Marshal(PerpDexsRequest{
Type: "perpDexs",
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result []*PerpDex
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return result, nil
}
func main() {
dexs, err := getPerpDexs()
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
for _, dex := range dexs {
if dex == nil {
continue
}
fmt.Printf("%s (%s): %d assets\n",
dex.FullName, dex.Name, len(dex.AssetToStreamingOiCap))
}
}
```
## Common Use Cases
### 1. List All DEXs and Their Assets
Enumerate all deployed DEXs with their asset counts and total OI capacity:
```javascript
async function listDexOverview() {
const dexs = await getPerpDexs();
console.log('=== Perpetual DEXs on Hyperliquid ===\n');
dexs.filter(d => d !== null).forEach(dex => {
const totalOiCap = dex.assetToStreamingOiCap.reduce(
(sum, [, cap]) => sum + parseFloat(cap), 0
);
console.log(`${dex.fullName} (${dex.name})`);
console.log(` Deployer: ${dex.deployer}`);
console.log(` Assets: ${dex.assetToStreamingOiCap.length}`);
console.log(` Total OI Cap: $${(totalOiCap / 1e6).toFixed(1)}M`);
console.log(` Fee Scale: ${dex.deployerFeeScale}`);
console.log('');
});
}
```
### 2. Find a Specific Asset Across DEXs
Search for which DEXs list a specific asset:
```javascript
async function findAssetAcrossDexs(assetSymbol) {
const dexs = await getPerpDexs();
const results = [];
dexs.filter(d => d !== null).forEach(dex => {
const match = dex.assetToStreamingOiCap.find(
([name]) => name.split(':')[1] === assetSymbol
);
if (match) {
const fundingEntry = dex.assetToFundingMultiplier.find(
([name]) => name === match[0]
);
results.push({
dex: dex.fullName,
dexPrefix: dex.name,
asset: match[0],
oiCap: match[1],
fundingMultiplier: fundingEntry ? fundingEntry[1] : 'N/A'
});
}
});
console.log(`\n=== "${assetSymbol}" across DEXs ===\n`);
results.forEach(r => {
console.log(`${r.dex}: OI Cap $${(parseFloat(r.oiCap) / 1e6).toFixed(1)}M | Funding: ${r.fundingMultiplier}`);
});
return results;
}
// Usage
await findAssetAcrossDexs('GOLD');
```
### 3. Analyze Funding Parameters
Compare funding configurations across DEXs:
```javascript
async function analyzeFunding() {
const dexs = await getPerpDexs();
console.log('=== Funding Analysis ===\n');
dexs.filter(d => d !== null).forEach(dex => {
if (dex.assetToFundingMultiplier.length === 0 &&
dex.assetToFundingInterestRate.length === 0) {
console.log(`${dex.fullName}: No custom funding config`);
return;
}
console.log(`${dex.fullName}:`);
if (dex.assetToFundingMultiplier.length > 0) {
const multipliers = dex.assetToFundingMultiplier.map(([, m]) => parseFloat(m));
const avg = multipliers.reduce((a, b) => a + b, 0) / multipliers.length;
console.log(` Funding multipliers: ${multipliers.length} assets, avg ${avg.toFixed(4)}`);
}
if (dex.assetToFundingInterestRate.length > 0) {
console.log(` Interest rates: ${dex.assetToFundingInterestRate.length} assets`);
}
console.log('');
});
}
```
### 4. Audit Sub-Deployer Permissions
Review which addresses have administrative permissions:
```javascript
async function auditPermissions(dexName) {
const dexs = await getPerpDexs();
const dex = dexs.find(d => d !== null && d.name === dexName);
if (!dex) {
console.log(`DEX "${dexName}" not found`);
return;
}
console.log(`=== Permission Audit: ${dex.fullName} ===\n`);
console.log(`Deployer: ${dex.deployer}`);
console.log(`Oracle Updater: ${dex.oracleUpdater || 'None'}`);
console.log(`Fee Recipient: ${dex.feeRecipient || 'None'}`);
console.log('\nSub-Deployer Permissions:');
dex.subDeployers.forEach(([permission, addresses]) => {
console.log(` ${permission}:`);
addresses.forEach(addr => console.log(` - ${addr}`));
});
}
// Usage
await auditPermissions('xyz');
```
### 5. Monitor OI Cap Utilization
Build a dashboard showing available capacity:
```javascript
async function getOiCapSummary() {
const dexs = await getPerpDexs();
const summary = dexs
.filter(d => d !== null)
.map(dex => {
const assets = dex.assetToStreamingOiCap.map(([name, cap]) => ({
asset: name,
oiCap: parseFloat(cap)
}));
const totalCap = assets.reduce((sum, a) => sum + a.oiCap, 0);
const topAssets = assets
.sort((a, b) => b.oiCap - a.oiCap)
.slice(0, 3);
return {
name: dex.fullName,
assetCount: assets.length,
totalOiCap: totalCap,
topAssets: topAssets
};
})
.sort((a, b) => b.totalOiCap - a.totalOiCap);
console.log('=== OI Cap Summary (by total capacity) ===\n');
summary.forEach(dex => {
console.log(`${dex.name}: $${(dex.totalOiCap / 1e6).toFixed(0)}M total (${dex.assetCount} assets)`);
dex.topAssets.forEach(a => {
console.log(` ${a.asset}: $${(a.oiCap / 1e6).toFixed(0)}M`);
});
console.log('');
});
return summary;
}
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `400 Bad Request` | Invalid request format | Ensure valid JSON with `type` field |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Invalid request type",
"code": "INVALID_TYPE"
}
```
### Robust Error Handling
```javascript
async function safeGetPerpDexs(maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getPerpDexs();
} catch (error) {
if (error.response?.status === 429) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Filter null entries** — The response array may contain `null` values at certain indices
2. **Cache results** — DEX configurations change infrequently, cache for 5-15 minutes
3. **Parse asset names** — Asset names use the format `dexName:SYMBOL` (e.g., `"xyz:GOLD"`)
4. **Monitor fee changes** — Check `lastDeployerFeeScaleChangeTime` for recent fee updates
5. **Validate deployer addresses** — Verify deployer and fee recipient addresses when integrating
## Related Endpoints
- [**meta**](./meta) — Get core Hyperliquid trading pair metadata |
- [**spotMeta**](./spot-meta) — Get spot trading asset metadata |
- [**exchangeStatus**](./exchange-status) — Monitor exchange health and status |
- [**clearinghouseState**](./clearinghouse-state) — Get account state for a specific DEX |
---
*Discover perpetual DEXs on Hyperliquid with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## spotClearinghouseState - HyperCore Info Endpoint
# spotClearinghouseState
Get spot trading account state and token balances for a user 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 Endpoint
The `spotClearinghouseState` endpoint is essential for spot traders, portfolio managers, and trading platforms who need to:
- **Track Token Balances** — Monitor available and held balances across all tokens
- **Portfolio Management** — Calculate total portfolio value across spot holdings
- **Trading Validation** — Verify sufficient balance before placing spot orders
- **Liquidity Management** — Track which funds are locked in open orders
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"spotClearinghouseState"` |
| `user` | `string` | Yes | User's Ethereum wallet address |
### Example Request
```json
{
"type": "spotClearinghouseState",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}
```
## Response
### Success Response
```json
{
"balances": [
{
"coin": "USDC",
"token": 0,
"total": "0.01261784",
"hold": "0.0",
"entryNtl": "0.0"
},
{
"coin": "HYPE",
"token": 150,
"total": "0.00674734",
"hold": "0.0",
"entryNtl": "0.24186439"
}
]
}
```
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `balances` | `array` | Array of token balance objects |
#### Balance Object
| Field | Type | Description |
|-------|------|-------------|
| `coin` | `string` | Token symbol (e.g., "USDC", "HYPE", "ETH") |
| `token` | `integer` | Token index/ID |
| `total` | `string` | Total balance for this token |
| `hold` | `string` | Amount currently held in open spot orders |
| `entryNtl` | `string` | Entry notional value |
**Note:** Available balance = `total` - `hold`
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "spotClearinghouseState",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getSpotClearinghouseState(userAddress) {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'spotClearinghouseState',
user: userAddress
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const state = await getSpotClearinghouseState('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log(`Total balances: ${state.balances.length} tokens`);
// Display balances with available amounts
state.balances.forEach(balance => {
const total = parseFloat(balance.total);
const hold = parseFloat(balance.hold);
const available = total - hold;
console.log(`${balance.coin}:`);
console.log(` Total: ${balance.total}`);
console.log(` Available: ${available.toFixed(8)}`);
console.log(` On Hold: ${balance.hold}`);
});
// Find specific token
const usdcBalance = state.balances.find(b => b.coin === 'USDC');
if (usdcBalance) {
console.log(`USDC Balance: ${usdcBalance.total}`);
}
```
```python
from typing import Dict
from decimal import Decimal
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_spot_clearinghouse_state(user_address: str) -> Dict:
"""Get user's spot trading account state"""
response = requests.post(
ENDPOINT,
json={
'type': 'spotClearinghouseState',
'user': user_address
},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
state = get_spot_clearinghouse_state('0x63E8c7C149556D5f34F833419A287bb9Ef81487f')
print(f"Total balances: {len(state['balances'])} tokens\n")
# Display balances
for balance in state['balances']:
total = Decimal(balance['total'])
hold = Decimal(balance['hold'])
available = total - hold
print(f"{balance['coin']}:")
print(f" Total: {balance['total']}")
print(f" Available: {available}")
print(f" On Hold: {balance['hold']}")
print()
# Find tokens with non-zero balances
non_zero = [b for b in state['balances'] if Decimal(b['total']) > 0]
print(f"\nTokens with balance: {len(non_zero)}")
# Calculate tokens locked in orders
locked_tokens = [b for b in state['balances'] if Decimal(b['hold']) > 0]
print(f"Tokens with orders: {len(locked_tokens)}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type SpotClearinghouseRequest struct {
Type string `json:"type"`
User string `json:"user"`
}
type Balance struct {
Coin string `json:"coin"`
Total string `json:"total"`
Hold string `json:"hold"`
}
type SpotClearinghouseState struct {
Balances []Balance `json:"balances"`
}
func getSpotClearinghouseState(userAddress string) (*SpotClearinghouseState, error) {
reqBody, _ := json.Marshal(SpotClearinghouseRequest{
Type: "spotClearinghouseState",
User: userAddress,
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result SpotClearinghouseState
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
state, err := getSpotClearinghouseState("0x63E8c7C149556D5f34F833419A287bb9Ef81487f")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Total balances: %d tokens\n\n", len(state.Balances))
for _, balance := range state.Balances {
fmt.Printf("%s:\n", balance.Coin)
fmt.Printf(" Total: %s\n", balance.Total)
fmt.Printf(" On Hold: %s\n\n", balance.Hold)
}
}
```
## Common Use Cases
### 1. Check Available Balance
Calculate available balance for a specific token:
```javascript
async function getAvailableBalance(userAddress, token) {
const state = await getSpotClearinghouseState(userAddress);
const balance = state.balances.find(b => b.coin === token);
if (!balance) {
return {
token: token,
available: 0,
total: 0,
hold: 0,
exists: false
};
}
const total = parseFloat(balance.total);
const hold = parseFloat(balance.hold);
const available = total - hold;
return {
token: token,
available: available,
total: total,
hold: hold,
exists: true
};
}
// Usage
const usdcBalance = await getAvailableBalance(
'0x63E8c7C149556D5f34F833419A287bb9Ef81487f',
'USDC'
);
if (usdcBalance.available < 1000) {
console.log('Insufficient USDC balance for trade');
}
```
### 2. Portfolio Value Calculator
Calculate total portfolio value in USD:
```javascript
async function calculatePortfolioValue(userAddress, prices) {
const state = await getSpotClearinghouseState(userAddress);
let totalValue = 0;
const holdings = [];
state.balances.forEach(balance => {
const total = parseFloat(balance.total);
if (total === 0) return;
const price = prices[balance.coin] || 0;
const value = total * price;
totalValue += value;
holdings.push({
token: balance.coin,
amount: total,
price: price,
value: value,
percentage: 0 // Will calculate after
});
});
// Calculate percentages
holdings.forEach(h => {
h.percentage = (h.value / totalValue) * 100;
});
// Sort by value
holdings.sort((a, b) => b.value - a.value);
return {
totalValue: totalValue,
holdings: holdings,
tokenCount: holdings.length
};
}
// Usage with example prices
const prices = { USDC: 1, ETH: 2500, BTC: 45000 };
const portfolio = await calculatePortfolioValue(
'0x63E8c7C149556D5f34F833419A287bb9Ef81487f',
prices
);
console.log(`Total Portfolio Value: $${portfolio.totalValue.toFixed(2)}`);
portfolio.holdings.forEach(h => {
console.log(`${h.token}: $${h.value.toFixed(2)} (${h.percentage.toFixed(1)}%)`);
});
```
### 3. Validate Trade Feasibility
Check if user has sufficient balance for a trade:
```javascript
async function canExecuteTrade(userAddress, token, requiredAmount) {
const balance = await getAvailableBalance(userAddress, token);
if (!balance.exists) {
return {
canTrade: false,
reason: `No ${token} balance found`,
available: 0,
required: requiredAmount
};
}
if (balance.available < requiredAmount) {
return {
canTrade: false,
reason: 'Insufficient balance',
available: balance.available,
required: requiredAmount,
shortfall: requiredAmount - balance.available
};
}
return {
canTrade: true,
available: balance.available,
required: requiredAmount,
remaining: balance.available - requiredAmount
};
}
// Usage
const tradeCheck = await canExecuteTrade(
'0x63E8c7C149556D5f34F833419A287bb9Ef81487f',
'USDC',
1000
);
if (!tradeCheck.canTrade) {
console.error(`Cannot trade: ${tradeCheck.reason}`);
console.error(`Required: ${tradeCheck.required}, Available: ${tradeCheck.available}`);
}
```
### 4. Monitor Locked Balances
Track which tokens have funds locked in orders:
```javascript
async function getLockedBalances(userAddress) {
const state = await getSpotClearinghouseState(userAddress);
const lockedBalances = state.balances
.filter(b => parseFloat(b.hold) > 0)
.map(b => ({
token: b.coin,
total: parseFloat(b.total),
hold: parseFloat(b.hold),
available: parseFloat(b.total) - parseFloat(b.hold),
percentLocked: (parseFloat(b.hold) / parseFloat(b.total)) * 100
}));
return lockedBalances;
}
// Usage
const locked = await getLockedBalances('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log(`${locked.length} tokens with locked funds:\n`);
locked.forEach(l => {
console.log(`${l.token}:`);
console.log(` Locked: ${l.hold} (${l.percentLocked.toFixed(1)}%)`);
console.log(` Available: ${l.available}`);
});
```
### 5. Balance Summary Report
Generate a comprehensive balance report:
```javascript
async function getBalanceSummary(userAddress) {
const state = await getSpotClearinghouseState(userAddress);
console.log('\n=== Spot Balance Summary ===\n');
const nonZeroBalances = state.balances.filter(b => parseFloat(b.total) > 0);
const lockedBalances = state.balances.filter(b => parseFloat(b.hold) > 0);
console.log(`Total Tokens: ${nonZeroBalances.length}`);
console.log(`Tokens with Orders: ${lockedBalances.length}\n`);
console.log('Balances:');
nonZeroBalances.forEach(balance => {
const total = parseFloat(balance.total);
const hold = parseFloat(balance.hold);
const available = total - hold;
console.log(`\n${balance.coin}:`);
console.log(` Total: ${balance.total}`);
console.log(` Available: ${available.toFixed(8)}`);
if (hold > 0) {
console.log(` On Hold: ${balance.hold} ⚠️`);
}
});
}
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `400 Bad Request` | Missing or invalid user address | Ensure valid Ethereum address format |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Missing required parameter: user",
"code": "MISSING_PARAMETER"
}
```
### Robust Error Handling
```javascript
async function safeGetSpotClearinghouseState(userAddress, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getSpotClearinghouseState(userAddress);
} catch (error) {
if (error.response?.status === 429) {
// Rate limit - exponential backoff
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (error.response?.status === 400) {
throw new Error('Invalid user address');
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Poll responsibly** — Don't poll more frequently than needed (every 5-10 seconds for active trading)
2. **Handle zero balances** — Token may exist with zero balance
3. **Check available balance** — Always calculate `total - hold` before placing orders
4. **Validate addresses** — Ensure user addresses are valid Ethereum addresses
5. **Cache when appropriate** — Cache balance data briefly to reduce API calls
## Related Endpoints
- [**clearinghouseState**](./clearinghouse-state) — Get perpetual account state
- [**openOrders**](./open-orders) — See which orders are holding funds
- [**spotMeta**](./spot-meta) — Get spot trading asset metadata
- [**userFees**](./user-fees) — Get user fee rates for trading
---
*Access real-time Hyperliquid spot balances with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## spotMeta - HyperCore Info Endpoint
# spotMeta
Get metadata for all available spot trading assets on Hyperliquid, including token details, decimal precision, and trading pair information.
## When to Use This Endpoint
The `spotMeta` endpoint is essential for:
- **Spot Trading Interfaces** — Display available spot markets with correct token information
- **Token Discovery** — List all tradeable spot assets
- **Decimal Handling** — Format token amounts with correct precision
- **Token Validation** — Verify token addresses and canonical status
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"spotMeta"` |
### Example Request
```json
{
"type": "spotMeta"
}
```
## Response
### Success Response
```json
{
"universe": [
{
"tokens": [0, 1],
"name": "USDC/USDT"
}
],
"tokens": [
{
"name": "USDC",
"szDecimals": 8,
"weiDecimals": 8,
"index": 0,
"tokenId": "0x6d1e7cde53ba9467b783cb7c530ce054",
"isCanonical": true,
"fullName": "USD Coin"
},
{
"name": "USDT",
"szDecimals": 8,
"weiDecimals": 8,
"index": 1,
"tokenId": "0x4ed5f9b9547c4fbb52be8b24fcb5e8ba",
"isCanonical": true,
"fullName": "Tether USD"
}
]
}
```
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `universe` | `array` | Array of spot trading pair objects |
| `tokens` | `array` | Array of token metadata objects |
#### Token Object
| Field | Type | Description |
|-------|------|-------------|
| `name` | `string` | Token symbol (e.g., "USDC") |
| `szDecimals` | `integer` | Decimal places for size formatting |
| `weiDecimals` | `integer` | Decimal places for wei conversions |
| `index` | `integer` | Unique token index |
| `tokenId` | `string` | Unique token identifier |
| `isCanonical` | `boolean` | Whether the token is canonical |
| `fullName` | `string` | Full token name |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{"type":"spotMeta"}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getSpotMeta() {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ type: 'spotMeta' })
});
return await response.json();
}
// Usage
const spotMeta = await getSpotMeta();
console.log(`Available spot tokens: ${spotMeta.tokens.length}`);
console.log(`Available spot pairs: ${spotMeta.universe.length}`);
// Find specific token
const usdc = spotMeta.tokens.find(t => t.name === 'USDC');
console.log(`USDC decimals: ${usdc.szDecimals}`);
```
```python
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_spot_meta():
response = requests.post(
ENDPOINT,
json={'type': 'spotMeta'},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
spot_meta = get_spot_meta()
print(f"Available spot tokens: {len(spot_meta['tokens'])}")
# Find USDC
usdc = next(t for t in spot_meta['tokens'] if t['name'] == 'USDC')
print(f"USDC ID: {usdc['tokenId']}")
print(f"USDC canonical: {usdc['isCanonical']}")
```
## Common Use Cases
### 1. Format Token Amounts
```javascript
function formatTokenAmount(tokenName, amount, spotMeta) {
const token = spotMeta.tokens.find(t => t.name === tokenName);
if (!token) return amount.toString();
return amount.toFixed(token.szDecimals);
}
// Usage
const spotMeta = await getSpotMeta();
console.log(formatTokenAmount('USDC', 1000.123456, spotMeta)); // "1000.12345600"
```
### 2. Build Token Selector
```javascript
async function getTokenList() {
const spotMeta = await getSpotMeta();
return spotMeta.tokens
.filter(t => t.isCanonical)
.map(token => ({
symbol: token.name,
fullName: token.fullName,
tokenId: token.tokenId,
decimals: token.szDecimals
}));
}
```
### 3. Validate Token
```javascript
function isValidToken(tokenName, spotMeta) {
return spotMeta.tokens.some(t => t.name === tokenName);
}
```
## Best Practices
1. **Cache spot metadata** for extended periods as it changes infrequently
2. **Use correct decimals** when formatting token amounts
3. **Filter canonical tokens** when presenting token lists to users
4. **Validate tokens** before attempting trades
## Related Endpoints
- [**meta**](./meta) — Get perpetual trading pair metadata
- [**spotClearinghouseState**](./spot-clearinghouse-state) — Get spot account balances
---
*Access Hyperliquid spot market metadata with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## subAccounts - HyperCore Info Endpoint
# subAccounts
Get sub-account information for a user, including linked accounts, permissions, and relationship details.
## When to Use This Endpoint
The `subAccounts` endpoint is essential for:
- **Account Management** — View all sub-accounts linked to a main account
- **Permission Tracking** — Monitor sub-account permissions and access levels
- **Portfolio Organization** — Organize trading strategies across multiple accounts
- **Access Control** — Manage delegation and trading permissions
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"subAccounts"` |
| `user` | `string` | Yes | User's Ethereum wallet address |
### Example Request
```json
{
"type": "subAccounts",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}
```
## Response
### Success Response
Returns sub-account information for the specified user.
```json
{
"subAccounts": []
}
```
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `subAccounts` | `array` | Array of sub-account records with addresses and permissions |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "subAccounts",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getSubAccounts(userAddress) {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'subAccounts',
user: userAddress
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const accounts = await getSubAccounts('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log(`Total sub-accounts: ${accounts.subAccounts.length}`);
```
```python
from typing import Dict
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_sub_accounts(user_address: str) -> Dict:
"""Get user sub-account information"""
response = requests.post(
ENDPOINT,
json={
'type': 'subAccounts',
'user': user_address
},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
accounts = get_sub_accounts('0x63E8c7C149556D5f34F833419A287bb9Ef81487f')
print(f"Total sub-accounts: {len(accounts['subAccounts'])}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type SubAccountsRequest struct {
Type string `json:"type"`
User string `json:"user"`
}
type SubAccountsResponse struct {
SubAccounts []interface{} `json:"subAccounts"`
}
func getSubAccounts(userAddress string) (*SubAccountsResponse, error) {
reqBody, _ := json.Marshal(SubAccountsRequest{
Type: "subAccounts",
User: userAddress,
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result SubAccountsResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
accounts, err := getSubAccounts("0x63E8c7C149556D5f34F833419A287bb9Ef81487f")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Total sub-accounts: %d\n", len(accounts.SubAccounts))
}
```
## Common Use Cases
### 1. List All Sub-Accounts
Display all sub-accounts for a user:
```javascript
async function listSubAccounts(userAddress) {
const data = await getSubAccounts(userAddress);
console.log('=== Sub-Accounts ===\n');
console.log(`Total sub-accounts: ${data.subAccounts.length}`);
if (data.subAccounts.length === 0) {
console.log('No sub-accounts configured');
} else {
console.log('Sub-accounts are configured');
}
}
// Usage
await listSubAccounts('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
```
### 2. Check Account Structure
Verify account hierarchy:
```javascript
async function checkAccountStructure(userAddress) {
const data = await getSubAccounts(userAddress);
return {
mainAccount: userAddress,
subAccountCount: data.subAccounts.length,
hasSubAccounts: data.subAccounts.length > 0,
timestamp: new Date().toISOString()
};
}
// Usage
const structure = await checkAccountStructure('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log('Account structure:', structure);
```
### 3. Build Account Management Dashboard
Create a dashboard for account management:
```javascript
async function getAccountDashboard(userAddress) {
try {
const data = await getSubAccounts(userAddress);
return {
status: 'success',
mainAccount: userAddress,
subAccounts: data.subAccounts,
totalAccounts: 1 + data.subAccounts.length, // main + sub-accounts
lastUpdated: new Date().toISOString()
};
} catch (error) {
return {
status: 'error',
error: error.message
};
}
}
// Usage
const dashboard = await getAccountDashboard('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log('Account Dashboard:', dashboard);
```
### 4. Monitor Account Changes
Track sub-account additions or removals:
```javascript
class SubAccountMonitor {
constructor(userAddress) {
this.userAddress = userAddress;
this.lastKnownCount = null;
}
async checkForChanges() {
const data = await getSubAccounts(this.userAddress);
const currentCount = data.subAccounts.length;
if (this.lastKnownCount !== null) {
const change = currentCount - this.lastKnownCount;
if (change > 0) {
console.log(`${change} sub-account(s) added`);
} else if (change < 0) {
console.log(`${Math.abs(change)} sub-account(s) removed`);
}
}
this.lastKnownCount = currentCount;
return {
currentCount: currentCount,
changed: this.lastKnownCount !== null && currentCount !== this.lastKnownCount
};
}
}
// Usage
const monitor = new SubAccountMonitor('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
await monitor.checkForChanges();
```
### 5. Validate Sub-Account Access
Check if sub-accounts are properly configured:
```javascript
async function validateSubAccountAccess(userAddress) {
const data = await getSubAccounts(userAddress);
const validation = {
isConfigured: data.subAccounts.length > 0,
accountCount: data.subAccounts.length,
status: data.subAccounts.length > 0 ? 'configured' : 'unconfigured',
recommendation: data.subAccounts.length === 0
? 'Consider setting up sub-accounts for strategy separation'
: 'Sub-accounts are active'
};
console.log('Sub-Account Validation:', validation);
return validation;
}
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `400 Bad Request` | Missing or invalid user address | Ensure valid Ethereum address format |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Missing required parameter: user",
"code": "MISSING_PARAMETER"
}
```
### Robust Error Handling
```javascript
async function safeGetSubAccounts(userAddress, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getSubAccounts(userAddress);
} catch (error) {
if (error.response?.status === 429) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (error.response?.status === 400) {
throw new Error('Invalid user address');
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Validate addresses** — Ensure user addresses are valid Ethereum addresses
2. **Cache data** — Cache sub-account data for several minutes
3. **Handle empty states** — Account for users without sub-accounts
4. **Monitor changes** — Track sub-account additions/removals over time
5. **Organize strategies** — Use sub-accounts to separate different trading strategies
## Related Endpoints
- [**clearinghouseState**](./clearinghouse-state) — Get account state for each account
- [**openOrders**](./open-orders) — Get orders across accounts
- [**userFees**](./user-fees) — Get fee information
- [**extraAgents**](./extra-agents) — Get agent information
---
*Manage your Hyperliquid sub-accounts with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## userAbstraction - HyperCore Info Endpoint
# userAbstraction
Get the account abstraction mode for a user on Hyperliquid, indicating whether the account operates in unified, portfolio margin, or another mode.
## When to Use This Endpoint
The `userAbstraction` endpoint is essential for:
- **Account Mode Detection** — Determine how a user's account is configured
- **Margin Logic** — Adapt margin calculations based on unified vs portfolio margin mode
- **UI Customization** — Display the correct interface based on account abstraction type
- **Trading Logic** — Adjust order placement and risk management based on account mode
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"userAbstraction"` |
| `user` | `string` | Yes | User's Ethereum wallet address |
### Example Request
```json
{
"type": "userAbstraction",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}
```
## Response
### Success Response
Returns a string indicating the account abstraction mode for the specified user.
```json
"unifiedAccount"
```
### Possible Values
| Value | Description |
|-------|-------------|
| `unifiedAccount` | Unified account mode — perps and spot share a single margin pool |
| `portfolioMargin` | Portfolio margin mode — margin calculated across the full portfolio |
| `disabled` | Account abstraction is disabled |
| `default` | Default account mode |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "userAbstraction",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getUserAbstraction(userAddress) {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'userAbstraction',
user: userAddress
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const mode = await getUserAbstraction('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log(`Account abstraction mode: ${mode}`);
```
```python
from typing import str
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_user_abstraction(user_address: str) -> str:
"""Get user account abstraction mode"""
response = requests.post(
ENDPOINT,
json={
'type': 'userAbstraction',
'user': user_address
},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
mode = get_user_abstraction('0x63E8c7C149556D5f34F833419A287bb9Ef81487f')
print(f"Account abstraction mode: {mode}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type UserAbstractionRequest struct {
Type string `json:"type"`
User string `json:"user"`
}
func getUserAbstraction(userAddress string) (string, error) {
reqBody, _ := json.Marshal(UserAbstractionRequest{
Type: "userAbstraction",
User: userAddress,
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result string
if err := json.Unmarshal(body, &result); err != nil {
return "", err
}
return result, nil
}
func main() {
mode, err := getUserAbstraction("0x63E8c7C149556D5f34F833419A287bb9Ef81487f")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Account abstraction mode: %s\n", mode)
}
```
## Common Use Cases
### 1. Check Account Mode
Determine the account abstraction mode before executing trades:
```javascript
async function checkAccountMode(userAddress) {
const mode = await getUserAbstraction(userAddress);
console.log('=== Account Mode ===\n');
console.log(`Mode: ${mode}`);
return mode;
}
// Usage
const mode = await checkAccountMode('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
```
### 2. Adapt Trading Logic
Adjust trading behavior based on account mode:
```javascript
async function getTradeConfig(userAddress) {
const mode = await getUserAbstraction(userAddress);
const configs = {
unifiedAccount: {
marginShared: true,
spotAndPerpsLinked: true,
description: 'Perps and spot share a single margin pool'
},
portfolioMargin: {
marginShared: true,
spotAndPerpsLinked: true,
description: 'Margin calculated across the full portfolio'
},
disabled: {
marginShared: false,
spotAndPerpsLinked: false,
description: 'Standard isolated margin mode'
},
default: {
marginShared: false,
spotAndPerpsLinked: false,
description: 'Default account configuration'
}
};
return configs[mode] || configs['default'];
}
// Usage
const config = await getTradeConfig('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log(`Mode: ${config.description}`);
console.log(`Margin shared: ${config.marginShared}`);
```
### 3. Display Account Mode Badge
Show account mode in a dashboard:
```javascript
async function getAccountModeBadge(userAddress) {
const mode = await getUserAbstraction(userAddress);
const badges = {
unifiedAccount: { label: 'Unified Account', color: 'green' },
portfolioMargin: { label: 'Portfolio Margin', color: 'blue' },
disabled: { label: 'Standard', color: 'gray' },
default: { label: 'Default', color: 'gray' }
};
return badges[mode] || { label: mode, color: 'gray' };
}
// Usage
const badge = await getAccountModeBadge('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log(`Display badge: ${badge.label} (${badge.color})`);
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `400 Bad Request` | Missing or invalid user address | Ensure valid Ethereum address format |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Missing required parameter: user",
"code": "MISSING_PARAMETER"
}
```
### Robust Error Handling
```javascript
async function safeGetUserAbstraction(userAddress, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getUserAbstraction(userAddress);
} catch (error) {
if (error.response?.status === 429) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (error.response?.status === 400) {
throw new Error('Invalid user address');
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Cache mode data** — Account mode changes infrequently, cache for 5-10 minutes
2. **Validate addresses** — Ensure user addresses are valid Ethereum addresses
3. **Handle unknown modes** — Have fallback logic for unrecognized mode values
4. **Check before trading** — Query account mode before placing orders that depend on margin type
5. **Update on mode change** — Invalidate cached data when users switch account modes
## Related Endpoints
- [**clearinghouseState**](./clearinghouse-state) — Get perpetual account state
- [**spotClearinghouseState**](./spot-clearinghouse-state) — Get spot account balances
- [**userRole**](./user-role) — Get user role information
- [**subAccounts**](./sub-accounts) — Get sub-account details
---
*Check account abstraction modes with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## userFees - HyperCore Info Endpoint
# userFees
Get fee rates, volume information, and referral discounts for a user 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 Endpoint
The `userFees` endpoint is essential for traders, trading platforms, and analytics tools who need to:
- **Calculate Trading Costs** — Estimate fees before placing orders
- **Volume Tracking** — Monitor daily trading volume
- **Fee Optimization** — Compare user's fees against standard schedule
- **Referral Programs** — Track referral discounts and benefits
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"userFees"` |
| `user` | `string` | Yes | User's Ethereum wallet address |
### Example Request
```json
{
"type": "userFees",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}
```
## Response
### Success Response
```json
{
"dailyUserVlm": [
{
"date": "2026-02-07",
"userCross": "0.0",
"userAdd": "0.0",
"exchange": "6761946801.4399995804"
},
{
"date": "2026-02-08",
"userCross": "0.0",
"userAdd": "0.0",
"exchange": "3963888811.4499998093"
},
{
"date": "2026-02-09",
"userCross": "0.0",
"userAdd": "0.0",
"exchange": "2538522069.9000000954"
}
],
"feeSchedule": {
"cross": "0.00045",
"add": "0.00015",
"spotCross": "0.0007",
"spotAdd": "0.0004",
"tiers": {
"vip": [
{
"ntlCutoff": "5000000.0",
"cross": "0.0004",
"add": "0.00012",
"spotCross": "0.0006",
"spotAdd": "0.0003"
}
],
"mm": [
{
"makerFractionCutoff": "0.005",
"add": "-0.00001"
}
]
},
"referralDiscount": "0.04",
"stakingDiscountTiers": [
{
"bpsOfMaxSupply": "0.0",
"discount": "0.0"
},
{
"bpsOfMaxSupply": "0.0001",
"discount": "0.05"
}
]
},
"userCrossRate": "0.00045",
"userAddRate": "0.00015",
"userSpotCrossRate": "0.0007",
"userSpotAddRate": "0.0004",
"activeReferralDiscount": "0.04",
"trial": null,
"feeTrialEscrow": "0.0",
"nextTrialAvailableTimestamp": null,
"stakingLink": null,
"activeStakingDiscount": {
"bpsOfMaxSupply": "0.0",
"discount": "0.0"
}
}
```
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `dailyUserVlm` | `array` | Array of daily trading volume objects (last 15 days) |
| `feeSchedule` | `object` | Complete fee schedule with tiers and discounts |
| `userCrossRate` | `string` | User's current cross margin fee rate |
| `userAddRate` | `string` | User's current add liquidity fee rate |
| `userSpotCrossRate` | `string` | User's current spot cross margin fee rate |
| `userSpotAddRate` | `string` | User's current spot add liquidity fee rate |
| `activeReferralDiscount` | `string` | Active referral discount (decimal, e.g., "0.04" = 4%) |
| `trial` | `null \| object` | Fee trial information if active |
| `feeTrialEscrow` | `string` | Amount in escrow for fee trial |
| `nextTrialAvailableTimestamp` | `null \| integer` | Timestamp when next trial becomes available |
| `stakingLink` | `null \| string` | Staking link if applicable |
| `activeStakingDiscount` | `object` | Current staking discount tier |
#### Daily Volume Object
| Field | Type | Description |
|-------|------|-------------|
| `date` | `string` | Date in YYYY-MM-DD format |
| `userCross` | `string` | User's cross margin trading volume for the day |
| `userAdd` | `string` | User's add liquidity volume for the day |
| `exchange` | `string` | Total exchange volume for the day |
#### Fee Schedule Object
| Field | Type | Description |
|-------|------|-------------|
| `cross` | `string` | Base cross margin fee rate |
| `add` | `string` | Base add liquidity fee rate |
| `spotCross` | `string` | Base spot cross margin fee rate |
| `spotAdd` | `string` | Base spot add liquidity fee rate |
| `tiers` | `object` | VIP and market maker tier structures |
| `referralDiscount` | `string` | Standard referral discount percentage |
| `stakingDiscountTiers` | `array` | Array of staking discount tier objects |
#### VIP Tier Object
| Field | Type | Description |
|-------|------|-------------|
| `ntlCutoff` | `string` | Notional volume cutoff for this tier |
| `cross` | `string` | Cross margin fee rate at this tier |
| `add` | `string` | Add liquidity fee rate at this tier |
| `spotCross` | `string` | Spot cross margin fee rate at this tier |
| `spotAdd` | `string` | Spot add liquidity fee rate at this tier |
#### Market Maker Tier Object
| Field | Type | Description |
|-------|------|-------------|
| `makerFractionCutoff` | `string` | Maker fraction cutoff for this tier |
| `add` | `string` | Add liquidity rebate (negative = rebate) |
#### Staking Discount Tier Object
| Field | Type | Description |
|-------|------|-------------|
| `bpsOfMaxSupply` | `string` | Basis points of max supply staked |
| `discount` | `string` | Fee discount percentage at this tier |
**Note:** Fee rates are expressed as decimals (e.g., "0.00045" = 0.045% or 4.5 basis points)
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "userFees",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getUserFees(userAddress) {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'userFees',
user: userAddress
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const fees = await getUserFees('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
// Convert to basis points for readability
const crossRateBps = parseFloat(fees.userCrossRate) * 10000;
const addRateBps = parseFloat(fees.userAddRate) * 10000;
console.log(`Cross Margin Rate: ${crossRateBps} bps`);
console.log(`Add Liquidity Rate: ${addRateBps} bps`);
console.log(`Spot Cross Rate: ${parseFloat(fees.userSpotCrossRate) * 10000} bps`);
console.log(`Spot Add Rate: ${parseFloat(fees.userSpotAddRate) * 10000} bps`);
if (parseFloat(fees.activeReferralDiscount) > 0) {
console.log(`Active Referral Discount: ${parseFloat(fees.activeReferralDiscount) * 100}%`);
console.log(`Referral Discount: ${(parseFloat(fees.referralDiscount) * 100).toFixed(1)}%`);
}
```
```python
from typing import Dict
from decimal import Decimal
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_user_fees(user_address: str) -> Dict:
"""Get user's fee rates and volume information"""
response = requests.post(
ENDPOINT,
json={
'type': 'userFees',
'user': user_address
},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
fees = get_user_fees('0x63E8c7C149556D5f34F833419A287bb9Ef81487f')
# Convert to basis points
cross_rate = Decimal(fees['userCrossRate'])
add_rate = Decimal(fees['userAddRate'])
spot_cross_rate = Decimal(fees['userSpotCrossRate'])
spot_add_rate = Decimal(fees['userSpotAddRate'])
print(f"Cross Margin Rate: {cross_rate * 10000} bps")
print(f"Add Liquidity Rate: {add_rate * 10000} bps")
print(f"Spot Cross Rate: {spot_cross_rate * 10000} bps")
print(f"Spot Add Rate: {spot_add_rate * 10000} bps")
# Check discounts
if Decimal(fees['activeReferralDiscount']) > 0:
print(f"Active Referral Discount: {Decimal(fees['activeReferralDiscount']) * 100}%")
if Decimal(fees['activeStakingDiscount']['discount']) > 0:
print(f"Active Staking Discount: {Decimal(fees['activeStakingDiscount']['discount']) * 100}%")
# Volume history
print(f"\nDaily Volume Records: {len(fees['dailyUserVlm'])}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type UserFeesRequest struct {
Type string `json:"type"`
User string `json:"user"`
}
type UserRates struct {
UserCrossRate string `json:"userCrossRate"`
UserAddRate string `json:"userAddRate"`
}
type UserFees struct {
UserRates UserRates `json:"userRates"`
DailyUserVlm []interface{} `json:"dailyUserVlm"`
FeeSchedule map[string]interface{} `json:"feeSchedule"`
ReferralDiscount string `json:"referralDiscount"`
}
func getUserFees(userAddress string) (*UserFees, error) {
reqBody, _ := json.Marshal(UserFeesRequest{
Type: "userFees",
User: userAddress,
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result UserFees
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func rateToBps(rate string) float64 {
r, _ := strconv.ParseFloat(rate, 64)
return r * 10000
}
func main() {
fees, err := getUserFees("0x63E8c7C149556D5f34F833419A287bb9Ef81487f")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
crossBps := rateToBps(fees.UserRates.UserCrossRate)
addBps := rateToBps(fees.UserRates.UserAddRate)
fmt.Printf("Cross Margin Rate: %.1f bps (%s)\n", crossBps, fees.UserRates.UserCrossRate)
fmt.Printf("Add Liquidity Rate: %.1f bps (%s)\n", addBps, fees.UserRates.UserAddRate)
discount, _ := strconv.ParseFloat(fees.ReferralDiscount, 64)
if discount > 0 {
fmt.Printf("Referral Discount: %.1f%%\n", discount*100)
}
fmt.Printf("\nDaily Volume Records: %d\n", len(fees.DailyUserVlm))
}
```
## Common Use Cases
### 1. Calculate Trading Costs
Estimate fees for a trade:
```javascript
async function calculateTradingFee(userAddress, orderValue, isMaker = false) {
const fees = await getUserFees(userAddress);
// Use cross rate for taker, add rate for maker
const feeRate = isMaker
? parseFloat(fees.userRates.userAddRate)
: parseFloat(fees.userRates.userCrossRate);
// Apply referral discount if available
const discount = parseFloat(fees.referralDiscount);
const effectiveRate = feeRate * (1 - discount);
const feeAmount = orderValue * effectiveRate;
return {
orderValue: orderValue,
feeRate: feeRate,
discount: discount,
effectiveRate: effectiveRate,
feeAmount: feeAmount,
feeBps: effectiveRate * 10000
};
}
// Usage
const tradeFee = await calculateTradingFee(
'0x63E8c7C149556D5f34F833419A287bb9Ef81487f',
10000, // $10,000 order
true // maker order
);
console.log(`Order Value: $${tradeFee.orderValue}`);
console.log(`Fee Rate: ${tradeFee.feeBps.toFixed(2)} bps`);
console.log(`Estimated Fee: $${tradeFee.feeAmount.toFixed(2)}`);
```
### 2. Compare Against Standard Fees
Compare user's fees to standard rates:
```javascript
async function compareFeeRates(userAddress, standardRate = 0.0005) {
const fees = await getUserFees(userAddress);
const userRate = parseFloat(fees.userRates.userCrossRate);
const savingsBps = (standardRate - userRate) * 10000;
const savingsPercent = ((standardRate - userRate) / standardRate) * 100;
return {
userRate: userRate,
standardRate: standardRate,
savingsBps: savingsBps,
savingsPercent: savingsPercent,
hasBetterRate: userRate < standardRate
};
}
// Usage
const comparison = await compareFeeRates(
'0x63E8c7C149556D5f34F833419A287bb9Ef81487f',
0.0005 // 5 bps standard
);
if (comparison.hasBetterRate) {
console.log(`You save ${comparison.savingsBps.toFixed(2)} bps (${comparison.savingsPercent.toFixed(1)}%)`);
}
```
### 3. Estimate Monthly Fee Savings
Calculate potential savings with referral discount:
```javascript
async function estimateMonthlySavings(userAddress, monthlyVolume) {
const fees = await getUserFees(userAddress);
const baseRate = parseFloat(fees.userRates.userCrossRate);
const discount = parseFloat(fees.referralDiscount);
const baseFees = monthlyVolume * baseRate;
const discountedFees = baseFees * (1 - discount);
const savings = baseFees - discountedFees;
return {
monthlyVolume: monthlyVolume,
baseRate: baseRate,
discount: discount,
baseFees: baseFees,
discountedFees: discountedFees,
savings: savings,
savingsPercent: discount * 100
};
}
// Usage
const savings = await estimateMonthlySavings(
'0x63E8c7C149556D5f34F833419A287bb9Ef81487f',
1000000 // $1M monthly volume
);
console.log(`Monthly Volume: $${savings.monthlyVolume.toLocaleString()}`);
console.log(`Base Fees: $${savings.baseFees.toFixed(2)}`);
console.log(`With Discount: $${savings.discountedFees.toFixed(2)}`);
console.log(`Monthly Savings: $${savings.savings.toFixed(2)}`);
```
### 4. Fee Tier Analyzer
Analyze user's fee tier and potential improvements:
```javascript
async function analyzeFeePosition(userAddress) {
const fees = await getUserFees(userAddress);
const crossRate = parseFloat(fees.userRates.userCrossRate);
const addRate = parseFloat(fees.userRates.userAddRate);
const discount = parseFloat(fees.referralDiscount);
// Example tier thresholds (adjust based on actual schedule)
const tiers = [
{ name: 'Standard', rate: 0.0005, minVolume: 0 },
{ name: 'Tier 1', rate: 0.0004, minVolume: 100000 },
{ name: 'Tier 2', rate: 0.0003, minVolume: 500000 },
{ name: 'Tier 3', rate: 0.0002, minVolume: 2000000 },
];
const currentTier = tiers.findLast(t => t.rate >= crossRate) || tiers[0];
const nextTier = tiers[tiers.indexOf(currentTier) + 1];
console.log('=== Fee Analysis ===\n');
console.log(`Current Cross Rate: ${(crossRate * 10000).toFixed(2)} bps`);
console.log(`Current Add Rate: ${(addRate * 10000).toFixed(2)} bps`);
console.log(`Estimated Tier: ${currentTier.name}`);
if (discount > 0) {
console.log(`Referral Discount: ${(discount * 100).toFixed(1)}%`);
}
if (nextTier) {
const improvement = ((crossRate - nextTier.rate) / crossRate) * 100;
console.log(`\nNext tier saves ${improvement.toFixed(1)}% on fees`);
console.log(`Requires ~$${nextTier.minVolume.toLocaleString()} monthly volume`);
}
}
```
### 5. Fee Comparison Tool
Compare fees across different order types:
```javascript
async function compareFeeTypes(userAddress, orderValue) {
const fees = await getUserFees(userAddress);
const makerRate = parseFloat(fees.userRates.userAddRate);
const takerRate = parseFloat(fees.userRates.userCrossRate);
const discount = parseFloat(fees.referralDiscount);
const makerFee = orderValue * makerRate * (1 - discount);
const takerFee = orderValue * takerRate * (1 - discount);
console.log(`Order Value: $${orderValue.toLocaleString()}\n`);
console.log('Maker Order (limit):');
console.log(` Rate: ${(makerRate * 10000).toFixed(2)} bps`);
console.log(` Fee: $${makerFee.toFixed(2)}`);
console.log('\nTaker Order (market):');
console.log(` Rate: ${(takerRate * 10000).toFixed(2)} bps`);
console.log(` Fee: $${takerFee.toFixed(2)}`);
console.log(`\nSavings with maker: $${(takerFee - makerFee).toFixed(2)}`);
}
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `400 Bad Request` | Missing or invalid user address | Ensure valid Ethereum address format |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Missing required parameter: user",
"code": "MISSING_PARAMETER"
}
```
### Robust Error Handling
```javascript
async function safeGetUserFees(userAddress, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getUserFees(userAddress);
} catch (error) {
if (error.response?.status === 429) {
// Rate limit - exponential backoff
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (error.response?.status === 400) {
throw new Error('Invalid user address');
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Cache fee data** — Fee rates change infrequently, cache for several minutes
2. **Always use effective rate** — Apply referral discount when calculating costs
3. **Display fees clearly** — Show both basis points and dollar amounts
4. **Validate addresses** — Ensure user addresses are valid Ethereum addresses
5. **Consider order type** — Use correct rate for maker vs taker orders
## Related Endpoints
- [**clearinghouseState**](./clearinghouse-state) — Get account state and trading volume
- [**openOrders**](./open-orders) — See orders that will incur fees
- [**meta**](./meta) — Get trading pair metadata
- [**spotClearinghouseState**](./spot-clearinghouse-state) — Get spot trading balances
---
*Access real-time Hyperliquid fee information with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## userRateLimit - HyperCore Info Endpoint
# userRateLimit
Get rate limit information for a user on Hyperliquid, including current usage and remaining capacity.
## When to Use This Endpoint
The `userRateLimit` endpoint is essential for:
- **Usage Monitoring** — Track API usage against rate limits
- **Optimization** — Identify when to throttle requests
- **Compliance** — Ensure requests stay within allowed limits
- **Planning** — Understand user-specific rate limit allocations
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"userRateLimit"` |
| `user` | `string` | Yes | User's Ethereum wallet address |
### Example Request
```json
{
"type": "userRateLimit",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}
```
## Response
### Success Response
Returns rate limit information for the specified user.
```json
{
"limit": 100,
"remaining": 95,
"reset": 1704067200000
}
```
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `limit` | `integer` | Maximum number of requests allowed |
| `remaining` | `integer` | Number of requests remaining in current period |
| `reset` | `integer` | Unix timestamp (milliseconds) when rate limit resets |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "userRateLimit",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getUserRateLimit(userAddress) {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'userRateLimit',
user: userAddress
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const rateLimit = await getUserRateLimit('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log(`Remaining: ${rateLimit.remaining}/${rateLimit.limit}`);
console.log(`Resets: ${new Date(rateLimit.reset).toISOString()}`);
```
```python
from datetime import datetime
from typing import Dict
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_user_rate_limit(user_address: str) -> Dict:
"""Get user rate limit information"""
response = requests.post(
ENDPOINT,
json={
'type': 'userRateLimit',
'user': user_address
},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
rate_limit = get_user_rate_limit('0x63E8c7C149556D5f34F833419A287bb9Ef81487f')
print(f"Remaining: {rate_limit['remaining']}/{rate_limit['limit']}")
reset_time = datetime.fromtimestamp(rate_limit['reset'] / 1000)
print(f"Resets: {reset_time.isoformat()}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type UserRateLimitRequest struct {
Type string `json:"type"`
User string `json:"user"`
}
type UserRateLimitResponse struct {
Limit int `json:"limit"`
Remaining int `json:"remaining"`
Reset int64 `json:"reset"`
}
func getUserRateLimit(userAddress string) (*UserRateLimitResponse, error) {
reqBody, _ := json.Marshal(UserRateLimitRequest{
Type: "userRateLimit",
User: userAddress,
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result UserRateLimitResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
rateLimit, err := getUserRateLimit("0x63E8c7C149556D5f34F833419A287bb9Ef81487f")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Remaining: %d/%d\n", rateLimit.Remaining, rateLimit.Limit)
resetTime := time.Unix(rateLimit.Reset/1000, 0)
fmt.Printf("Resets: %s\n", resetTime.Format(time.RFC3339))
}
```
## Common Use Cases
### 1. Check Rate Limit Status
Monitor current rate limit status:
```javascript
async function checkRateLimitStatus(userAddress) {
const rateLimit = await getUserRateLimit(userAddress);
const percentUsed = ((rateLimit.limit - rateLimit.remaining) / rateLimit.limit) * 100;
const resetDate = new Date(rateLimit.reset);
console.log('=== Rate Limit Status ===\n');
console.log(`Limit: ${rateLimit.limit} requests`);
console.log(`Remaining: ${rateLimit.remaining} (${percentUsed.toFixed(1)}% used)`);
console.log(`Resets: ${resetDate.toISOString()}`);
if (rateLimit.remaining < 10) {
console.warn('WARNING: Approaching rate limit!');
}
}
```
### 2. Implement Smart Throttling
Automatically throttle requests based on remaining capacity:
```javascript
class RateLimitedClient {
constructor(userAddress) {
this.userAddress = userAddress;
this.lastCheck = null;
}
async shouldThrottle() {
const rateLimit = await getUserRateLimit(this.userAddress);
this.lastCheck = Date.now();
// Throttle if less than 20% remaining
const remainingPercent = (rateLimit.remaining / rateLimit.limit) * 100;
return remainingPercent < 20;
}
async makeRequest(requestFn) {
if (await this.shouldThrottle()) {
const rateLimit = await getUserRateLimit(this.userAddress);
const waitTime = rateLimit.reset - Date.now();
console.log(`Throttling: waiting ${waitTime}ms`);
await new Promise(r => setTimeout(r, waitTime));
}
return await requestFn();
}
}
// Usage
const client = new RateLimitedClient('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
const result = await client.makeRequest(() => someApiCall());
```
### 3. Build Rate Limit Monitor
Create a monitoring system:
```javascript
async function monitorRateLimit(userAddress, alertThreshold = 10) {
const rateLimit = await getUserRateLimit(userAddress);
const status = {
limit: rateLimit.limit,
remaining: rateLimit.remaining,
used: rateLimit.limit - rateLimit.remaining,
percentUsed: ((rateLimit.limit - rateLimit.remaining) / rateLimit.limit) * 100,
resetTime: new Date(rateLimit.reset),
timeUntilReset: rateLimit.reset - Date.now()
};
if (status.remaining <= alertThreshold) {
console.error(`ALERT: Only ${status.remaining} requests remaining!`);
console.log(`Resets in ${Math.ceil(status.timeUntilReset / 1000)}s`);
}
return status;
}
// Usage
const status = await monitorRateLimit('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log('Rate limit status:', status);
```
### 4. Calculate Optimal Request Rate
Calculate safe request rate:
```javascript
async function calculateOptimalRate(userAddress) {
const rateLimit = await getUserRateLimit(userAddress);
const timeUntilReset = rateLimit.reset - Date.now();
const secondsUntilReset = timeUntilReset / 1000;
// Calculate requests per second to use remaining capacity
const optimalRPS = rateLimit.remaining / secondsUntilReset;
// Add 20% buffer for safety
const safeRPS = optimalRPS * 0.8;
return {
remaining: rateLimit.remaining,
timeUntilReset: secondsUntilReset,
optimalRPS: optimalRPS,
safeRPS: safeRPS,
delayBetweenRequests: 1000 / safeRPS // milliseconds
};
}
// Usage
const optimal = await calculateOptimalRate('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log(`Safe request rate: ${optimal.safeRPS.toFixed(2)} req/s`);
console.log(`Delay between requests: ${optimal.delayBetweenRequests.toFixed(0)}ms`);
```
### 5. Rate Limit Dashboard
Create a comprehensive rate limit dashboard:
```javascript
async function getRateLimitDashboard(userAddress) {
try {
const rateLimit = await getUserRateLimit(userAddress);
const now = Date.now();
const percentUsed = ((rateLimit.limit - rateLimit.remaining) / rateLimit.limit) * 100;
const timeUntilReset = rateLimit.reset - now;
return {
status: 'success',
metrics: {
limit: rateLimit.limit,
used: rateLimit.limit - rateLimit.remaining,
remaining: rateLimit.remaining,
percentUsed: percentUsed.toFixed(1) + '%',
resetTime: new Date(rateLimit.reset).toISOString(),
resetIn: `${Math.ceil(timeUntilReset / 1000)}s`
},
health: percentUsed < 80 ? 'healthy' : percentUsed < 95 ? 'warning' : 'critical'
};
} catch (error) {
return {
status: 'error',
error: error.message
};
}
}
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `400 Bad Request` | Missing or invalid user address | Ensure valid Ethereum address format |
| `429 Too Many Requests` | Rate limit exceeded | Wait for reset time |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Missing required parameter: user",
"code": "MISSING_PARAMETER"
}
```
### Robust Error Handling
```javascript
async function safeGetUserRateLimit(userAddress, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getUserRateLimit(userAddress);
} catch (error) {
if (error.response?.status === 429) {
// Already rate limited - wait longer
await new Promise(r => setTimeout(r, Math.pow(2, i + 1) * 1000));
} else if (error.response?.status === 400) {
throw new Error('Invalid user address');
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Check regularly** — Monitor rate limits before making bulk requests
2. **Respect limits** — Implement throttling when approaching limits
3. **Cache strategically** — Cache rate limit data for 10-30 seconds
4. **Plan ahead** — Check limits before starting long-running operations
5. **Implement backoff** — Use exponential backoff when limits are reached
## Related Endpoints
- [**clearinghouseState**](./clearinghouse-state) — Get account state
- [**userFees**](./user-fees) — Get user fee information
- [**openOrders**](./open-orders) — Get user open orders
---
*Monitor and optimize your Hyperliquid API usage with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## userRole - HyperCore Info Endpoint
# userRole
Get role information for a user on Hyperliquid, including permissions, access levels, and account capabilities.
## When to Use This Endpoint
The `userRole` endpoint is essential for:
- **Permission Checking** — Verify user access levels and capabilities
- **Access Control** — Implement role-based access in applications
- **Feature Gating** — Enable/disable features based on user role
- **Account Management** — Understand account type and permissions
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"userRole"` |
| `user` | `string` | Yes | User's Ethereum wallet address |
### Example Request
```json
{
"type": "userRole",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}
```
## Response
### Success Response
Returns role information for the specified user.
```json
{
"role": "standard"
}
```
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `role` | `string` | User's role on the platform (e.g., "standard", "vip", "market_maker") |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "userRole",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getUserRole(userAddress) {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'userRole',
user: userAddress
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const roleData = await getUserRole('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log(`User role: ${roleData.role}`);
```
```python
from typing import Dict
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_user_role(user_address: str) -> Dict:
"""Get user role information"""
response = requests.post(
ENDPOINT,
json={
'type': 'userRole',
'user': user_address
},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
role_data = get_user_role('0x63E8c7C149556D5f34F833419A287bb9Ef81487f')
print(f"User role: {role_data['role']}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type UserRoleRequest struct {
Type string `json:"type"`
User string `json:"user"`
}
type UserRoleResponse struct {
Role string `json:"role"`
}
func getUserRole(userAddress string) (*UserRoleResponse, error) {
reqBody, _ := json.Marshal(UserRoleRequest{
Type: "userRole",
User: userAddress,
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result UserRoleResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
roleData, err := getUserRole("0x63E8c7C149556D5f34F833419A287bb9Ef81487f")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("User role: %s\n", roleData.Role)
}
```
## Common Use Cases
### 1. Check User Permissions
Verify user role for access control:
```javascript
async function checkUserPermissions(userAddress) {
const roleData = await getUserRole(userAddress);
console.log('=== User Permissions ===\n');
console.log(`Role: ${roleData.role}`);
return roleData.role;
}
// Usage
const role = await checkUserPermissions('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
```
### 2. Role-Based Feature Access
Implement role-based feature gating:
```javascript
async function canAccessFeature(userAddress, featureName) {
const roleData = await getUserRole(userAddress);
// Define feature access by role
const featureAccess = {
standard: ['basic_trading', 'view_data'],
vip: ['basic_trading', 'view_data', 'advanced_analytics', 'priority_support'],
market_maker: ['basic_trading', 'view_data', 'advanced_analytics', 'market_making', 'api_access']
};
const userFeatures = featureAccess[roleData.role] || [];
const hasAccess = userFeatures.includes(featureName);
console.log(`Feature "${featureName}": ${hasAccess ? 'Granted' : 'Denied'}`);
return hasAccess;
}
// Usage
const canUseAdvancedAnalytics = await canAccessFeature(
'0x63E8c7C149556D5f34F833419A287bb9Ef81487f',
'advanced_analytics'
);
```
### 3. Display Role Badge
Show user role in UI:
```javascript
async function getUserRoleBadge(userAddress) {
const roleData = await getUserRole(userAddress);
const badges = {
standard: { label: 'Standard', color: 'gray' },
vip: { label: 'VIP', color: 'gold' },
market_maker: { label: 'Market Maker', color: 'blue' }
};
return badges[roleData.role] || { label: 'User', color: 'gray' };
}
// Usage
const badge = await getUserRoleBadge('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log(`Display badge: ${badge.label} (${badge.color})`);
```
### 4. Build Access Control System
Create comprehensive access control:
```javascript
class AccessControl {
constructor(userAddress) {
this.userAddress = userAddress;
this.role = null;
}
async initialize() {
const roleData = await getUserRole(this.userAddress);
this.role = roleData.role;
return this.role;
}
hasPermission(permission) {
const permissions = {
standard: ['read', 'basic_trade'],
vip: ['read', 'basic_trade', 'advanced_trade', 'analytics'],
market_maker: ['read', 'basic_trade', 'advanced_trade', 'analytics', 'market_make', 'api']
};
const userPermissions = permissions[this.role] || [];
return userPermissions.includes(permission);
}
getPermissions() {
const permissions = {
standard: ['read', 'basic_trade'],
vip: ['read', 'basic_trade', 'advanced_trade', 'analytics'],
market_maker: ['read', 'basic_trade', 'advanced_trade', 'analytics', 'market_make', 'api']
};
return permissions[this.role] || [];
}
}
// Usage
const acl = new AccessControl('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
await acl.initialize();
if (acl.hasPermission('advanced_trade')) {
console.log('User can access advanced trading');
}
```
### 5. Role-Based Dashboard
Customize dashboard based on user role:
```javascript
async function buildRoleBasedDashboard(userAddress) {
const roleData = await getUserRole(userAddress);
const dashboardConfig = {
standard: {
widgets: ['account_summary', 'basic_charts', 'order_book'],
features: ['basic_trading']
},
vip: {
widgets: ['account_summary', 'advanced_charts', 'order_book', 'analytics'],
features: ['basic_trading', 'advanced_trading', 'analytics']
},
market_maker: {
widgets: ['account_summary', 'advanced_charts', 'order_book', 'analytics', 'api_stats'],
features: ['basic_trading', 'advanced_trading', 'analytics', 'market_making', 'api_access']
}
};
const config = dashboardConfig[roleData.role] || dashboardConfig.standard;
return {
role: roleData.role,
dashboard: config,
timestamp: new Date().toISOString()
};
}
// Usage
const dashboard = await buildRoleBasedDashboard('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log('Dashboard configuration:', dashboard);
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `400 Bad Request` | Missing or invalid user address | Ensure valid Ethereum address format |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Missing required parameter: user",
"code": "MISSING_PARAMETER"
}
```
### Robust Error Handling
```javascript
async function safeGetUserRole(userAddress, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getUserRole(userAddress);
} catch (error) {
if (error.response?.status === 429) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (error.response?.status === 400) {
throw new Error('Invalid user address');
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Cache role data** — Role changes infrequently, cache for 5-10 minutes
2. **Validate addresses** — Ensure user addresses are valid Ethereum addresses
3. **Default to least privilege** — Use most restrictive role as default
4. **Handle unknown roles** — Have fallback for unrecognized roles
5. **Implement feature flags** — Combine with feature flags for flexible access control
## Performance Tips
### Cached Role Checker
```javascript
class CachedRoleChecker {
constructor(cacheDurationMs = 300000) {
this.cache = new Map();
this.cacheDurationMs = cacheDurationMs; // 5 minutes
}
async getRole(userAddress) {
const cached = this.cache.get(userAddress);
const now = Date.now();
if (cached && (now - cached.timestamp) < this.cacheDurationMs) {
return cached.role;
}
const roleData = await getUserRole(userAddress);
this.cache.set(userAddress, {
role: roleData.role,
timestamp: now
});
return roleData.role;
}
invalidate(userAddress) {
this.cache.delete(userAddress);
}
clearAll() {
this.cache.clear();
}
}
// Usage
const roleChecker = new CachedRoleChecker();
const role = await roleChecker.getRole('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
```
## Related Endpoints
- [**extraAgents**](./extra-agents) — Get agent information
- [**subAccounts**](./sub-accounts) — Get sub-account details
- [**clearinghouseState**](./clearinghouse-state) — Get account state
- [**userFees**](./user-fees) — Get fee information (may vary by role)
---
*Implement role-based access control with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## userVaultEquities - HyperCore Info Endpoint
# userVaultEquities
Get user's equity positions across all vaults, including share balances, current value, unrealized gains, and allocation details.
> **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 Endpoint
The `userVaultEquities` endpoint is essential for portfolio trackers, wealth managers, and investors who need to:
- **Track Vault Investments** — Monitor all vault positions in one place
- **Calculate Portfolio Value** — Get real-time value of vault holdings
- **Analyze Performance** — Track unrealized gains/losses across vaults
- **Portfolio Management** — View vault allocation and diversification
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"userVaultEquities"` |
| `user` | `string` | Yes | User's Ethereum wallet address |
### Example Request
```json
{
"type": "userVaultEquities",
"user": "0x66e7293b07744b2d92384d33a0f86b9c333d8597"
}
```
## Response
### Success Response
```json
[
{
"vaultAddress": "0x115849ce84370f25cadcf0d348510d73837e1aa5",
"equity": "9773.685144",
"lockedUntilTimestamp": 1770368683304
}
]
```
### Response Fields
The response is an array of vault equity objects. Each object contains:
| Field | Type | Description |
|-------|------|-------------|
| `vaultAddress` | `string` | Ethereum address of the vault contract |
| `equity` | `string` | User's current equity value in the vault (USD) |
| `lockedUntilTimestamp` | `integer` | Unix timestamp (milliseconds) when vault funds unlock |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "userVaultEquities",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getUserVaultEquities(userAddress) {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'userVaultEquities',
user: userAddress
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const equities = await getUserVaultEquities('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log(`Active vault positions: ${equities.length}`);
// Calculate portfolio metrics
const totalValue = equities.reduce((sum, e) => sum + parseFloat(e.currentValue), 0);
const totalPnl = equities.reduce((sum, e) => sum + parseFloat(e.unrealizedPnl), 0);
const totalDeposits = equities.reduce((sum, e) => sum + parseFloat(e.netDeposits), 0);
console.log(`\nPortfolio Summary:`);
console.log(`Total Value: $${totalValue.toLocaleString()}`);
console.log(`Total PnL: $${totalPnl.toLocaleString()}`);
console.log(`Total Return: ${((totalPnl / totalDeposits) * 100).toFixed(2)}%`);
// List positions
console.log(`\nVault Positions:`);
equities.forEach(e => {
console.log(`\n${e.vaultName}:`);
console.log(` Shares: ${e.shares}`);
console.log(` Value: $${parseFloat(e.currentValue).toLocaleString()}`);
console.log(` PnL: $${e.unrealizedPnl} (${e.pnlPercent}%)`);
});
```
```python
from typing import List, Dict
from datetime import datetime
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_user_vault_equities(user_address: str) -> List[Dict]:
"""Get user's vault equity positions"""
response = requests.post(
ENDPOINT,
json={
'type': 'userVaultEquities',
'user': user_address
},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
equities = get_user_vault_equities('0x63E8c7C149556D5f34F833419A287bb9Ef81487f')
print(f"Active vault positions: {len(equities)}\n")
# Calculate portfolio metrics
total_value = sum(float(e['currentValue']) for e in equities)
total_pnl = sum(float(e['unrealizedPnl']) for e in equities)
total_deposits = sum(float(e['netDeposits']) for e in equities)
print("=== Portfolio Summary ===")
print(f"Total Value: ${total_value:,.2f}")
print(f"Total PnL: ${total_pnl:,.2f}")
print(f"Total Return: {(total_pnl / total_deposits * 100):.2f}%")
print("\n=== Vault Positions ===")
for equity in equities:
print(f"\n{equity['vaultName']}:")
print(f" Shares: {equity['shares']}")
print(f" Value: ${float(equity['currentValue']):,.2f}")
print(f" PnL: ${equity['unrealizedPnl']} ({equity['pnlPercent']}%)")
# Check lockup status
lockup_expiry = datetime.fromtimestamp(int(equity['lockupExpiry']) / 1000)
if datetime.now() < lockup_expiry:
days_left = (lockup_expiry - datetime.now()).days
print(f" Lockup: {days_left} days remaining")
else:
print(f" Lockup: Expired (withdrawable)")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"time"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type UserVaultEquitiesRequest struct {
Type string `json:"type"`
User string `json:"user"`
}
type VaultEquity struct {
VaultAddress string `json:"vaultAddress"`
VaultName string `json:"vaultName"`
Shares string `json:"shares"`
SharePrice string `json:"sharePrice"`
CurrentValue string `json:"currentValue"`
DepositValue string `json:"depositValue"`
UnrealizedPnl string `json:"unrealizedPnl"`
PnlPercent string `json:"pnlPercent"`
AllTimeDeposits string `json:"allTimeDeposits"`
AllTimeWithdrawals string `json:"allTimeWithdrawals"`
NetDeposits string `json:"netDeposits"`
DepositTimestamp int64 `json:"depositTimestamp"`
LockupExpiry int64 `json:"lockupExpiry"`
}
func getUserVaultEquities(userAddress string) ([]VaultEquity, error) {
reqBody, _ := json.Marshal(UserVaultEquitiesRequest{
Type: "userVaultEquities",
User: userAddress,
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var equities []VaultEquity
if err := json.Unmarshal(body, &equities); err != nil {
return nil, err
}
return equities, nil
}
func main() {
equities, err := getUserVaultEquities("0x63E8c7C149556D5f34F833419A287bb9Ef81487f")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Active vault positions: %d\n\n", len(equities))
// Calculate totals
var totalValue, totalPnl float64
for _, equity := range equities {
value, _ := strconv.ParseFloat(equity.CurrentValue, 64)
pnl, _ := strconv.ParseFloat(equity.UnrealizedPnl, 64)
totalValue += value
totalPnl += pnl
}
fmt.Printf("Portfolio Summary:\n")
fmt.Printf("Total Value: $%.2f\n", totalValue)
fmt.Printf("Total PnL: $%.2f\n\n", totalPnl)
fmt.Println("=== Vault Positions ===")
for _, equity := range equities {
fmt.Printf("\n%s:\n", equity.VaultName)
fmt.Printf(" Shares: %s\n", equity.Shares)
fmt.Printf(" Value: $%s\n", equity.CurrentValue)
fmt.Printf(" PnL: $%s (%s%%)\n", equity.UnrealizedPnl, equity.PnlPercent)
// Check lockup
lockupTime := time.Unix(equity.LockupExpiry/1000, 0)
if time.Now().Before(lockupTime) {
daysLeft := int(time.Until(lockupTime).Hours() / 24)
fmt.Printf(" Lockup: %d days remaining\n", daysLeft)
} else {
fmt.Println(" Lockup: Expired (withdrawable)")
}
}
}
```
## Common Use Cases
### 1. Calculate Total Vault Portfolio Value
Get comprehensive portfolio metrics:
```javascript
async function getVaultPortfolioMetrics(userAddress) {
const equities = await getUserVaultEquities(userAddress);
if (equities.length === 0) {
return { message: 'No vault positions found' };
}
const totalCurrentValue = equities.reduce((sum, e) =>
sum + parseFloat(e.currentValue), 0
);
const totalDeposited = equities.reduce((sum, e) =>
sum + parseFloat(e.netDeposits), 0
);
const totalPnl = equities.reduce((sum, e) =>
sum + parseFloat(e.unrealizedPnl), 0
);
const weightedReturn = equities.reduce((sum, e) => {
const weight = parseFloat(e.currentValue) / totalCurrentValue;
return sum + (parseFloat(e.pnlPercent) * weight);
}, 0);
return {
totalPositions: equities.length,
totalValue: totalCurrentValue.toFixed(2),
totalDeposited: totalDeposited.toFixed(2),
totalPnl: totalPnl.toFixed(2),
totalReturnPercent: ((totalPnl / totalDeposited) * 100).toFixed(2),
weightedReturnPercent: weightedReturn.toFixed(2),
largestPosition: equities.reduce((max, e) =>
parseFloat(e.currentValue) > parseFloat(max.currentValue) ? e : max
)
};
}
// Usage
const metrics = await getVaultPortfolioMetrics('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log('Portfolio Metrics:', metrics);
console.log(`Largest position: ${metrics.largestPosition.vaultName}`);
```
### 2. Check Withdrawal Availability
Determine which positions can be withdrawn:
```javascript
async function checkWithdrawalAvailability(userAddress) {
const equities = await getUserVaultEquities(userAddress);
const now = Date.now();
const available = [];
const locked = [];
equities.forEach(equity => {
const position = {
vaultName: equity.vaultName,
value: parseFloat(equity.currentValue),
shares: parseFloat(equity.shares),
lockupExpiry: equity.lockupExpiry
};
if (equity.lockupExpiry <= now) {
position.status = 'Available';
available.push(position);
} else {
const daysRemaining = Math.ceil((equity.lockupExpiry - now) / (1000 * 60 * 60 * 24));
position.status = 'Locked';
position.daysRemaining = daysRemaining;
locked.push(position);
}
});
const availableValue = available.reduce((sum, p) => sum + p.value, 0);
const lockedValue = locked.reduce((sum, p) => sum + p.value, 0);
return {
available: available,
locked: locked,
availableValue: availableValue.toFixed(2),
lockedValue: lockedValue.toFixed(2),
totalValue: (availableValue + lockedValue).toFixed(2)
};
}
// Usage
const withdrawal = await checkWithdrawalAvailability('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log(`\nWithdrawal Status:`);
console.log(`Available: $${withdrawal.availableValue}`);
console.log(`Locked: $${withdrawal.lockedValue}`);
console.log(`\nAvailable Positions (${withdrawal.available.length}):`);
withdrawal.available.forEach(p => {
console.log(` ${p.vaultName}: $${p.value.toLocaleString()}`);
});
console.log(`\nLocked Positions (${withdrawal.locked.length}):`);
withdrawal.locked.forEach(p => {
console.log(` ${p.vaultName}: $${p.value.toLocaleString()} (${p.daysRemaining} days)`);
});
```
### 3. Analyze Vault Allocation
View portfolio diversification across vaults:
```javascript
async function analyzeVaultAllocation(userAddress) {
const equities = await getUserVaultEquities(userAddress);
const totalValue = equities.reduce((sum, e) =>
sum + parseFloat(e.currentValue), 0
);
const allocation = equities.map(e => {
const value = parseFloat(e.currentValue);
const percentage = (value / totalValue) * 100;
return {
vaultName: e.vaultName,
value: value,
percentage: percentage.toFixed(2),
shares: parseFloat(e.shares),
pnl: parseFloat(e.unrealizedPnl),
pnlPercent: parseFloat(e.pnlPercent)
};
}).sort((a, b) => b.value - a.value);
// Check concentration risk
const top3Concentration = allocation.slice(0, 3).reduce((sum, a) =>
sum + parseFloat(a.percentage), 0
);
return {
allocation: allocation,
totalValue: totalValue.toFixed(2),
positions: allocation.length,
top3Concentration: top3Concentration.toFixed(2),
diversified: top3Concentration < 75
};
}
// Usage
const analysis = await analyzeVaultAllocation('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log(`\n=== Portfolio Allocation ===`);
console.log(`Total Value: $${parseFloat(analysis.totalValue).toLocaleString()}`);
console.log(`Positions: ${analysis.positions}`);
console.log(`Top 3 Concentration: ${analysis.top3Concentration}%`);
console.log(`Diversified: ${analysis.diversified ? 'Yes' : 'No (concentrated)'}`);
console.log(`\n=== Allocation by Vault ===`);
analysis.allocation.forEach((a, i) => {
console.log(`${i + 1}. ${a.vaultName}: ${a.percentage}% ($${a.value.toLocaleString()})`);
console.log(` PnL: ${a.pnlPercent > 0 ? '+' : ''}${a.pnlPercent}%`);
});
```
### 4. Track Performance Over Time
Monitor vault performance metrics:
```javascript
async function trackVaultPerformance(userAddress) {
const equities = await getUserVaultEquities(userAddress);
const performance = equities.map(e => {
const currentValue = parseFloat(e.currentValue);
const depositValue = parseFloat(e.netDeposits);
const pnl = parseFloat(e.unrealizedPnl);
const pnlPercent = parseFloat(e.pnlPercent);
// Calculate holding period
const depositDate = new Date(e.depositTimestamp);
const now = new Date();
const daysHeld = Math.floor((now - depositDate) / (1000 * 60 * 60 * 24));
// Annualized return
const annualizedReturn = daysHeld > 0
? (pnlPercent / daysHeld) * 365
: 0;
return {
vaultName: e.vaultName,
currentValue: currentValue,
depositValue: depositValue,
pnl: pnl,
returnPercent: pnlPercent,
daysHeld: daysHeld,
annualizedReturn: annualizedReturn.toFixed(2),
dailyReturn: daysHeld > 0 ? (pnlPercent / daysHeld).toFixed(3) : '0.000'
};
}).sort((a, b) => parseFloat(b.annualizedReturn) - parseFloat(a.annualizedReturn));
return performance;
}
// Usage
const performance = await trackVaultPerformance('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log(`\n=== Vault Performance ===`);
performance.forEach((p, i) => {
console.log(`\n${i + 1}. ${p.vaultName}`);
console.log(` Value: $${p.currentValue.toLocaleString()}`);
console.log(` Return: ${p.returnPercent > 0 ? '+' : ''}${p.returnPercent}%`);
console.log(` Days Held: ${p.daysHeld}`);
console.log(` Annualized: ${p.annualizedReturn}%`);
console.log(` Daily Avg: ${p.dailyReturn}%`);
});
```
### 5. Identify Best and Worst Performers
Analyze which vaults are performing well:
```javascript
async function identifyPerformers(userAddress) {
const equities = await getUserVaultEquities(userAddress);
// Sort by PnL percentage
const sorted = [...equities].sort((a, b) =>
parseFloat(b.pnlPercent) - parseFloat(a.pnlPercent)
);
const bestPerformers = sorted.slice(0, 3).map(e => ({
vaultName: e.vaultName,
pnl: parseFloat(e.unrealizedPnl),
pnlPercent: parseFloat(e.pnlPercent),
value: parseFloat(e.currentValue)
}));
const worstPerformers = sorted.slice(-3).reverse().map(e => ({
vaultName: e.vaultName,
pnl: parseFloat(e.unrealizedPnl),
pnlPercent: parseFloat(e.pnlPercent),
value: parseFloat(e.currentValue)
}));
// Calculate averages
const avgPnlPercent = equities.reduce((sum, e) =>
sum + parseFloat(e.pnlPercent), 0
) / equities.length;
return {
bestPerformers: bestPerformers,
worstPerformers: worstPerformers,
avgReturn: avgPnlPercent.toFixed(2),
spread: (parseFloat(sorted[0].pnlPercent) - parseFloat(sorted[sorted.length - 1].pnlPercent)).toFixed(2)
};
}
// Usage
const performers = await identifyPerformers('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log(`\n=== Best Performers ===`);
performers.bestPerformers.forEach((p, i) => {
console.log(`${i + 1}. ${p.vaultName}: +${p.pnlPercent}% ($${p.pnl.toLocaleString()})`);
});
console.log(`\n=== Worst Performers ===`);
performers.worstPerformers.forEach((p, i) => {
console.log(`${i + 1}. ${p.vaultName}: ${p.pnlPercent}% ($${p.pnl.toLocaleString()})`);
});
console.log(`\nPortfolio Statistics:`);
console.log(`Average Return: ${performers.avgReturn}%`);
console.log(`Performance Spread: ${performers.spread}%`);
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `400 Bad Request` | Missing or invalid user address | Ensure valid Ethereum address format |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Missing required parameter: user",
"code": "MISSING_PARAMETER"
}
```
### Robust Error Handling
```javascript
async function safeGetUserVaultEquities(userAddress, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getUserVaultEquities(userAddress);
} catch (error) {
if (error.response?.status === 429) {
// Rate limit - exponential backoff
const delay = Math.pow(2, i) * 1000;
await new Promise(r => setTimeout(r, delay));
} else if (error.response?.status === 400) {
throw new Error('Invalid user address');
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Poll responsibly** — Update vault positions every 30-60 seconds for dashboards
2. **Handle empty results** — Users may have no vault positions
3. **Check lockup periods** — Verify withdrawal availability before transactions
4. **Track allocation** — Monitor portfolio concentration and diversification
5. **Calculate returns properly** — Account for deposits/withdrawals over time
## Related Endpoints
- [**leadingVaults**](./leading-vaults) — Discover top-performing vaults
- [**vaultSummaries**](./vault-summaries) — Get comprehensive vault information
- [**clearinghouseState**](./clearinghouse-state) — Get user's perpetual account state
- [**spotClearinghouseState**](./spot-clearinghouse-state) — Get spot trading balances
---
*Track your Hyperliquid vault investments with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## validatorL1Votes - HyperCore Info Endpoint
# validatorL1Votes
Get validator voting information for L1 operations on Hyperliquid, including consensus data and validator participation.
## When to Use This Endpoint
The `validatorL1Votes` endpoint is essential for:
- **Validator Monitoring** — Track validator voting activity and participation
- **Consensus Analysis** — Analyze voting patterns and consensus formation
- **Network Health** — Monitor validator coordination on L1 operations
- **Staking Insights** — Understand validator behavior for staking decisions
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"validatorL1Votes"` |
### Example Request
```json
{
"type": "validatorL1Votes"
}
```
## Response
### Success Response
Returns validator voting information for L1 operations.
```json
{
"votes": []
}
```
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `votes` | `array` | Array of validator vote records for L1 operations |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{"type":"validatorL1Votes"}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getValidatorL1Votes() {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'validatorL1Votes'
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const votes = await getValidatorL1Votes();
console.log(`Total votes: ${votes.votes.length}`);
```
```python
from typing import Dict
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_validator_l1_votes() -> Dict:
"""Get validator L1 voting information"""
response = requests.post(
ENDPOINT,
json={'type': 'validatorL1Votes'},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
votes = get_validator_l1_votes()
print(f"Total votes: {len(votes['votes'])}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type ValidatorL1VotesRequest struct {
Type string `json:"type"`
}
type ValidatorL1VotesResponse struct {
Votes []interface{} `json:"votes"`
}
func getValidatorL1Votes() (*ValidatorL1VotesResponse, error) {
reqBody, _ := json.Marshal(ValidatorL1VotesRequest{
Type: "validatorL1Votes",
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result ValidatorL1VotesResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
votes, err := getValidatorL1Votes()
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Total votes: %d\n", len(votes.Votes))
}
```
## Common Use Cases
### 1. Monitor Validator Participation
Track validator activity on L1 operations:
```javascript
async function monitorValidatorActivity() {
const data = await getValidatorL1Votes();
console.log('=== Validator L1 Voting Activity ===\n');
console.log(`Total vote records: ${data.votes.length}`);
if (data.votes.length === 0) {
console.log('No recent L1 voting activity');
}
}
```
### 2. Analyze Consensus Patterns
Analyze voting patterns and consensus formation:
```javascript
async function analyzeConsensus() {
const data = await getValidatorL1Votes();
return {
totalVotes: data.votes.length,
timestamp: Date.now(),
hasActivity: data.votes.length > 0
};
}
// Usage
const analysis = await analyzeConsensus();
console.log(`Consensus analysis:`, analysis);
```
### 3. Build Validator Dashboard
Create a monitoring dashboard for validators:
```javascript
async function getValidatorDashboard() {
try {
const votes = await getValidatorL1Votes();
return {
status: 'operational',
voteCount: votes.votes.length,
lastUpdated: new Date().toISOString()
};
} catch (error) {
return {
status: 'error',
error: error.message
};
}
}
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Invalid request",
"code": "INVALID_REQUEST"
}
```
### Robust Error Handling
```javascript
async function safeGetValidatorL1Votes(maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getValidatorL1Votes();
} catch (error) {
if (error.response?.status === 429) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Poll regularly** — Monitor validator activity at consistent intervals
2. **Cache appropriately** — Cache results for several minutes to reduce load
3. **Handle empty responses** — Account for periods with no L1 voting activity
4. **Implement timeouts** — Use reasonable timeout values (10-30 seconds)
5. **Monitor trends** — Track voting patterns over time for insights
## Related Endpoints
- [**delegatorSummary**](./delegator-summary) — Get delegation summary information
- [**delegations**](./delegations) — Get staking delegation details
- [**meta**](./meta) — Get trading pair metadata
---
*Access real-time Hyperliquid validator information with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## vaultSummaries - HyperCore Info Endpoint
# vaultSummaries
Get comprehensive summary information for all vaults on the platform, including performance metrics, total value locked, and vault characteristics.
> **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 Endpoint
The `vaultSummaries` endpoint is essential for vault aggregators, analytics platforms, and DeFi dashboards who need to:
- **Aggregate Vault Data** — Get complete overview of all available vaults
- **Build Vault Explorers** — Create searchable vault directories
- **Track Market Growth** — Monitor total vault ecosystem metrics
- **Portfolio Diversification** — Discover vaults across different strategies
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"vaultSummaries"` |
### Example Request
```json
{
"type": "vaultSummaries"
}
```
## Response
### Success Response
```json
[
{
"vaultAddress": "0x1234567890abcdef1234567890abcdef12345678",
"name": "Alpha Strategy Vault",
"tvl": "5000000.00",
"apy": "45.2",
"totalDeposits": "4800000.00",
"totalWithdrawals": "200000.00",
"netDeposits": "4600000.00",
"sharePrice": "1.15",
"totalShares": "4347826.09",
"inception": "2024-01-15",
"performanceFee": "20",
"managementFee": "2",
"minDeposit": "1000.00",
"depositLockup": "7"
},
{
"vaultAddress": "0xabcdef1234567890abcdef1234567890abcdef12",
"name": "Delta Neutral Vault",
"tvl": "3500000.00",
"apy": "28.7",
"totalDeposits": "3200000.00",
"totalWithdrawals": "100000.00",
"netDeposits": "3100000.00",
"sharePrice": "1.09",
"totalShares": "3211009.17",
"inception": "2024-02-20",
"performanceFee": "15",
"managementFee": "1.5",
"minDeposit": "500.00",
"depositLockup": "3"
}
]
```
### Response Fields
The response is an array of vault summary objects, each containing:
| Field | Type | Description |
|-------|------|-------------|
| `vaultAddress` | `string` | Ethereum address of the vault contract |
| `name` | `string` | Name of the vault |
| `tvl` | `string` | Total value locked in USD |
| `apy` | `string` | Annual percentage yield |
| `totalDeposits` | `string` | Cumulative deposits in USD |
| `totalWithdrawals` | `string` | Cumulative withdrawals in USD |
| `netDeposits` | `string` | Net deposits (deposits - withdrawals) |
| `sharePrice` | `string` | Current share price |
| `totalShares` | `string` | Total shares outstanding |
| `inception` | `string` | Vault creation date (ISO 8601) |
| `performanceFee` | `string` | Performance fee percentage |
| `managementFee` | `string` | Management fee percentage |
| `minDeposit` | `string` | Minimum deposit amount in USD |
| `depositLockup` | `string` | Lockup period in days |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "vaultSummaries"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getVaultSummaries() {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'vaultSummaries'
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const vaults = await getVaultSummaries();
console.log(`Total vaults: ${vaults.length}`);
// Calculate ecosystem metrics
const totalTVL = vaults.reduce((sum, v) => sum + parseFloat(v.tvl), 0);
const avgAPY = vaults.reduce((sum, v) => sum + parseFloat(v.apy), 0) / vaults.length;
console.log(`\nEcosystem Metrics:`);
console.log(`Total TVL: $${totalTVL.toLocaleString()}`);
console.log(`Average APY: ${avgAPY.toFixed(2)}%`);
// Group by fee structure
const lowFee = vaults.filter(v => parseFloat(v.performanceFee) < 15);
console.log(`\nLow-fee vaults (< 15%): ${lowFee.length}`);
```
```python
from typing import List, Dict
from datetime import datetime
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_vault_summaries() -> List[Dict]:
"""Get summary information for all vaults"""
response = requests.post(
ENDPOINT,
json={'type': 'vaultSummaries'},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
vaults = get_vault_summaries()
print(f"Total vaults: {len(vaults)}\n")
# Calculate ecosystem metrics
total_tvl = sum(float(v['tvl']) for v in vaults)
avg_apy = sum(float(v['apy']) for v in vaults) / len(vaults)
print("=== Ecosystem Metrics ===")
print(f"Total TVL: ${total_tvl:,.2f}")
print(f"Average APY: {avg_apy:.2f}%")
# Find vaults by criteria
print("\n=== Vaults by TVL (Top 5) ===")
vaults_by_tvl = sorted(vaults, key=lambda v: float(v['tvl']), reverse=True)
for i, vault in enumerate(vaults_by_tvl[:5], 1):
print(f"{i}. {vault['name']}: ${float(vault['tvl']):,.2f}")
# Analyze fee structures
print("\n=== Fee Analysis ===")
low_fee = [v for v in vaults if float(v['performanceFee']) < 15]
high_fee = [v for v in vaults if float(v['performanceFee']) >= 20]
print(f"Low-fee vaults (< 15%): {len(low_fee)}")
print(f"High-fee vaults (≥ 20%): {len(high_fee)}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"sort"
"strconv"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type VaultSummariesRequest struct {
Type string `json:"type"`
}
type VaultSummary struct {
VaultAddress string `json:"vaultAddress"`
Name string `json:"name"`
TVL string `json:"tvl"`
APY string `json:"apy"`
TotalDeposits string `json:"totalDeposits"`
TotalWithdrawals string `json:"totalWithdrawals"`
NetDeposits string `json:"netDeposits"`
SharePrice string `json:"sharePrice"`
TotalShares string `json:"totalShares"`
Inception string `json:"inception"`
PerformanceFee string `json:"performanceFee"`
ManagementFee string `json:"managementFee"`
MinDeposit string `json:"minDeposit"`
DepositLockup string `json:"depositLockup"`
}
func getVaultSummaries() ([]VaultSummary, error) {
reqBody, _ := json.Marshal(VaultSummariesRequest{
Type: "vaultSummaries",
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var vaults []VaultSummary
if err := json.Unmarshal(body, &vaults); err != nil {
return nil, err
}
return vaults, nil
}
func main() {
vaults, err := getVaultSummaries()
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Total vaults: %d\n\n", len(vaults))
// Calculate total TVL
var totalTVL float64
for _, vault := range vaults {
tvl, _ := strconv.ParseFloat(vault.TVL, 64)
totalTVL += tvl
}
fmt.Printf("Total TVL: $%.2f\n", totalTVL)
// Sort by TVL
sort.Slice(vaults, func(i, j int) bool {
tvlI, _ := strconv.ParseFloat(vaults[i].TVL, 64)
tvlJ, _ := strconv.ParseFloat(vaults[j].TVL, 64)
return tvlI > tvlJ
})
fmt.Println("\n=== Top 5 Vaults by TVL ===")
for i, vault := range vaults {
if i >= 5 {
break
}
fmt.Printf("%d. %s\n", i+1, vault.Name)
fmt.Printf(" TVL: $%s\n", vault.TVL)
fmt.Printf(" APY: %s%%\n", vault.APY)
}
}
```
## Common Use Cases
### 1. Find Vaults by Investment Criteria
Filter vaults based on specific requirements:
```javascript
async function findVaultsByCriteria(criteria) {
const vaults = await getVaultSummaries();
return vaults.filter(v => {
const tvl = parseFloat(v.tvl);
const apy = parseFloat(v.apy);
const minDeposit = parseFloat(v.minDeposit);
const lockup = parseInt(v.depositLockup);
const perfFee = parseFloat(v.performanceFee);
// Check all criteria
if (criteria.minTVL && tvl < criteria.minTVL) return false;
if (criteria.minAPY && apy < criteria.minAPY) return false;
if (criteria.maxMinDeposit && minDeposit > criteria.maxMinDeposit) return false;
if (criteria.maxLockup && lockup > criteria.maxLockup) return false;
if (criteria.maxPerformanceFee && perfFee > criteria.maxPerformanceFee) return false;
return true;
});
}
// Usage
const suitableVaults = await findVaultsByCriteria({
minTVL: 1000000, // At least $1M TVL
minAPY: 25, // At least 25% APY
maxMinDeposit: 5000, // Max $5k minimum deposit
maxLockup: 7, // Max 7 days lockup
maxPerformanceFee: 20 // Max 20% performance fee
});
console.log(`Found ${suitableVaults.length} vaults matching criteria`);
suitableVaults.forEach(v => {
console.log(`${v.name}: ${v.apy}% APY, $${v.tvl} TVL`);
});
```
### 2. Analyze Vault Growth Metrics
Track vault growth and capital flows:
```javascript
async function analyzeVaultGrowth() {
const vaults = await getVaultSummaries();
const analysis = vaults.map(v => {
const tvl = parseFloat(v.tvl);
const netDeposits = parseFloat(v.netDeposits);
const sharePrice = parseFloat(v.sharePrice);
// Calculate returns from share price
const returns = ((sharePrice - 1) / 1) * 100;
// Calculate growth from trading vs deposits
const tradingGains = tvl - netDeposits;
const growthFromTrading = (tradingGains / netDeposits) * 100;
return {
name: v.name,
tvl: tvl,
netDeposits: netDeposits,
tradingGains: tradingGains,
returns: returns.toFixed(2),
growthFromTrading: growthFromTrading.toFixed(2),
depositorCount: Math.round(netDeposits / parseFloat(v.minDeposit))
};
});
return analysis.sort((a, b) => b.growthFromTrading - a.growthFromTrading);
}
// Usage
const growth = await analyzeVaultGrowth();
console.log('\n=== Vaults with Highest Trading Gains ===');
growth.slice(0, 5).forEach((v, i) => {
console.log(`\n${i + 1}. ${v.name}`);
console.log(` Trading Gains: $${v.tradingGains.toLocaleString()}`);
console.log(` Growth from Trading: ${v.growthFromTrading}%`);
console.log(` Total Returns: ${v.returns}%`);
});
```
### 3. Compare Fee Structures
Analyze and compare vault fee models:
```javascript
async function analyzeFeeStructures() {
const vaults = await getVaultSummaries();
const feeAnalysis = vaults.map(v => {
const apy = parseFloat(v.apy);
const perfFee = parseFloat(v.performanceFee);
const mgmtFee = parseFloat(v.managementFee);
const tvl = parseFloat(v.tvl);
// Estimate annual fees
const annualMgmtFee = tvl * (mgmtFee / 100);
const estimatedPerfFee = tvl * (apy / 100) * (perfFee / 100);
const totalAnnualFees = annualMgmtFee + estimatedPerfFee;
// Net APY after fees
const grossReturns = tvl * (apy / 100);
const netReturns = grossReturns - totalAnnualFees;
const netAPY = (netReturns / tvl) * 100;
return {
name: v.name,
grossAPY: apy,
netAPY: netAPY.toFixed(2),
perfFee: perfFee,
mgmtFee: mgmtFee,
totalFeesUSD: totalAnnualFees.toFixed(2),
feeImpact: ((apy - netAPY) / apy * 100).toFixed(2)
};
});
// Sort by net APY
return feeAnalysis.sort((a, b) => parseFloat(b.netAPY) - parseFloat(a.netAPY));
}
// Usage
const feeAnalysis = await analyzeFeeStructures();
console.log('\n=== Best Net Returns After Fees ===');
feeAnalysis.slice(0, 5).forEach((v, i) => {
console.log(`\n${i + 1}. ${v.name}`);
console.log(` Gross APY: ${v.grossAPY}%`);
console.log(` Net APY: ${v.netAPY}%`);
console.log(` Fee Impact: ${v.feeImpact}%`);
});
```
### 4. Track Market Concentration
Analyze TVL distribution across vaults:
```javascript
async function analyzeMarketConcentration() {
const vaults = await getVaultSummaries();
// Sort by TVL
const sortedVaults = [...vaults].sort((a, b) =>
parseFloat(b.tvl) - parseFloat(a.tvl)
);
const totalTVL = vaults.reduce((sum, v) => sum + parseFloat(v.tvl), 0);
// Calculate concentration metrics
const top5TVL = sortedVaults.slice(0, 5).reduce((sum, v) =>
sum + parseFloat(v.tvl), 0
);
const top10TVL = sortedVaults.slice(0, 10).reduce((sum, v) =>
sum + parseFloat(v.tvl), 0
);
const concentration = {
totalVaults: vaults.length,
totalTVL: totalTVL,
top5Share: ((top5TVL / totalTVL) * 100).toFixed(2),
top10Share: ((top10TVL / totalTVL) * 100).toFixed(2),
avgTVL: (totalTVL / vaults.length).toFixed(2),
medianTVL: parseFloat(sortedVaults[Math.floor(vaults.length / 2)].tvl)
};
return {
...concentration,
topVaults: sortedVaults.slice(0, 5).map(v => ({
name: v.name,
tvl: parseFloat(v.tvl),
marketShare: ((parseFloat(v.tvl) / totalTVL) * 100).toFixed(2)
}))
};
}
// Usage
const concentration = await analyzeMarketConcentration();
console.log('\n=== Market Concentration ===');
console.log(`Total TVL: $${concentration.totalTVL.toLocaleString()}`);
console.log(`Top 5 control: ${concentration.top5Share}%`);
console.log(`Top 10 control: ${concentration.top10Share}%`);
console.log('\n=== Top 5 Vaults ===');
concentration.topVaults.forEach((v, i) => {
console.log(`${i + 1}. ${v.name}: ${v.marketShare}% market share`);
});
```
### 5. Build Vault Comparison Tool
Create a comprehensive vault comparison:
```javascript
async function compareVaults(vaultAddresses) {
const allVaults = await getVaultSummaries();
const selectedVaults = allVaults.filter(v =>
vaultAddresses.includes(v.vaultAddress)
);
const comparison = selectedVaults.map(v => {
const tvl = parseFloat(v.tvl);
const apy = parseFloat(v.apy);
const sharePrice = parseFloat(v.sharePrice);
const perfFee = parseFloat(v.performanceFee);
const mgmtFee = parseFloat(v.managementFee);
// Calculate net APY after fees
const grossReturns = tvl * (apy / 100);
const annualFees = tvl * (mgmtFee / 100) + grossReturns * (perfFee / 100);
const netAPY = ((grossReturns - annualFees) / tvl) * 100;
return {
name: v.name,
address: v.vaultAddress,
tvl: tvl,
apy: apy,
netAPY: netAPY.toFixed(2),
sharePrice: sharePrice,
returns: ((sharePrice - 1) * 100).toFixed(2),
minDeposit: parseFloat(v.minDeposit),
lockup: parseInt(v.depositLockup),
fees: `${perfFee}% perf / ${mgmtFee}% mgmt`,
inception: v.inception
};
});
return comparison;
}
// Usage
const vaultsToCompare = [
'0x1234567890abcdef1234567890abcdef12345678',
'0xabcdef1234567890abcdef1234567890abcdef12'
];
const comparison = await compareVaults(vaultsToCompare);
console.log('\n=== Vault Comparison ===');
comparison.forEach(v => {
console.log(`\n${v.name}`);
console.log(`TVL: $${v.tvl.toLocaleString()}`);
console.log(`Gross APY: ${v.apy}% | Net APY: ${v.netAPY}%`);
console.log(`Returns: ${v.returns}%`);
console.log(`Min Deposit: $${v.minDeposit} | Lockup: ${v.lockup} days`);
console.log(`Fees: ${v.fees}`);
});
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Rate limit exceeded",
"code": "RATE_LIMIT_EXCEEDED"
}
```
### Robust Error Handling
```javascript
async function safeGetVaultSummaries(maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getVaultSummaries();
} catch (error) {
if (error.response?.status === 429) {
const delay = Math.pow(2, i) * 1000;
await new Promise(r => setTimeout(r, delay));
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Cache appropriately** — Vault summaries can be cached for 5-15 minutes
2. **Consider fees** — Always calculate net returns after fees
3. **Check liquidity** — Verify TVL is sufficient for your deposit size
4. **Review lockups** — Ensure lockup periods match your investment timeline
5. **Monitor growth** — Track both deposit growth and trading performance
## Related Endpoints
- [**leadingVaults**](./leading-vaults) — Get top-performing vaults
- [**userVaultEquities**](./user-vault-equities) — Get user's vault positions
- [**clearinghouseState**](./clearinghouse-state) — Get user's perpetual account state
---
*Access comprehensive Hyperliquid vault data with Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## webData2 - HyperCore Info Endpoint
# webData2
Get comprehensive web interface data for a user in a single request, optimized for dashboard and UI rendering.
## When to Use This Endpoint
The `webData2` endpoint is essential for:
- **Dashboard Building** — Get all necessary data for user dashboards
- **Web Interface** — Populate web UI with complete user data
- **Performance Optimization** — Reduce multiple API calls to one request
- **Full State Access** — Access comprehensive user state efficiently
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | `string` | Yes | Must be `"webData2"` |
| `user` | `string` | Yes | User's Ethereum wallet address |
### Example Request
```json
{
"type": "webData2",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}
```
## Response
### Success Response
Returns comprehensive web interface data for the specified user.
```json
{
"data": {}
}
```
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `data` | `object` | Comprehensive web interface data including account state, positions, orders, and other UI-relevant information |
## Code Examples
```bash
curl -X POST 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info' \
-H 'Content-Type: application/json' \
-d '{
"type": "webData2",
"user": "0x63E8c7C149556D5f34F833419A287bb9Ef81487f"
}'
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info';
async function getWebData2(userAddress) {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
type: 'webData2',
user: userAddress
})
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
}
// Usage
const webData = await getWebData2('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
console.log('Web data loaded successfully');
```
```python
from typing import Dict
ENDPOINT = 'https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info'
def get_web_data_2(user_address: str) -> Dict:
"""Get comprehensive web interface data"""
response = requests.post(
ENDPOINT,
json={
'type': 'webData2',
'user': user_address
},
headers={
'Content-Type': 'application/json',
},
timeout=10
)
response.raise_for_status()
return response.json()
# Usage
web_data = get_web_data_2('0x63E8c7C149556D5f34F833419A287bb9Ef81487f')
print("Web data loaded successfully")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-info.n.dwellir.com/API_KEY/info"
type WebData2Request struct {
Type string `json:"type"`
User string `json:"user"`
}
type WebData2Response struct {
Data map[string]interface{} `json:"data"`
}
func getWebData2(userAddress string) (*WebData2Response, error) {
reqBody, _ := json.Marshal(WebData2Request{
Type: "webData2",
User: userAddress,
})
req, _ := http.NewRequest("POST", Endpoint, bytes.NewBuffer(reqBody))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result WebData2Response
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
return &result, nil
}
func main() {
webData, err := getWebData2("0x63E8c7C149556D5f34F833419A287bb9Ef81487f")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Println("Web data loaded successfully")
}
```
## Common Use Cases
### 1. Load Complete Dashboard
Load all data needed for a user dashboard:
```javascript
async function loadUserDashboard(userAddress) {
const webData = await getWebData2(userAddress);
console.log('=== User Dashboard ===\n');
console.log('Dashboard data loaded successfully');
console.log('Ready to render UI');
return webData.data;
}
// Usage
const dashboardData = await loadUserDashboard('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
```
### 2. Initialize Web Interface
Bootstrap a web application with user data:
```javascript
class WebInterface {
constructor(userAddress) {
this.userAddress = userAddress;
this.data = null;
}
async initialize() {
console.log('Initializing web interface...');
this.data = await getWebData2(this.userAddress);
console.log('Interface ready');
return this.data;
}
getData() {
return this.data;
}
async refresh() {
console.log('Refreshing data...');
this.data = await getWebData2(this.userAddress);
return this.data;
}
}
// Usage
const interface = new WebInterface('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
await interface.initialize();
```
### 3. Periodic Data Refresh
Refresh dashboard data at intervals:
```javascript
class DashboardDataManager {
constructor(userAddress, refreshIntervalMs = 30000) {
this.userAddress = userAddress;
this.refreshIntervalMs = refreshIntervalMs;
this.currentData = null;
this.onUpdate = null;
}
async start(updateCallback) {
this.onUpdate = updateCallback;
// Initial load
await this.refresh();
// Periodic refresh
setInterval(() => this.refresh(), this.refreshIntervalMs);
}
async refresh() {
try {
this.currentData = await getWebData2(this.userAddress);
if (this.onUpdate) {
this.onUpdate(this.currentData);
}
return this.currentData;
} catch (error) {
console.error('Failed to refresh data:', error);
}
}
getCurrentData() {
return this.currentData;
}
}
// Usage
const manager = new DashboardDataManager('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
manager.start((data) => {
console.log('Dashboard data updated');
// Update UI with new data
});
```
### 4. Build Trading Interface
Create a complete trading interface:
```javascript
async function buildTradingInterface(userAddress) {
try {
const webData = await getWebData2(userAddress);
return {
status: 'success',
data: webData.data,
isReady: true,
lastUpdated: new Date().toISOString()
};
} catch (error) {
return {
status: 'error',
error: error.message,
isReady: false
};
}
}
// Usage
const tradingInterface = await buildTradingInterface('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
if (tradingInterface.isReady) {
console.log('Trading interface ready');
} else {
console.error('Failed to load interface:', tradingInterface.error);
}
```
### 5. Cache-Optimized Data Loading
Implement efficient caching for web data:
```javascript
class CachedWebDataLoader {
constructor(userAddress, cacheDurationMs = 60000) {
this.userAddress = userAddress;
this.cacheDurationMs = cacheDurationMs;
this.cache = null;
this.cacheTime = 0;
}
async load(forceRefresh = false) {
const now = Date.now();
const cacheAge = now - this.cacheTime;
if (!forceRefresh && this.cache && cacheAge < this.cacheDurationMs) {
console.log(`Using cached data (age: ${Math.round(cacheAge / 1000)}s)`);
return this.cache;
}
console.log('Loading fresh data...');
const data = await getWebData2(this.userAddress);
this.cache = data;
this.cacheTime = now;
return data;
}
invalidateCache() {
this.cache = null;
this.cacheTime = 0;
}
}
// Usage
const loader = new CachedWebDataLoader('0x63E8c7C149556D5f34F833419A287bb9Ef81487f');
const data = await loader.load(); // Fresh load
const cachedData = await loader.load(); // From cache
```
## Error Handling
### Common Errors
| Error | Cause | Solution |
|-------|-------|----------|
| `401 Unauthorized` | Invalid API key | Verify your API key is correct |
| `400 Bad Request` | Missing or invalid user address | Ensure valid Ethereum address format |
| `429 Too Many Requests` | Rate limit exceeded | Implement request throttling |
| `500 Internal Server Error` | Server issue | Retry with exponential backoff |
### Error Response Example
```json
{
"error": "Missing required parameter: user",
"code": "MISSING_PARAMETER"
}
```
### Robust Error Handling
```javascript
async function safeGetWebData2(userAddress, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await getWebData2(userAddress);
} catch (error) {
if (error.response?.status === 429) {
await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000));
} else if (error.response?.status === 400) {
throw new Error('Invalid user address');
} else if (i === maxRetries - 1) {
throw error;
}
}
}
}
```
## Best Practices
1. **Cache appropriately** — Cache data for 30-60 seconds to reduce API calls
2. **Handle loading states** — Show loading indicators during data fetch
3. **Validate addresses** — Ensure user addresses are valid before requests
4. **Refresh periodically** — Update dashboard data every 30-60 seconds
5. **Optimize rendering** — Only re-render UI components when data changes
## Performance Tips
### Efficient Dashboard Updates
```javascript
class EfficientDashboard {
constructor(userAddress) {
this.userAddress = userAddress;
this.lastData = null;
}
async update() {
const newData = await getWebData2(this.userAddress);
// Compare with previous data
const hasChanged = JSON.stringify(newData) !== JSON.stringify(this.lastData);
if (hasChanged) {
console.log('Data changed - updating UI');
this.lastData = newData;
return { changed: true, data: newData };
}
console.log('No changes detected');
return { changed: false, data: newData };
}
}
```
## Related Endpoints
- [**clearinghouseState**](./clearinghouse-state) — Get detailed account state
- [**openOrders**](./open-orders) — Get open orders separately
- [**userFees**](./user-fees) — Get fee information
- [**spotClearinghouseState**](./spot-clearinghouse-state) — Get spot balances
---
*Build powerful web interfaces with comprehensive data from Dwellir's HyperCore Info Endpoint. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## hl_getBatchBlocks - Get Batch Fill Blocks
# hl_getBatchBlocks
Return fill blocks in a `[from, to]` range for a given stream.
## When to Use This Method
`hl_getBatchBlocks` is essential for:
- **Backfilling** — Retrieve historical fill data in bulk
- **Batch Processing** — Process trade events in ordered block ranges
- **Analytics Pipelines** — Feed fill data into downstream systems
- **Reconciliation** — Verify trade execution across block ranges
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-jsonrpc.n.dwellir.com//hypercore
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `stream` | string | Yes | Data stream. Must be `"trades"` |
| `from` | integer | Yes | First block number (inclusive, must be > 0) |
| `to` | integer | Yes | Last block number (inclusive, must be >= from) |
The range is capped at 100 blocks per request by default.
### Example Request
```json
{
"jsonrpc": "2.0",
"method": "hl_getBatchBlocks",
"params": { "stream": "trades", "from": 907626062, "to": 907626064 },
"id": 1
}
```
## Response
### Success Response
```json
{
"jsonrpc": "2.0",
"result": {
"blocks": [
{
"local_time": "2026-02-27T09:58:16.738110784",
"block_time": "2026-02-27T09:58:16.410825222",
"block_number": 907626062,
"events": [
[
"0x9f9a72b449783e6a7e9afca2efa49a6b77793555",
{
"coin": "ETH",
"px": "2010.8",
"sz": "0.02",
"side": "B",
"time": 1772186296410,
"startPosition": "0.0543",
"dir": "Open Long",
"closedPnl": "0.0",
"hash": "0x92bca362a1e7aad59436043619464e0203a000483ceac9a736854eb560eb84c0",
"oid": 331832891533,
"crossed": false,
"fee": "0.005791",
"tid": 379919209298471,
"feeToken": "USDC",
"twapId": null
}
],
[
"0xf8ae6942b61c6cd0333d174244f2be138626a89e",
{
"coin": "ETH",
"px": "2010.8",
"sz": "0.02",
"side": "A",
"time": 1772186296410,
"startPosition": "0.0",
"dir": "Open Short",
"closedPnl": "0.0",
"hash": "0x92bca362a1e7aad59436043619464e0203a000483ceac9a736854eb560eb84c0",
"oid": 331834694017,
"crossed": true,
"fee": "0.017373",
"tid": 379919209298471,
"feeToken": "USDC",
"twapId": null
}
]
]
},
{
"local_time": "2026-02-27T09:58:16.935172042",
"block_time": "2026-02-27T09:58:16.511724597",
"block_number": 907626064,
"events": []
}
]
},
"id": 1
}
```
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `blocks` | array | Array of block objects in the requested range |
#### Block Object
| Field | Type | Description |
|-------|------|-------------|
| `block_number` | integer | Block number (height) |
| `block_time` | string | ISO-8601 timestamp from the upstream source |
| `local_time` | string | ISO-8601 timestamp when the block was received locally |
| `events` | array | Array of fill events in this block (may be empty) |
#### Fill Event
Each event is a two-element array: `[address, fill]`, where `address` is the trader's hex address and `fill` is an object with the following fields:
| Field | Type | Description |
|-------|------|-------------|
| `coin` | string | Asset symbol (e.g. `"ETH"`, `"HYPE"`, `"xyz:XYZ100"`) |
| `px` | string | Execution price |
| `sz` | string | Fill size |
| `side` | string | `"B"` (buy) or `"A"` (sell/ask) |
| `time` | integer | Unix timestamp in milliseconds |
| `startPosition` | string | Position size before this fill |
| `dir` | string | Trade direction (e.g. `"Open Long"`, `"Open Short"`, `"Close Long"`, `"Close Short"`) |
| `closedPnl` | string | Realized PnL from this fill |
| `hash` | string | Transaction hash |
| `oid` | integer | Order ID |
| `crossed` | boolean | Whether the order crossed the spread (taker) |
| `fee` | string | Fee charged (negative means rebate) |
| `tid` | integer | Trade ID |
| `feeToken` | string | Token used for fee payment (e.g. `"USDC"`) |
| `twapId` | integer \| null | TWAP order ID, if applicable |
| `cloid` | string | Client order ID (optional, present when set by the trader) |
### Error Response
```json
{
"jsonrpc": "2.0",
"error": { "code": -32602, "message": "from must be > 0" },
"id": 1
}
```
## Code Examples
```bash
curl -s https://api-hyperliquid-mainnet-jsonrpc.n.dwellir.com//hypercore \
-H 'Content-Type: application/json' \
-d '{
"jsonrpc": "2.0",
"method": "hl_getBatchBlocks",
"params": { "stream": "trades", "from": 907626062, "to": 907626064 },
"id": 1
}' | jq .
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-jsonrpc.n.dwellir.com//hypercore';
async function getBatchBlocks(from, to, stream = 'trades') {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'hl_getBatchBlocks',
params: { stream, from, to },
id: 1
})
});
const data = await response.json();
if (data.error) {
throw new Error(`JSON-RPC error ${data.error.code}: ${data.error.message}`);
}
return data.result.blocks;
}
// Usage
const blocks = await getBatchBlocks(907626062, 907626064);
console.log(`Received ${blocks.length} blocks`);
for (const block of blocks) {
console.log(`Block ${block.block_number}: ${block.events.length} events at ${block.block_time}`);
}
```
```python
ENDPOINT = 'https://api-hyperliquid-mainnet-jsonrpc.n.dwellir.com//hypercore'
def get_batch_blocks(from_block: int, to_block: int, stream: str = 'trades') -> list:
"""Retrieve a batch of fill blocks for the given range."""
response = requests.post(
ENDPOINT,
json={
'jsonrpc': '2.0',
'method': 'hl_getBatchBlocks',
'params': {'stream': stream, 'from': from_block, 'to': to_block},
'id': 1
},
headers={'Content-Type': 'application/json'},
timeout=30
)
response.raise_for_status()
data = response.json()
if 'error' in data:
raise Exception(f"JSON-RPC error {data['error']['code']}: {data['error']['message']}")
return data['result']['blocks']
# Usage
blocks = get_batch_blocks(907626062, 907626064)
print(f"Received {len(blocks)} blocks")
for block in blocks:
print(f"Block {block['block_number']}: {len(block['events'])} events at {block['block_time']}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-jsonrpc.n.dwellir.com//hypercore"
type JSONRPCRequest struct {
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params interface{} `json:"params"`
ID int `json:"id"`
}
type BatchBlocksParams struct {
Stream string `json:"stream"`
From int64 `json:"from"`
To int64 `json:"to"`
}
type Block struct {
BlockNumber int64 `json:"block_number"`
BlockTime string `json:"block_time"`
LocalTime string `json:"local_time"`
Events json.RawMessage `json:"events"`
}
type BatchBlocksResult struct {
Blocks []Block `json:"blocks"`
}
type JSONRPCResponse struct {
JSONRPC string `json:"jsonrpc"`
Result *BatchBlocksResult `json:"result,omitempty"`
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"error,omitempty"`
ID int `json:"id"`
}
func getBatchBlocks(from, to int64) ([]Block, error) {
reqBody, _ := json.Marshal(JSONRPCRequest{
JSONRPC: "2.0",
Method: "hl_getBatchBlocks",
Params: BatchBlocksParams{Stream: "trades", From: from, To: to},
ID: 1,
})
resp, err := http.Post(Endpoint, "application/json", bytes.NewBuffer(reqBody))
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result JSONRPCResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
if result.Error != nil {
return nil, fmt.Errorf("JSON-RPC error %d: %s", result.Error.Code, result.Error.Message)
}
return result.Result.Blocks, nil
}
func main() {
blocks, err := getBatchBlocks(907626062, 907626064)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Received %d blocks\n", len(blocks))
for _, block := range blocks {
fmt.Printf("Block %d at %s\n", block.BlockNumber, block.BlockTime)
}
}
```
## Common Use Cases
### 1. Sequential Backfill
Fetch all blocks from a known starting point to the latest:
```javascript
async function backfill(startBlock) {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'hl_getLatestBlockNumber',
params: ['trades'],
id: 1
})
});
const { result: latestBlock } = await response.json();
let current = startBlock;
while (current <= latestBlock) {
const to = Math.min(current + 99, latestBlock);
const blocks = await getBatchBlocks(current, to);
console.log(`Fetched blocks ${current}–${to}: ${blocks.length} blocks`);
for (const block of blocks) {
// Process each block
}
current = to + 1;
}
}
```
### 2. Event Counting
Count fill events across a block range:
```python
def count_events(from_block: int, to_block: int) -> dict:
blocks = get_batch_blocks(from_block, to_block)
total_events = 0
for block in blocks:
total_events += len(block['events'])
return {
'block_range': f"{from_block}–{to_block}",
'blocks_returned': len(blocks),
'total_events': total_events
}
```
## Error Handling
| Error Code | Cause | Solution |
|------------|-------|----------|
| -32602 | `from` must be > 0 | Ensure `from` is a positive integer |
| -32602 | `to` must be >= `from` | Ensure `to` is greater than or equal to `from` |
| -32602 | Range exceeds max batch size | Reduce the range to 100 blocks or fewer |
| -32602 | Unsupported stream | Use `"trades"` as the stream value |
| -32600 | Array-wrapped request | Send a single JSON-RPC object, not an array |
| -32700 | Malformed JSON | Validate your request JSON |
## Best Practices
1. **Respect the batch limit** — Keep ranges at or below 100 blocks per request
2. **Use sequential fetching** — Combine with `hl_getLatestBlockNumber` to walk forward
3. **Handle sparse ranges** — Some blocks in a range may have no events
4. **Implement retries** — Use exponential backoff for transient errors
## Related Methods
- [**hl_getLatestBlockNumber**](./hl_getLatestBlockNumber) — Get the latest available block number
---
*Query HyperCore fill data with Dwellir's JSON-RPC API. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## hl_getLatestBlockNumber - Get Latest Block Number
# hl_getLatestBlockNumber
Return the highest block number currently available for a given stream.
## When to Use This Method
`hl_getLatestBlockNumber` is essential for:
- **Synchronization** — Determine the current head before fetching batch blocks
- **Polling** — Check for new blocks at regular intervals
- **Catch-up Logic** — Calculate how far behind your consumer is
- **Health Monitoring** — Verify the data pipeline is advancing
## Request
### Endpoint
```
POST https://api-hyperliquid-mainnet-jsonrpc.n.dwellir.com//hypercore
```
### Headers
| Header | Value | Required |
|--------|-------|----------|
| `Content-Type` | `application/json` | Yes |
### Parameters
This method accepts both positional and named parameters.
**Positional params:**
| Position | Type | Required | Description |
|----------|------|----------|-------------|
| `[0]` | string | Yes | Data stream. Must be `"trades"` |
**Named params:**
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `stream` | string | Yes | Data stream. Must be `"trades"` |
### Example Request (positional params)
```json
{
"jsonrpc": "2.0",
"method": "hl_getLatestBlockNumber",
"params": ["trades"],
"id": 1
}
```
### Example Request (named params)
```json
{
"jsonrpc": "2.0",
"method": "hl_getLatestBlockNumber",
"params": { "stream": "trades" },
"id": 1
}
```
## Response
### Success Response
```json
{
"jsonrpc": "2.0",
"result": 907628737,
"id": 1
}
```
The result is a bare integer representing the highest block number across all fill files.
### Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `result` | integer | The highest block number available for the stream |
### Error Response
```json
{
"jsonrpc": "2.0",
"error": { "code": -32602, "message": "unsupported stream" },
"id": 1
}
```
## Code Examples
```bash
curl -s https://api-hyperliquid-mainnet-jsonrpc.n.dwellir.com//hypercore \
-H 'Content-Type: application/json' \
-d '{
"jsonrpc": "2.0",
"method": "hl_getLatestBlockNumber",
"params": ["trades"],
"id": 1
}' | jq .
```
```javascript
const ENDPOINT = 'https://api-hyperliquid-mainnet-jsonrpc.n.dwellir.com//hypercore';
async function getLatestBlockNumber(stream = 'trades') {
const response = await fetch(ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'hl_getLatestBlockNumber',
params: [stream],
id: 1
})
});
const data = await response.json();
if (data.error) {
throw new Error(`JSON-RPC error ${data.error.code}: ${data.error.message}`);
}
return data.result;
}
// Usage
const latestBlock = await getLatestBlockNumber();
console.log(`Latest block: ${latestBlock}`);
```
```python
ENDPOINT = 'https://api-hyperliquid-mainnet-jsonrpc.n.dwellir.com//hypercore'
def get_latest_block_number(stream: str = 'trades') -> int:
"""Get the highest block number for the given stream."""
response = requests.post(
ENDPOINT,
json={
'jsonrpc': '2.0',
'method': 'hl_getLatestBlockNumber',
'params': [stream],
'id': 1
},
headers={'Content-Type': 'application/json'},
timeout=10
)
response.raise_for_status()
data = response.json()
if 'error' in data:
raise Exception(f"JSON-RPC error {data['error']['code']}: {data['error']['message']}")
return data['result']
# Usage
latest = get_latest_block_number()
print(f"Latest block: {latest}")
```
```go
package main
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
const Endpoint = "https://api-hyperliquid-mainnet-jsonrpc.n.dwellir.com//hypercore"
type JSONRPCRequest struct {
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params interface{} `json:"params"`
ID int `json:"id"`
}
type JSONRPCResponse struct {
JSONRPC string `json:"jsonrpc"`
Result int64 `json:"result"`
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"error,omitempty"`
ID int `json:"id"`
}
func getLatestBlockNumber() (int64, error) {
reqBody, _ := json.Marshal(JSONRPCRequest{
JSONRPC: "2.0",
Method: "hl_getLatestBlockNumber",
Params: []string{"trades"},
ID: 1,
})
resp, err := http.Post(Endpoint, "application/json", bytes.NewBuffer(reqBody))
if err != nil {
return 0, err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
var result JSONRPCResponse
if err := json.Unmarshal(body, &result); err != nil {
return 0, err
}
if result.Error != nil {
return 0, fmt.Errorf("JSON-RPC error %d: %s", result.Error.Code, result.Error.Message)
}
return result.Result, nil
}
func main() {
latest, err := getLatestBlockNumber()
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Latest block: %d\n", latest)
}
```
## Common Use Cases
### 1. Poll for New Blocks
Check for new data at regular intervals:
```javascript
async function pollForNewBlocks(callback, intervalMs = 5000) {
let lastSeen = await getLatestBlockNumber();
console.log(`Starting poll from block ${lastSeen}`);
setInterval(async () => {
const latest = await getLatestBlockNumber();
if (latest > lastSeen) {
console.log(`New blocks: ${lastSeen + 1} to ${latest}`);
callback(lastSeen + 1, latest);
lastSeen = latest;
}
}, intervalMs);
}
// Usage
pollForNewBlocks((from, to) => {
console.log(`Processing blocks ${from}–${to}`);
});
```
### 2. Calculate Consumer Lag
Monitor how far behind a consumer is:
```python
def check_lag(consumer_block: int) -> dict:
latest = get_latest_block_number()
lag = latest - consumer_block
return {
'consumer_block': consumer_block,
'latest_block': latest,
'lag_blocks': lag,
'status': 'healthy' if lag < 100 else 'behind'
}
```
## Error Handling
| Error Code | Cause | Solution |
|------------|-------|----------|
| -32602 | Unsupported stream | Use `"trades"` as the stream value |
| -32600 | Array-wrapped request | Send a single JSON-RPC object, not an array |
| -32700 | Malformed JSON | Validate your request JSON |
## Best Practices
1. **Poll responsibly** — Don't poll more frequently than every few seconds
2. **Use as a cursor** — Combine with `hl_getBatchBlocks` for sequential data retrieval
3. **Monitor lag** — Track the difference between your consumer position and the latest block
4. **Handle stale data** — If the latest block number hasn't advanced, the upstream may be paused
## Related Methods
- [**hl_getBatchBlocks**](./hl_getBatchBlocks) — Retrieve fill blocks in a range
---
*Query HyperCore fill data with Dwellir's JSON-RPC API. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## HyperCore JSON-RPC API
Dwellir provides a JSON-RPC 2.0 HTTP endpoint for querying HyperCore fill data. The API serves trade fill blocks with wire-level compatibility, so existing client code works unmodified.
## Endpoint
```
POST https://api-hyperliquid-mainnet-jsonrpc.n.dwellir.com//hypercore
```
All requests use standard JSON-RPC 2.0 over HTTP with `Content-Type: application/json`.
## Available Methods
| Method | Description |
|--------|-------------|
| [**hl_getBatchBlocks**](./hl_getBatchBlocks) | Return fill blocks in a `[from, to]` range for a given stream |
| [**hl_getLatestBlockNumber**](./hl_getLatestBlockNumber) | Return the highest block number for a given stream |
### hl_getBatchBlocks
Retrieve a batch of fill blocks for a specified range. Each block contains trade events with timestamps and fill details.
**Ideal for:**
- Backfilling historical trade data
- Batch processing fill events
- Building trade analytics pipelines
[**View hl_getBatchBlocks Documentation →**](./hl_getBatchBlocks)
### hl_getLatestBlockNumber
Get the highest block number currently available for a stream. Use this to determine the current head before fetching batch blocks.
**Ideal for:**
- Discovering the latest available data
- Polling for new blocks
- Synchronization and catch-up logic
[**View hl_getLatestBlockNumber Documentation →**](./hl_getLatestBlockNumber)
## Supported Streams
Currently only the `trades` stream is implemented. The upstream API also defines streams for orders, book updates, TWAP, events, and writer actions; these may be added in the future.
## Error Codes
Standard JSON-RPC 2.0 error codes are used:
| Code | Meaning |
|------|---------|
| -32700 | Parse error |
| -32600 | Invalid request |
| -32601 | Method not found |
| -32602 | Invalid params |
| -32603 | Internal error |
## Constraints
- **No batches** — Array-wrapped requests are rejected (`-32600`)
- **No notifications** — An `id` field (string or number) is required
- **Body limit** — 8 KiB max request body
- **Timeouts** — Each request gets a 30 s context deadline
---
*Query HyperCore fill data with Dwellir's JSON-RPC API. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## net_listening - Hyperliquid RPC Method
# net_listening
Returns `true` if client is actively listening for network connections on Hyperliquid.
## 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-hyperliquid-mainnet-evm.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-hyperliquid-mainnet-evm.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 - Hyperliquid RPC Method
# net_peerCount
Returns number of peers currently connected to Hyperliquid 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-hyperliquid-mainnet-evm.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-hyperliquid-mainnet-evm.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 - Hyperliquid RPC Method
# net_version
Returns the current network ID on Hyperliquid.
## 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-hyperliquid-mainnet-evm.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-hyperliquid-mainnet-evm.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
---
## Hyperliquid Order Book WebSocket API
Dwellir provides a high-performance WebSocket server delivering real-time order book data from Hyperliquid with ultra-low latency. This service offers direct node connectivity, significantly faster than public API endpoints.
:::tip Estimate Your Usage
Not sure which plan fits your trading strategy? Use our [**Volume Calculator**](https://www.dwellir.com/hyperliquid-orderbook#calculator) to estimate monthly message volume and get a personalized pricing recommendation.
:::
## Watch the WebSocket Walkthrough
VIDEO
## Available Subscription Types
The WebSocket API provides three distinct data streams, each designed for specific use cases:
| Subscription | Data Type | Best For |
|--------------|-----------|----------|
| [**Trades**](/hyperliquid/trades) | Real-time trade executions | Trade flow analysis, VWAP calculation, execution monitoring |
| [**L2 Order Book**](./l2-book) | Aggregated price levels | Spread analysis, market making, liquidity assessment |
| [**L4 Order Book**](./l4-book) | Individual orders | Queue position tracking, whale watching, microstructure analysis |
### Trades Stream
Stream real-time trade executions as they occur on Hyperliquid. Each trade includes price, size, direction, and participant addresses.
**Ideal for:**
- Volume-weighted average price (VWAP) calculations
- Trade flow and momentum analysis
- Execution quality monitoring
- Historical trade data collection
[**View Trades Documentation →**](/hyperliquid/trades)
### L2 Order Book (Level 2)
Aggregated order book data showing total size at each price level. Supports configurable depth and price aggregation for bandwidth optimization.
**Ideal for:**
- Bid-ask spread monitoring
- Market making strategies
- Liquidity depth analysis
- Support/resistance level detection
[**View L2 Order Book Documentation →**](./l2-book)
### L4 Order Book (Level 4)
The most detailed market data available - individual order visibility with user addresses, order IDs, timestamps, and full order parameters.
**Ideal for:**
- Queue position optimization
- Whale wallet tracking
- Market microstructure research
- Order flow toxicity analysis
[**View L4 Order Book Documentation →**](./l4-book)
## Data Flow Between Channels
The three subscription types serve different purposes and contain different data. Understanding which data lives where prevents common integration pitfalls.
```
Hyperliquid Node
|
|-- order_statuses --> L4 Book channel (status transitions: open, filled, canceled)
|-- book_diffs ------> L4 Book channel (order additions, removals, size changes)
|-- fills -----------> Trades channel (execution price, size, hash, wallets)
| L2 Book channel (aggregated from book state)
```
**Key point:** Individual fill details (execution price, counterparty, transaction hash) are only available on the **Trades** stream. The L4 Book channel reports order status changes but not per-fill data. To track an order from placement through each fill to completion, subscribe to both L4 Book and Trades.
For a detailed walkthrough, see [Understanding Order Data Flow](./l4-book#understanding-order-data-flow) in the L4 Book documentation.
## Key Features
- **Ultra-low latency** - Direct node connectivity eliminates public API overhead
- **Full market depth** - Access to L4 data with individual order visibility
- **Real-time streaming** - WebSocket push model for immediate updates
- **Efficient compression** - Optimized bandwidth usage for high-frequency data
- **Institutional grade** - Professional infrastructure with monitoring and support
## Performance Benchmarks
Based on real-world benchmarking of 2,662 matched trades:
| Metric | Public API | Dwellir WebSocket | Improvement |
|--------|------------|-------------------|-------------|
| Median Latency | 263ms | 212ms | **51ms faster (24%)** |
| Mean Latency | 368ms | 339ms | 29ms faster (8%) |
| Max Latency | 9,118ms | 1,977ms | 7,141ms faster |
**Win rate**: WebSocket delivers data faster in **75.5%** of cases.
## Quick Start
Connect to the WebSocket endpoint and subscribe to your desired data streams:
```
wss://.dwellir.com/ws
```
```python
async def main():
ws_url = "wss://your-instance.dwellir.com/ws"
async with websockets.connect(ws_url) as websocket:
# Subscribe to BTC trades
await websocket.send(json.dumps({
"method": "subscribe",
"subscription": {"type": "trades", "coin": "BTC"}
}))
# Listen for messages
async for message in websocket:
data = json.loads(message)
print(f"Received: {data}")
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const WebSocket = require('ws');
const ws = new WebSocket('wss://your-instance.dwellir.com/ws');
ws.on('open', () => {
// Subscribe to BTC trades
ws.send(JSON.stringify({
method: 'subscribe',
subscription: { type: 'trades', coin: 'BTC' }
}));
});
ws.on('message', (data) => {
const message = JSON.parse(data);
console.log('Received:', message);
});
```
:::tip Code Examples Repository
Clone our complete examples: [github.com/dwellir-public/hyperliquid-orderbook-server-code-examples](https://github.com/dwellir-public/hyperliquid-orderbook-server-code-examples)
:::
## Message Protocol
### Subscribe to Data Stream
```json
{
"method": "subscribe",
"subscription": {
"type": "trades", // or "l2Book" or "l4Book"
"coin": "BTC"
// Additional parameters vary by type
}
}
```
### Unsubscribe from Data Stream
```json
{
"method": "unsubscribe",
"subscription": {
// Same subscription object used to subscribe
}
}
```
### Server Responses
**Subscription Confirmation:**
```json
{
"channel": "subscriptionResponse",
"data": {
"method": "subscribe",
"subscription": { /* echoed subscription */ }
}
}
```
**Error Messages:**
```json
{
"channel": "error",
"data": "Descriptive error message"
}
```
Common errors include: `"coin not found"`, `"n_levels too high"`, `"Already subscribed"`, `"Order book not ready"`.
## Use Cases by Industry
### Quantitative Trading
| Use Case | Recommended Stream | Why |
|----------|-------------------|-----|
| High-frequency trading | L4 Book | Queue position optimization |
| Statistical arbitrage | L2 Book + Trades | Cross-market spread analysis |
| Momentum strategies | Trades | Trade flow direction |
### Market Making
| Use Case | Recommended Stream | Why |
|----------|-------------------|-----|
| Spread management | L2 Book | Real-time bid/ask monitoring |
| Inventory risk | L4 Book | See competing orders |
| Quote adjustment | Trades | Execution feedback |
### Analytics & Research
| Use Case | Recommended Stream | Why |
|----------|-------------------|-----|
| Market microstructure | L4 Book | Individual order analysis |
| Liquidity studies | L2 Book | Depth at price levels |
| Volume analysis | Trades | Complete trade history |
## Connection Best Practices
:::warning Implement Reconnection Logic
The server may restart occasionally to resync order book state. Your client **must** include automatic reconnection with exponential backoff.
:::
:::info Initial Connection Behavior
During the first few seconds after connecting, the WebSocket handshake and subscription setup may cause a brief delay before data starts flowing. If you compare streams from two different endpoints, trades observed by one source but not the other in the first 5-10 seconds are due to connection timing, not event loss. After the initial handshake period, both streams deliver identical data.
:::
```python
class RobustWSClient:
def __init__(self, ws_url):
self.ws_url = ws_url
self.reconnect_delay = 1
self.max_delay = 60
async def connect_with_retry(self):
while True:
try:
async with websockets.connect(self.ws_url) as ws:
self.reconnect_delay = 1 # Reset on success
await self.handle_connection(ws)
except Exception as e:
print(f"Connection error: {e}")
await asyncio.sleep(self.reconnect_delay)
self.reconnect_delay = min(self.reconnect_delay * 2, self.max_delay)
```
## Get Started
### Hosted WebSocket Service
Dwellir offers production-ready WebSocket servers with:
- **Direct node connectivity** - Fastest possible data access
- **Geographic distribution** - Servers in Singapore and Tokyo
- **99.99% uptime SLA** - Enterprise reliability
- **Dedicated support** - Direct access to engineering team
### Resources
- **[Volume Calculator](https://www.dwellir.com/hyperliquid-orderbook#calculator)** - Estimate your monthly usage
- **[Code Examples](https://github.com/dwellir-public/hyperliquid-orderbook-server-code-examples)** - Production-ready implementations
- **[Pricing](https://www.dwellir.com/hyperliquid-orderbook)** - Plans for every scale
### Contact Us
Ready to integrate ultra-low latency Hyperliquid data?
- **Email**: ben@dwellir.com
- **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com)
---
*Access institutional-grade Hyperliquid market data with Dwellir's ultra-low latency WebSocket infrastructure.*
---
## L2 Order Book - Aggregated Price Levels
# L2 Order Book (Level 2)
Stream aggregated order book data showing total size at each price level. The L2 book provides a consolidated view of market depth, with configurable levels and price aggregation for bandwidth optimization.
:::tip Code Examples Repository
Clone our complete examples: [github.com/dwellir-public/hyperliquid-orderbook-server-code-examples](https://github.com/dwellir-public/hyperliquid-orderbook-server-code-examples)
:::
## How to Subscribe
Send a subscription message to the WebSocket endpoint:
```json
{
"method": "subscribe",
"subscription": {
"type": "l2Book",
"coin": "BTC",
"nSigFigs": 5,
"nLevels": 20,
"strict": true
}
}
```
### Subscription Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `type` | string | Yes | - | Must be `"l2Book"` |
| `coin` | string | Yes | - | Trading pair symbol (e.g., `"BTC"`, `"ETH"`, `"xyz:MSTR"`, `"@150"`) |
| `nSigFigs` | number | No | 5 | Price aggregation: 2-5 significant figures |
| `nLevels` | number | No | 20 | Number of levels per side: 1-100 |
| `strict` | bool | No | False | Only send data on updates within the subscribed level interval |
:::info HIP3 Markets
For HIP3 (permissionless perpetuals) markets, use the full coin label format with the `xyz:` prefix. For example, use `"xyz:MSTR"` for the MicroStrategy perpetual, not just `"MSTR"`. Standard perpetuals like BTC and ETH do not require a prefix.
:::
:::info Spot Markets
For spot markets, use the `@{index}` format where the index is the spot asset index. For example, use `"@150"` for a specific spot market.
:::
### Understanding `nSigFigs` (Price Aggregation)
The `nSigFigs` parameter controls how prices are rounded for aggregation:
| nSigFigs | BTC Example | Effect |
|----------|-------------|--------|
| 5 | $106,217 | Most granular - individual price points |
| 4 | $106,200 | Moderate aggregation |
| 3 | $106,000 | Coarse aggregation |
| 2 | $110,000 | Very coarse - major levels only |
Lower `nSigFigs` values reduce message frequency and bandwidth but sacrifice price precision.
## Sample Response
```json
{
"channel": "l2Book",
"data": {
"coin": "BTC",
"time": 1767878802704,
"levels": [
[
{"px": "90057", "sz": "5.34526", "n": 25},
{"px": "90056", "sz": "0.01336", "n": 4},
{"px": "90055", "sz": "0.33772", "n": 5},
{"px": "90054", "sz": "0.01859", "n": 2},
{"px": "90053", "sz": "0.08936", "n": 2}
],
[
{"px": "90058", "sz": "7.46316", "n": 18},
{"px": "90059", "sz": "0.44694", "n": 5},
{"px": "90060", "sz": "0.00013", "n": 1},
{"px": "90061", "sz": "0.05576", "n": 3},
{"px": "90062", "sz": "0.9716", "n": 3}
]
]
}
}
```
In this example:
- **Best bid**: $90,057 with 5.34526 BTC across 25 orders
- **Best ask**: $90,058 with 7.46316 BTC across 18 orders
- **Spread**: $1 (approximately 1.1 basis points)
## Response Field Reference
| Field | Type | Description |
|-------|------|-------------|
| `channel` | string | Always `"l2Book"` for this subscription type |
| `data.coin` | string | Trading pair symbol |
| `data.time` | number | Unix timestamp in milliseconds |
| `data.levels` | array | Two-element array: `[bids, asks]` |
| `levels[0]` | array | Bid levels (buyers), sorted best (highest) to worst |
| `levels[1]` | array | Ask levels (sellers), sorted best (lowest) to worst |
### Level Object Fields
| Field | Type | Description |
|-------|------|-------------|
| `px` | string | Price level |
| `sz` | string | Total size at this price level |
| `n` | number | Number of orders aggregated at this level |
## Code Examples
```python
#!/usr/bin/env python3
"""
L2 Order Book Stream - Aggregated price levels with spread display
"""
def display_orderbook(data):
"""Display the order book with spread calculation"""
if data.get("channel") != "l2Book":
return
coin = data["data"]["coin"]
levels = data["data"]["levels"]
bids = levels[0]
asks = levels[1]
print(f"\n{'='*55}")
print(f"{coin} Order Book")
print(f"{'='*55}")
# Display asks (sellers) - reverse for visual display
print("\nASKS (Sellers)")
print(f"{'Price':<15} {'Size':<15} {'Orders':<10}")
print("-" * 55)
for ask in reversed(asks[:5]):
print(f"${ask['px']:<14} {ask['sz']:<15} {ask['n']:<10}")
# Calculate and display spread
if bids and asks:
best_bid = float(bids[0]['px'])
best_ask = float(asks[0]['px'])
spread = best_ask - best_bid
spread_bps = (spread / best_bid) * 10000
print(f"\n{'─'*55}")
print(f"Spread: ${spread:.2f} ({spread_bps:.1f} bps)")
print(f"{'─'*55}\n")
# Display bids (buyers)
print("BIDS (Buyers)")
print(f"{'Price':<15} {'Size':<15} {'Orders':<10}")
print("-" * 55)
for bid in bids[:5]:
print(f"${bid['px']:<14} {bid['sz']:<15} {bid['n']:<10}")
async def stream_l2_book():
ws_url = "wss://your-instance.dwellir.com/ws"
async with websockets.connect(ws_url) as websocket:
# Subscribe to ETH L2 order book
await websocket.send(json.dumps({
"method": "subscribe",
"subscription": {
"type": "l2Book",
"coin": "ETH",
"nLevels": 10,
"nSigFigs": 5,
"strict": True
}
}))
print("Subscribed to ETH L2 order book")
async for message in websocket:
data = json.loads(message)
display_orderbook(data)
if __name__ == "__main__":
asyncio.run(stream_l2_book())
```
```javascript
const WebSocket = require('ws');
const wsUrl = 'wss://your-instance.dwellir.com/ws';
const ws = new WebSocket(wsUrl);
ws.on('open', () => {
// Subscribe to ETH L2 order book
ws.send(JSON.stringify({
method: 'subscribe',
subscription: {
type: 'l2Book',
coin: 'ETH',
nLevels: 10,
nSigFigs: 5
}
}));
console.log('Subscribed to ETH L2 order book\n');
});
ws.on('message', (rawData) => {
const data = JSON.parse(rawData);
if (data.channel === 'l2Book') {
displayOrderBook(data.data);
}
});
function displayOrderBook(bookData) {
const { coin, levels } = bookData;
const [bids, asks] = levels;
console.log(`\n${'='.repeat(55)}`);
console.log(`${coin} Order Book`);
console.log('='.repeat(55));
// Display asks (reversed)
console.log('\nASKS (Sellers)');
console.log(`${'Price'.padEnd(15)} ${'Size'.padEnd(15)} ${'Orders'.padEnd(10)}`);
console.log('-'.repeat(55));
asks.slice(0, 5).reverse().forEach(ask => {
console.log(`$${ask.px.padEnd(14)} ${ask.sz.padEnd(15)} ${String(ask.n).padEnd(10)}`);
});
// Calculate spread
if (bids.length && asks.length) {
const bestBid = parseFloat(bids[0].px);
const bestAsk = parseFloat(asks[0].px);
const spread = bestAsk - bestBid;
const spreadBps = (spread / bestBid) * 10000;
console.log(`\n${'-'.repeat(55)}`);
console.log(`Spread: $${spread.toFixed(2)} (${spreadBps.toFixed(1)} bps)`);
console.log('-'.repeat(55) + '\n');
}
// Display bids
console.log('BIDS (Buyers)');
console.log(`${'Price'.padEnd(15)} ${'Size'.padEnd(15)} ${'Orders'.padEnd(10)}`);
console.log('-'.repeat(55));
bids.slice(0, 5).forEach(bid => {
console.log(`$${bid.px.padEnd(14)} ${bid.sz.padEnd(15)} ${String(bid.n).padEnd(10)}`);
});
}
ws.on('error', (error) => console.error('WebSocket error:', error));
```
```go
package main
"encoding/json"
"fmt"
"log"
"strconv"
"github.com/gorilla/websocket"
)
type L2BookMessage struct {
Channel string `json:"channel"`
Data struct {
Coin string `json:"coin"`
Time int64 `json:"time"`
Levels [][]L2Level `json:"levels"`
} `json:"data"`
}
type L2Level struct {
Px string `json:"px"`
Sz string `json:"sz"`
N int `json:"n"`
}
func main() {
wsURL := "wss://your-instance.dwellir.com/ws"
conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer conn.Close()
// Subscribe to ETH L2 order book
subscription := map[string]interface{}{
"method": "subscribe",
"subscription": map[string]interface{}{
"type": "l2Book",
"coin": "ETH",
"nLevels": 10,
"nSigFigs": 5,
},
}
conn.WriteJSON(subscription)
fmt.Println("Subscribed to ETH L2 order book\n")
for {
_, message, err := conn.ReadMessage()
if err != nil {
log.Println("Read error:", err)
return
}
var bookMsg L2BookMessage
if err := json.Unmarshal(message, &bookMsg); err != nil {
continue
}
if bookMsg.Channel == "l2Book" {
displayOrderBook(bookMsg.Data.Coin, bookMsg.Data.Levels)
}
}
}
func displayOrderBook(coin string, levels [][]L2Level) {
if len(levels) < 2 {
return
}
bids := levels[0]
asks := levels[1]
fmt.Printf("\n%s\n%s Order Book\n%s\n",
"=======================================================",
coin,
"=======================================================")
// Calculate spread
if len(bids) > 0 && len(asks) > 0 {
bestBid, _ := strconv.ParseFloat(bids[0].Px, 64)
bestAsk, _ := strconv.ParseFloat(asks[0].Px, 64)
spread := bestAsk - bestBid
spreadBps := (spread / bestBid) * 10000
fmt.Printf("Best Bid: $%.2f | Best Ask: $%.2f | Spread: $%.2f (%.1f bps)\n\n",
bestBid, bestAsk, spread, spreadBps)
}
}
```
### Liquidity Depth Calculator
Calculate total liquidity within a price range:
```python
class LiquidityAnalyzer:
def __init__(self):
self.current_book = None
def update(self, book_data):
self.current_book = book_data
def get_liquidity_within_percent(self, percent):
"""Calculate total liquidity within X% of mid price"""
if not self.current_book:
return None
levels = self.current_book["levels"]
bids, asks = levels[0], levels[1]
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
threshold = mid_price * (percent / 100)
upper_bound = mid_price + threshold
lower_bound = mid_price - threshold
bid_liquidity = sum(
float(b['sz']) for b in bids
if float(b['px']) >= lower_bound
)
ask_liquidity = sum(
float(a['sz']) for a in asks
if float(a['px']) <= upper_bound
)
return {
'bid_liquidity': bid_liquidity,
'ask_liquidity': ask_liquidity,
'total_liquidity': bid_liquidity + ask_liquidity,
'imbalance': bid_liquidity / ask_liquidity if ask_liquidity > 0 else float('inf')
}
def get_depth_at_price(self, side, price_levels=5):
"""Get cumulative depth for top N price levels"""
if not self.current_book:
return []
levels = self.current_book["levels"]
book_side = levels[0] if side == 'bid' else levels[1]
cumulative = 0
depth = []
for level in book_side[:price_levels]:
cumulative += float(level['sz'])
depth.append({
'price': level['px'],
'size': level['sz'],
'cumulative': cumulative,
'orders': level['n']
})
return depth
```
### Order Book Imbalance Signal
Detect buying/selling pressure from book shape:
```python
def calculate_imbalance(bids, asks, levels=5):
"""
Calculate order book imbalance.
Returns value from -1 (all asks) to +1 (all bids)
"""
bid_volume = sum(float(b['sz']) for b in bids[:levels])
ask_volume = sum(float(a['sz']) for a in asks[:levels])
total = bid_volume + ask_volume
if total == 0:
return 0
return (bid_volume - ask_volume) / total
def get_imbalance_signal(imbalance):
"""Convert imbalance to trading signal"""
if imbalance > 0.3:
return "STRONG_BUY"
elif imbalance > 0.1:
return "BUY"
elif imbalance < -0.3:
return "STRONG_SELL"
elif imbalance < -0.1:
return "SELL"
return "NEUTRAL"
```
## Use Cases
### Market Making
Monitor spread and depth to optimize quote placement:
- **Spread monitoring**: Track bid-ask spread for quote width
- **Inventory management**: Adjust quotes based on book imbalance
- **Competition analysis**: Count orders at each level to gauge competition
### Liquidity Analysis
Assess market depth for large order execution:
- **Slippage estimation**: Calculate expected price impact for order sizes
- **Best execution**: Find optimal order sizes and timing
- **Market quality metrics**: Track spread, depth, and resilience
### Support/Resistance Detection
Identify significant price levels from order concentration:
- **Order clusters**: Large `n` values indicate many orders at a level
- **Size walls**: High `sz` values suggest strong support/resistance
- **Level breaks**: Monitor when significant levels get absorbed
### Algorithmic Trading Signals
Generate trading signals from book dynamics:
- **Imbalance signals**: Buy when bids dominate, sell when asks dominate
- **Spread compression**: Trade when spread narrows (high liquidity)
- **Depth changes**: Alert on sudden liquidity additions or removals
## Subscription Management
### Adjusting Parameters
Change depth or aggregation by resubscribing:
```python
# Switch from 20 levels to 50 levels
await websocket.send(json.dumps({
"method": "unsubscribe",
"subscription": {"type": "l2Book", "coin": "BTC", "nLevels": 20}
}))
await websocket.send(json.dumps({
"method": "subscribe",
"subscription": {"type": "l2Book", "coin": "BTC", "nLevels": 50}
}))
```
### Bandwidth Optimization
For high-frequency updates, use lower `nSigFigs`:
```json
{
"method": "subscribe",
"subscription": {
"type": "l2Book",
"coin": "BTC",
"nSigFigs": 3,
"nLevels": 10
}
}
```
This reduces message size and frequency while maintaining key price levels.
## Get Access
Ready to integrate real-time Hyperliquid L2 order book data?
- **[Volume Calculator](https://www.dwellir.com/hyperliquid-orderbook#calculator)** - Estimate monthly message volume
- **[Contact Sales](mailto:ben@dwellir.com)** - Get your WebSocket credentials
- **[Dashboard](https://dashboard.dwellir.com)** - Manage your subscription
---
*Stream institutional-grade Hyperliquid order book data with Dwellir's ultra-low latency infrastructure.*
---
## L4 Order Book - Individual Order Visibility
# L4 Order Book (Level 4)
The most detailed market data available - individual order visibility with user wallet addresses, order IDs, timestamps, and full order parameters. L4 data enables queue position tracking, whale watching, and advanced market microstructure analysis.
:::tip Code Examples Repository
Clone our complete examples: [github.com/dwellir-public/hyperliquid-orderbook-server-code-examples](https://github.com/dwellir-public/hyperliquid-orderbook-server-code-examples)
:::
## How to Subscribe
Send a subscription message to the WebSocket endpoint:
```json
{
"method": "subscribe",
"subscription": {
"type": "l4Book",
"coin": "BTC"
}
}
```
### Subscription Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | string | Yes | Must be `"l4Book"` |
| `coin` | string | Yes | Trading pair symbol (e.g., `"BTC"`, `"ETH"`, `"xyz:MSTR"`, `"@150"`) |
:::info HIP3 Markets
For HIP3 (permissionless perpetuals) markets, use the full coin label format with the `xyz:` prefix. For example, use `"xyz:MSTR"` for the MicroStrategy perpetual, not just `"MSTR"`. Standard perpetuals like BTC and ETH do not require a prefix.
:::
:::info Spot Markets
For spot markets, use the `@{index}` format where the index is the spot asset index. For example, use `"@150"` for a specific spot market.
:::
Unlike L2, L4 subscriptions do not support `nLevels` or `nSigFigs` - you receive the complete order book with all individual orders.
## Message Types
L4 subscriptions produce two types of messages:
1. **Initial Snapshot** - Complete order book state when you subscribe
2. **Incremental Updates** - Changes as orders are placed, modified, or filled
### Initial Snapshot Response
When you first subscribe, you receive a complete snapshot of the order book wrapped in a `Snapshot` object:
```json
{
"channel": "l4Book",
"data": {
"Snapshot": {
"coin": "BTC",
"height": 854890775,
"levels": [
[
{
"user": "0xf9109ada2f73c62e9889b45453065f0d99260a2d",
"coin": "BTC",
"side": "B",
"limitPx": "90057",
"sz": "0.33289",
"oid": 289682065711,
"timestamp": 1767878782721,
"triggerCondition": "N/A",
"isTrigger": false,
"triggerPx": "0.0",
"isPositionTpsl": false,
"reduceOnly": false,
"orderType": "Limit",
"tif": "Alo",
"cloid": "0x4c4617dbd8b94d358285c5c6d5a43df3"
}
],
[
{
"user": "0x13558be785661958932ceac35ba20de187275a42",
"coin": "BTC",
"side": "A",
"limitPx": "90058",
"sz": "0.37634",
"oid": 289682176026,
"timestamp": 1767878800615,
"triggerCondition": "N/A",
"isTrigger": false,
"triggerPx": "0.0",
"isPositionTpsl": false,
"reduceOnly": false,
"orderType": "Limit",
"tif": "Alo",
"cloid": "0x000000000814768000001999b6671c90"
}
]
]
}
}
}
```
:::note Snapshot Size
A full BTC order book snapshot typically contains 20,000-40,000+ orders and can exceed 5 MB. The example above shows one order per side for brevity. Many WebSocket libraries default to a 1 MB message limit. If your connection closes immediately after subscribing, increase the maximum message size (e.g., `max_size=50 * 1024 * 1024` in Python's `websockets` library).
:::
### Incremental Update Response
After the initial snapshot, you receive incremental updates wrapped in an `Updates` object containing [`order_statuses`](#orderstatus-object-in-order_statuses-array) and [`book_diffs`](#bookdiff-object-in-book_diffs-array).
**Example 1: New Order**
This example shows a new order being added to the book:
```json
{
"channel": "l4Book",
"data": {
"Updates": {
"time": 1767878802703,
"height": 854890776,
"order_statuses": [
{
"time": "2026-01-08T13:26:42.703377851",
"user": "0xbc927e87d072dfac3693846a83fa6922cc6c5f2a",
"status": "open",
"order": {
"user": null,
"coin": "BTC",
"side": "B",
"limitPx": "90056.0",
"sz": "0.00014",
"oid": 289682192129,
"timestamp": 1767878802703,
"triggerCondition": "N/A",
"isTrigger": false,
"triggerPx": "0.0",
"isPositionTpsl": false,
"reduceOnly": false,
"orderType": "Limit",
"tif": "Alo",
"cloid": "0xa097c34ee13a42a1afeed2a5ce96b413"
}
}
],
"book_diffs": [
{
"user": "0xbc927e87d072dfac3693846a83fa6922cc6c5f2a",
"oid": 289682192129,
"px": "90056.0",
"coin": "BTC",
"raw_book_diff": {
"new": {
"sz": "0.00014"
}
}
}
]
}
}
}
```
**Example 2: Order Size Update (Partial Fill)**
This example shows an existing order being partially filled, with the size decreasing from 108.65 to 107.5:
```json
{
"channel": "l4Book",
"data": {
"Updates": {
"time": 1767878902834,
"height": 854890880,
"order_statuses": [],
"book_diffs": [
{
"user": "0x97991003fd631e2923f40cab2a4fdc35e60dc807",
"oid": 316542552323,
"px": "84.371",
"coin": "SOL",
"raw_book_diff": {
"update": {
"origSz": "108.65",
"newSz": "107.5"
}
}
}
]
}
}
}
```
In this update:
- The order at price `84.371` was partially filled
- Original size (`origSz`): `108.65` SOL
- New remaining size (`newSz`): `107.5` SOL
## Response Field Reference
This section provides a detailed breakdown of all fields in L4 messages. For specific field values like order statuses, see [Order Status Values](#order-status-values).
All L4 messages follow this top-level structure:
```typescript
{
channel: "l4Book",
data: Snapshot | Updates
}
```
### Message Type 1: Snapshot (Initial State)
**Structure:** `{ channel: "l4Book", data: { Snapshot: {...} } }`
Received once when you first subscribe. Contains the complete order book state.
#### Snapshot Object
| Field | Type | Description |
|-------|------|-------------|
| `coin` | `string` | Trading pair symbol (e.g., `"BTC"`, `"ETH"`, `"xyz:MSTR"`, `"@150"`) |
| `height` | `number` | Hyperliquid block height |
| `levels` | `[Order[], Order[]]` | Two-element array: `[bids, asks]`. Each element is an array of Order objects. |
#### Order Object (in `levels` arrays)
Each order in the `levels[0]` (bids) and `levels[1]` (asks) arrays contains:
| Field | Type | Description |
|-------|------|-------------|
| `user` | `string` | Wallet address of order owner (e.g., `"0xf9109ada..."`) |
| `coin` | `string` | Trading pair (e.g., `"BTC"`) |
| `side` | `"B" \| "A"` | `"B"` = Bid (buy), `"A"` = Ask (sell) |
| `limitPx` | `string` | Limit price (e.g., `"90057"`) |
| `sz` | `string` | Remaining order size (e.g., `"0.33289"`) |
| `oid` | `number` | Unique order ID (e.g., `289682065711`) |
| `timestamp` | `number` | Order placement time in Unix milliseconds (e.g., `1767878782721`) |
| `triggerCondition` | `string` | Trigger condition type, or `"N/A"` if not a trigger order |
| `isTrigger` | `boolean` | Whether this is a trigger/stop order |
| `triggerPx` | `string` | Trigger price, or `"0.0"` if not a trigger order |
| `isPositionTpsl` | `boolean` | Whether this is a position take-profit/stop-loss order |
| `reduceOnly` | `boolean` | Whether order can only reduce position |
| `orderType` | `string` | Order type: `"Limit"`, `"Market"`, `"Stop Market"`, `"Stop Limit"`, `"Scale"`, `"TWAP"` |
| `tif` | `"Gtc" \| "Ioc" \| "Alo"` | Time-in-force: `"Gtc"` (Good til Cancel), `"Ioc"` (Immediate or Cancel), `"Alo"` (Add Liquidity Only) |
| `cloid` | `string` | Client order ID - hex string provided by user (e.g., `"0x4c4617dbd8b94d35..."`) |
### Message Type 2: Updates (Incremental Changes)
**Structure:** `{ channel: "l4Book", data: { Updates: {...} } }`
Received continuously after the snapshot. Contains incremental changes to the order book.
#### Updates Object
| Field | Type | Description |
|-------|------|-------------|
| `time` | `number` | Unix timestamp in milliseconds (e.g., `1767878802703`) |
| `height` | `number` | Hyperliquid block height - increments with each update |
| `order_statuses` | `OrderStatus[]` | Array of [order status changes](#orderstatus-object-in-order_statuses-array) (new orders, fills, cancellations, rejections). See [Order Status Values](#order-status-values) for status meanings. |
| `book_diffs` | `BookDiff[]` | Array of [order book modifications](#bookdiff-object-in-book_diffs-array) (additions, removals, size changes) |
:::warning L4 Book does not include individual fill details
The `order_statuses` array contains **status transitions** (open, filled, canceled), not per-fill execution data. To get individual fill details (price, size, counterparty), subscribe to the [Trades stream](/hyperliquid/trades) and correlate using `oid`. See [Understanding Order Data Flow](#understanding-order-data-flow) for details.
:::
#### OrderStatus Object (in `order_statuses` array)
| Field | Type | Description |
|-------|------|-------------|
| `time` | `string` | ISO-8601 timestamp with nanosecond precision (e.g., `"2026-01-08T13:26:42.703377851"`) |
| `user` | `string` | Wallet address of order owner |
| `status` | `string` | Order status: `"open"`, `"filled"`, `"canceled"`, `"badAloPxRejected"`, etc. See [Order Status Values](#order-status-values) for all possible values and their meanings. |
| `order` | `Order` | Order object with same structure as [Order Object](#order-object-in-levels-arrays) above (but `user` field may be `null`) |
#### BookDiff Object (in `book_diffs` array)
The `book_diffs` array contains changes to individual orders in the book. Each diff describes what happened to a specific order - whether it was added (`new`), partially filled (`update`), modified (`modified`), or removed (`remove`).
**Common fields present in all diff types:**
| Field | Type | Description |
|-------|------|-------------|
| `user` | `string` | Wallet address of order owner (e.g., `"0xbc927e87..."`) |
| `oid` | `number` | Unique order ID being modified (e.g., `289682192129`) |
| `px` | `string` | Price level where order exists/existed (e.g., `"90056.0"`) |
| `coin` | `string` | Trading pair (e.g., `"BTC"`) |
| `raw_book_diff` | `NewDiff \| UpdateDiff \| ModifiedDiff \| "remove"` | Describes what changed. Can be: `{ new: { sz } }` for new orders, `{ update: { origSz, newSz } }` for partial fills, `{ modified: { sz } }` for amendments, or `"remove"` for cancellations/complete fills. See [BookDiff Types](#bookdiff-types-the-raw_book_diff-field) below for detailed specifications. |
### BookDiff Types (the `raw_book_diff` field)
The `raw_book_diff` field indicates what happened to an order. It can take four forms:
| Type | TypeScript Definition | Description |
|------|----------------------|-------------|
| **NewDiff** | `{ new: { sz: string } }` | New order added to the book. The `sz` field contains the order size. Reference the corresponding entry in [`order_statuses`](#orderstatus-object-in-order_statuses-array) with matching `oid` to get full order details (side, tif, etc.). |
| **RemoveDiff** | `"remove"` | Order completely removed from book. Can occur due to: full fill (check [`order_statuses`](#orderstatus-object-in-order_statuses-array) for [`filled`](#successful-states) status), user cancellation ([`canceled`](#cancellation-states)), system cancellation, or order expiration. |
| **UpdateDiff** | `{ update: { origSz: string, newSz: string } }` | Order size changed (usually decreased due to partial fill). Contains both the original size (`origSz`) and the new remaining size (`newSz`). |
| **ModifiedDiff** | `{ modified: { sz: string } }` | Order size modified (typically from order amendments). The `sz` field contains the new remaining size. Unlike `UpdateDiff`, this only provides the new size without the original. |
### Order Status Values
The `status` field in `order_statuses` indicates the result of order processing. Understanding these statuses is critical for debugging order placement issues.
| Status | Type | Description | Debugging Notes |
|--------|------|-------------|-----------------|
| `open` | Success | Order successfully placed and resting on the book | Most common successful status. Order is live and can be filled. |
| `filled` | Success | Order fully executed | Order matched completely. Check `book_diffs` for removal. **Note:** the `sz` field in the order object may be non-zero even for `filled` status. This reflects remaining size at the time the status was emitted by the Hyperliquid node, not necessarily the final state. Use `book_diffs` for accurate size tracking. |
| `triggered` | Success | Trigger/stop order activated | Conditional order has been triggered and converted to regular order. |
| `canceled` | Cancellation | Order canceled by user or system | Standard cancellation. Check if user-initiated or system-triggered. |
| `reduceOnlyCanceled` | Cancellation | Reduce-only order was canceled | Position closed or order would have increased position instead of reducing. |
| `selfTradeCanceled` | Cancellation | Order canceled to prevent self-trading | Same user's buy and sell orders would have matched. Exchange prevented self-execution. |
| `marginCanceled` | Cancellation | Order canceled due to insufficient margin | User's margin balance insufficient to maintain the order. |
| `openInterestCapCanceled` | Cancellation | Order canceled due to open interest cap reached | Market has reached maximum open interest limit. Try again later or use different market. |
| `scheduledCancel` | Cancellation | Order canceled on a scheduled basis | Order was automatically canceled based on time or condition schedule. |
| `siblingFilledCanceled` | Cancellation | Order canceled because sibling order filled | Paired/bracket order canceled when the primary order executed. Common with OCO (One-Cancels-Other) orders. |
| `badAloPxRejected` | Rejection | Add-liquidity-only order rejected (never reached book) | **Most common rejection** (~70% in production data). ALO order would have crossed spread and executed as taker. Price was too aggressive for maker-only order. |
| `iocCancelRejected` | Rejection | Immediate-or-cancel order rejected (never reached book) | IOC order couldn't fill immediately at specified price. No matching liquidity available. |
| `perpMarginRejected` | Rejection | Perpetual futures order rejected (never reached book) | Insufficient margin to open the position. Check account balance and leverage. |
| `perpMaxPositionRejected` | Rejection | Perpetual order rejected - exceeds max position size (never reached book) | Order would exceed maximum allowed position size for this market. Reduce order size or close existing positions. |
| `minTradeNtlRejected` | Rejection | Minimum notional value rejected (never reached book) | Order size (price × quantity) below exchange minimum. Increase order size. |
| `reduceOnlyRejected` | Rejection | Reduce-only order rejected (never reached book) | Order marked reduce-only but would have increased position or no position exists to reduce. |
| `insufficientSpotBalanceRejected` | Rejection | Insufficient spot token balance (never reached book) | Not enough spot token balance to place order. Deposit more tokens or reduce order size. |
| `oracleRejected` | Rejection | Order rejected due to oracle price issues (never reached book) | Oracle price feed unavailable or stale. Wait for oracle to update or check market status. |
| `positionFlipAtOpenInterestCapRejected` | Rejection | Position flip rejected at open interest cap (never reached book) | Order would flip position direction when market is at OI cap. Close existing position first. |
| `positionIncreaseAtOpenInterestCapRejected` | Rejection | Position increase rejected at open interest cap (never reached book) | Cannot increase position size when market has reached open interest limit. |
| `tooAggressiveAtOpenInterestCapRejected` | Rejection | Order too aggressive at open interest cap (never reached book) | Order price too aggressive when market near OI cap. Use less aggressive limit price. |
## Understanding Order Data Flow
Hyperliquid separates order data across two channels. Understanding this separation is essential for building correct trading systems.
| Data | Channel | What you get |
|------|---------|-------------|
| Order status transitions (open, filled, canceled) | **L4 Book** | When an order changes state, not how it was filled |
| Book mutations (new, update, remove) | **L4 Book** | Size changes at each price level per order |
| Individual fill executions (price, size, counterparty) | **[Trades](/hyperliquid/trades)** | Each execution with price, size, hash, and both wallet addresses |
**For complete order visibility, subscribe to both channels** and correlate events using the `oid` (order ID) field:
```python
# Subscribe to both channels for full order tracking
await websocket.send(json.dumps({
"method": "subscribe",
"subscription": {"type": "l4Book", "coin": "ETH"}
}))
await websocket.send(json.dumps({
"method": "subscribe",
"subscription": {"type": "trades", "coin": "ETH"}
}))
# Correlate: l4Book order_statuses use "oid" in the order object,
# trades use "tid" (trade ID) but can be matched to orders by
# tracking which orders are open at each block height.
```
### Why "only 2 events" is normal
A common question is why an order shows only `open` then `filled` with no events in between. This is expected behavior. The L4 Book `order_statuses` array reports **state transitions**, not individual fills.
If an order receives 5 partial fills before completing, the L4 Book reports:
1. `open` - order placed on the book
2. `filled` - order fully executed
The 5 individual fills appear on the **Trades** stream, not in `order_statuses`. The `book_diffs` array tracks the size decreases from partial fills as `update` diffs.
## Order Lifecycle Patterns
Based on production data for ETH, these are the most common order lifecycle patterns on the L4 Book channel:
| Pattern | Frequency | Description |
|---------|-----------|-------------|
| Single rejection event | ~88% of all orders | Orders rejected immediately (`badAloPxRejected`, `perpMarginRejected`, etc.). Never reach the book. |
| `open` then `canceled` | ~98.9% of multi-event | Order placed and later canceled by the user or system |
| `open` then `filled` | ~1.1% of multi-event | Order placed and fully executed (may happen in the same block) |
| `triggered` then `filled` | Rare | Stop/trigger order activated and then filled |
| `open` then `triggered` then `filled` | Very rare | Order transitions through triggered state before filling |
Most orders on Hyperliquid are **ALO (Add Liquidity Only)** orders from market makers that get rejected because the price crossed the spread. This is normal high-frequency trading behavior.
## Code Examples
```python
#!/usr/bin/env python3
from dotenv import load_dotenv
from pathlib import Path
# Load environment variables
env_path = Path(__file__).parent.parent / '.env'
load_dotenv(env_path)
async def main():
ws_url = os.getenv("WEBSOCKET_URL", "wss://api-hyperliquid-mainnet-orderbook.n.dwellir.com/API_KEY/ws")
print(f"Connecting to: {ws_url}\n")
async with websockets.connect(ws_url, max_size=50 * 1024 * 1024) as websocket:
# Subscribe to BTC L4 orderbook
subscribe = {
"method": "subscribe",
"subscription": {
"type": "l4Book",
"coin": "BTC"
}
}
await websocket.send(json.dumps(subscribe))
print("✅ Subscribed to BTC L4 orderbook\n")
print("=" * 60)
message_count = 0
# Listen for messages
async for message in websocket:
message_count += 1
data = json.loads(message)
# Determine message type
if 'data' in data:
if 'Snapshot' in data['data']:
snapshot = data['data']['Snapshot']
height = snapshot.get('height', 'N/A')
bids = len(snapshot.get('bids', []))
asks = len(snapshot.get('asks', []))
print(f"📸 Snapshot #{message_count} | Height: {height} | Bids: {bids} | Asks: {asks}")
elif 'Updates' in data['data']:
updates = data['data']['Updates']
height = updates.get('height', 'N/A')
num_updates = len(updates.get('order_statuses', []))
print(f"🔄 Update #{message_count} | Height: {height} | Orders: {num_updates}")
else:
print(f"ℹ️ Message #{message_count}: {data.get('channel', 'unknown')}")
print("-" * 60)
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\n\n✋ Stopped by user")
```
```javascript
#!/usr/bin/env node
const WebSocket = require('ws');
require('dotenv').config({ path: require('path').join(__dirname, '..', '.env') });
const WS_URL = process.env.WEBSOCKET_URL || 'wss://api-hyperliquid-mainnet-orderbook.n.dwellir.com/API_KEY/ws';
async function main() {
console.log(`Connecting to: ${WS_URL}\n`);
const ws = new WebSocket(WS_URL);
let messageCount = 0;
ws.on('open', () => {
// Subscribe to BTC L4 orderbook
const subscribe = {
method: 'subscribe',
subscription: {
type: 'l4Book',
coin: 'BTC'
}
};
ws.send(JSON.stringify(subscribe));
console.log('✅ Subscribed to BTC L4 orderbook\n');
console.log('='.repeat(60));
});
ws.on('message', (rawData) => {
messageCount++;
const data = JSON.parse(rawData);
// Determine message type
if (data.data) {
if (data.data.Snapshot) {
const snapshot = data.data.Snapshot;
const height = snapshot.height || 'N/A';
const bids = (snapshot.bids || []).length;
const asks = (snapshot.asks || []).length;
console.log(`📸 Snapshot #${messageCount} | Height: ${height} | Bids: ${bids} | Asks: ${asks}`);
} else if (data.data.Updates) {
const updates = data.data.Updates;
const height = updates.height || 'N/A';
const numUpdates = (updates.order_statuses || []).length;
console.log(`🔄 Update #${messageCount} | Height: ${height} | Orders: ${numUpdates}`);
}
} else {
console.log(`ℹ️ Message #${messageCount}: ${data.channel || 'unknown'}`);
}
console.log('-'.repeat(60));
});
ws.on('error', (error) => {
console.error('❌ WebSocket error:', error.message);
});
ws.on('close', () => {
console.log('\n🔌 Connection closed');
});
// Handle Ctrl+C
process.on('SIGINT', () => {
console.log('\n\n✋ Stopped by user');
ws.close();
process.exit(0);
});
}
main().catch(console.error);
```
## Use Cases
### Queue Position Optimization
Understand your place in the order queue:
- **Time priority**: See exactly where your order sits at a price level
- **Fill probability**: Estimate likelihood of execution based on orders ahead
- **Repositioning**: Decide when to cancel and replace for better position
### Whale Wallet Tracking
Monitor large or notable traders:
- **Address tracking**: Follow specific wallet addresses
- **Size alerts**: Trigger on orders above threshold
- **Pattern detection**: Identify accumulation or distribution
### Market Microstructure Research
Analyze order flow dynamics:
- **Order arrival rates**: Study how orders enter the book
- **Cancellation patterns**: Track order lifetime and modification frequency
- **Toxicity analysis**: Measure adverse selection from order flow
### Smart Order Routing
Optimize order execution strategy:
- **Liquidity mapping**: Know exactly what size exists at each level
- **Hidden liquidity**: Detect when large orders are being worked
- **Impact estimation**: Model expected slippage from current book state
## Bandwidth Considerations
L4 data is significantly higher bandwidth than L2:
| Aspect | L2 | L4 |
|--------|----|----|
| Data per level | 3 fields (px, sz, n) | 15+ fields per order |
| Orders visible | Aggregated count only | Every individual order |
| Update frequency | Per price level | Per order change |
| Typical message size | 1-5 KB | 10-100+ KB |
Consider subscribing to L4 only for coins where you need individual order visibility.
## Get Access
Ready to integrate real-time Hyperliquid L4 order book data?
- **[Volume Calculator](https://www.dwellir.com/hyperliquid-orderbook#calculator)** - Estimate monthly message volume
- **[Contact Sales](mailto:ben@dwellir.com)** - Get your WebSocket credentials
- **[Dashboard](https://dashboard.dwellir.com)** - Manage your subscription
---
*Stream institutional-grade Hyperliquid order book data with Dwellir's ultra-low latency infrastructure.*
---
## Trades Stream - Real-Time Trade Executions
# Trades Stream
Stream real-time trade executions as they occur on Hyperliquid. Each trade message contains the execution price, size, direction (buy/sell), timestamp, and participant wallet addresses.
:::tip Code Examples Repository
Clone our complete examples: [github.com/dwellir-public/hyperliquid-orderbook-server-code-examples](https://github.com/dwellir-public/hyperliquid-orderbook-server-code-examples)
:::
## How to Subscribe
Send a subscription message to the WebSocket endpoint:
```json
{
"method": "subscribe",
"subscription": {
"type": "trades",
"coin": "BTC"
}
}
```
### Subscription Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | string | Yes | Must be `"trades"` |
| `coin` | string | Yes | Trading pair symbol (e.g., `"BTC"`, `"ETH"`, `"xyz:MSTR"`, `"@150"`) |
:::info HIP3 Markets
For HIP3 (permissionless perpetuals) markets, use the full coin label format with the `xyz:` prefix. For example, use `"xyz:MSTR"` for the MicroStrategy perpetual, not just `"MSTR"`. Standard perpetuals like BTC and ETH do not require a prefix.
:::
:::info Spot Markets
For spot markets, use the `@{index}` format where the index is the spot asset index. For example, use `"@150"` for a specific spot market.
:::
## Sample Response
```json
{
"channel": "trades",
"data": [
{
"coin": "BTC",
"side": "B",
"px": "90058.0",
"sz": "0.00012",
"hash": "0x0a4cc891f222c1cf0bc60432f4991e02013400778d25e0a1ae1573e4b1269bb9",
"time": 1767878803102,
"tid": 907188554740561,
"users": [
"0xb08ed6f6ad7b22138d4db6d0549efcf1f5e51767",
"0x13558be785661958932ceac35ba20de187275a42"
]
}
]
}
```
## Response Field Reference
| Field | Type | Description |
|-------|------|-------------|
| `channel` | string | Always `"trades"` for this subscription type |
| `data` | array | Array of trade objects (may contain multiple trades per message) |
| `coin` | string | Trading pair symbol |
| `side` | string | `"A"` = Ask (sell/taker sold), `"B"` = Bid (buy/taker bought) |
| `px` | string | Execution price |
| `sz` | string | Trade size in base currency |
| `time` | number | Unix timestamp in milliseconds |
| `hash` | string | Transaction hash on Hyperliquid. Zero-hash (`0x000...000`) indicates a [TWAP fill](#zero-hash-trades-twap-fills) with no on-chain transaction. |
| `tid` | number | Unique trade ID |
| `users` | array | Array of two wallet addresses: `[buyer, seller]` |
### Understanding the `side` Field
The `side` field indicates which side of the order book the trade executed against:
- **`"A"` (Ask)**: The taker sold into the bid. A market sell order matched with a resting buy order.
- **`"B"` (Bid)**: The taker bought from the ask. A market buy order matched with a resting sell order.
## Code Examples
```python
#!/usr/bin/env python3
"""
Trades Stream Example - Real-time trade executions
"""
from datetime import datetime
async def stream_trades():
ws_url = "wss://your-instance.dwellir.com/ws"
async with websockets.connect(ws_url) as websocket:
# Subscribe to BTC trades
await websocket.send(json.dumps({
"method": "subscribe",
"subscription": {
"type": "trades",
"coin": "BTC"
}
}))
print("Subscribed to BTC trades\n")
async for message in websocket:
data = json.loads(message)
if data.get("channel") == "trades":
for trade in data["data"]:
side = "BUY" if trade["side"] == "B" else "SELL"
timestamp = datetime.fromtimestamp(trade["time"] / 1000)
print(f"[{side}] {trade['coin']}: "
f"{trade['sz']} @ ${trade['px']} | "
f"{timestamp.strftime('%H:%M:%S.%f')[:-3]}")
if __name__ == "__main__":
asyncio.run(stream_trades())
```
```javascript
const WebSocket = require('ws');
const wsUrl = 'wss://your-instance.dwellir.com/ws';
const ws = new WebSocket(wsUrl);
ws.on('open', () => {
// Subscribe to BTC trades
ws.send(JSON.stringify({
method: 'subscribe',
subscription: {
type: 'trades',
coin: 'BTC'
}
}));
console.log('Subscribed to BTC trades\n');
});
ws.on('message', (rawData) => {
const data = JSON.parse(rawData);
if (data.channel === 'trades') {
for (const trade of data.data) {
const side = trade.side === 'B' ? 'BUY' : 'SELL';
const time = new Date(trade.time).toISOString();
console.log(`[${side}] ${trade.coin}: ${trade.sz} @ $${trade.px} | ${time}`);
}
}
});
ws.on('error', (error) => console.error('WebSocket error:', error));
```
```go
package main
"encoding/json"
"fmt"
"log"
"time"
"github.com/gorilla/websocket"
)
type TradeMessage struct {
Channel string `json:"channel"`
Data []Trade `json:"data"`
}
type Trade struct {
Coin string `json:"coin"`
Side string `json:"side"`
Px string `json:"px"`
Sz string `json:"sz"`
Time int64 `json:"time"`
Hash string `json:"hash"`
Tid int64 `json:"tid"`
Users []string `json:"users"`
}
func main() {
wsURL := "wss://your-instance.dwellir.com/ws"
conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
if err != nil {
log.Fatal("Connection failed:", err)
}
defer conn.Close()
// Subscribe to BTC trades
subscription := map[string]interface{}{
"method": "subscribe",
"subscription": map[string]string{
"type": "trades",
"coin": "BTC",
},
}
conn.WriteJSON(subscription)
fmt.Println("Subscribed to BTC trades\n")
for {
_, message, err := conn.ReadMessage()
if err != nil {
log.Println("Read error:", err)
return
}
var tradeMsg TradeMessage
if err := json.Unmarshal(message, &tradeMsg); err != nil {
continue
}
if tradeMsg.Channel == "trades" {
for _, trade := range tradeMsg.Data {
side := "SELL"
if trade.Side == "B" {
side = "BUY"
}
timestamp := time.UnixMilli(trade.Time).Format("15:04:05.000")
fmt.Printf("[%s] %s: %s @ $%s | %s\n",
side, trade.Coin, trade.Sz, trade.Px, timestamp)
}
}
}
}
```
### VWAP Calculator Example
Calculate Volume-Weighted Average Price from the trade stream:
```python
from collections import deque
class VWAPCalculator:
def __init__(self, window_size=100):
self.trades = deque(maxlen=window_size)
def add_trade(self, price, size):
self.trades.append({
'price': float(price),
'size': float(size)
})
def get_vwap(self):
if not self.trades:
return 0
total_value = sum(t['price'] * t['size'] for t in self.trades)
total_volume = sum(t['size'] for t in self.trades)
return total_value / total_volume if total_volume > 0 else 0
def get_total_volume(self):
return sum(t['size'] for t in self.trades)
# Usage in your trade handler
vwap = VWAPCalculator(window_size=100)
async def handle_trade(trade):
vwap.add_trade(trade['px'], trade['sz'])
print(f"VWAP: ${vwap.get_vwap():.2f} | Volume: {vwap.get_total_volume():.4f}")
```
### Buy/Sell Pressure Analysis
Track market direction from trade flow:
```python
class TradePressureAnalyzer:
def __init__(self, window_size=50):
self.buy_volume = 0
self.sell_volume = 0
self.trades = deque(maxlen=window_size)
def add_trade(self, side, size):
size = float(size)
# Remove oldest trade's contribution if at capacity
if len(self.trades) == self.trades.maxlen:
old = self.trades[0]
if old['side'] == 'B':
self.buy_volume -= old['size']
else:
self.sell_volume -= old['size']
# Add new trade
self.trades.append({'side': side, 'size': size})
if side == 'B':
self.buy_volume += size
else:
self.sell_volume += size
def get_buy_sell_ratio(self):
if self.sell_volume == 0:
return float('inf') if self.buy_volume > 0 else 0
return self.buy_volume / self.sell_volume
def get_pressure_signal(self):
ratio = self.get_buy_sell_ratio()
if ratio > 1.5:
return "STRONG BUY PRESSURE"
elif ratio > 1.1:
return "BUY PRESSURE"
elif ratio < 0.67:
return "STRONG SELL PRESSURE"
elif ratio < 0.9:
return "SELL PRESSURE"
return "NEUTRAL"
```
## Use Cases
### Trade Flow Analysis
Monitor real-time trade executions to understand market momentum:
- **Direction detection**: Track whether buyers or sellers are dominating
- **Large trade alerts**: Identify whale activity by filtering on size
- **Execution timing**: Measure latency between your orders and confirmations
### VWAP and TWAP Calculations
Build execution benchmarks from the trade stream:
- **VWAP**: Volume-weighted average price for execution quality analysis
- **TWAP**: Time-weighted average price for order slicing strategies
- **Implementation shortfall**: Compare your fills against market VWAP
### Historical Trade Recording
Capture trade data for backtesting and research:
- **Tick data collection**: Store every trade for historical analysis
- **Pattern recognition**: Train ML models on trade sequences
- **Market replay**: Reconstruct market conditions for strategy testing
### Wallet Tracking
Use the `users` field to monitor specific addresses:
- **Whale watching**: Alert when known large traders execute
- **Copy trading signals**: Track successful trader activity
- **Smart money flow**: Analyze institutional wallet behavior
## Zero-Hash Trades (TWAP Fills)
Approximately 10-15% of trades on Hyperliquid carry a zero transaction hash:
```
0x0000000000000000000000000000000000000000000000000000000000000000
```
These are **TWAP (Time-Weighted Average Price) fills**. TWAP orders split large executions into smaller slices over time. The Hyperliquid matching engine generates these fills internally, so they do not correspond to user-signed L1 transactions and have no on-chain hash.
Zero-hash trades are valid executions with accurate price, size, and participant data. Only the `hash` field differs from regular trades.
:::info This is native Hyperliquid behavior
Zero-hash trades appear at identical rates on the public Hyperliquid API. Dwellir passes through the `hash` field from the Hyperliquid node without modification.
:::
## Subscription Management
### Multiple Coin Subscriptions
Subscribe to multiple trading pairs on a single connection:
```python
coins = ["BTC", "ETH", "SOL", "ARB"]
for coin in coins:
await websocket.send(json.dumps({
"method": "subscribe",
"subscription": {
"type": "trades",
"coin": coin
}
}))
```
### Unsubscribe
Stop receiving trades for a specific coin:
```json
{
"method": "unsubscribe",
"subscription": {
"type": "trades",
"coin": "BTC"
}
}
```
## Get Access
Ready to integrate real-time Hyperliquid trade data?
- **[Volume Calculator](https://www.dwellir.com/hyperliquid-orderbook#calculator)** - Estimate monthly message volume
- **[Contact Sales](mailto:ben@dwellir.com)** - Get your WebSocket credentials
- **[Dashboard](https://dashboard.dwellir.com)** - Manage your subscription
---
*Stream institutional-grade Hyperliquid trade data with Dwellir's ultra-low latency infrastructure.*
---
## WebSocket API Quick Reference
Quick reference for connecting to and using the Hyperliquid Order Book WebSocket API. For detailed documentation on each subscription type, see the individual pages.
## Detailed Documentation
| Subscription | Description | Documentation |
|--------------|-------------|---------------|
| **Trades** | Real-time trade executions | [View Trades Docs →](/hyperliquid/trades) |
| **L2 Order Book** | Aggregated price levels | [View L2 Docs →](./l2-book) |
| **L4 Order Book** | Individual order visibility | [View L4 Docs →](./l4-book) |
For an overview of all subscription types and use cases, see the [Order Book Server Overview](./order-book-server).
## Connection
```
wss://.dwellir.com/ws
```
Contact ben@dwellir.com for server credentials.
## Quick Start
```python
async def main():
ws_url = "wss://your-instance.dwellir.com/ws"
async with websockets.connect(ws_url) as websocket:
# Subscribe to BTC trades
await websocket.send(json.dumps({
"method": "subscribe",
"subscription": {"type": "trades", "coin": "BTC"}
}))
async for message in websocket:
print(json.loads(message))
asyncio.run(main())
```
```javascript
const WebSocket = require('ws');
const ws = new WebSocket('wss://your-instance.dwellir.com/ws');
ws.on('open', () => {
ws.send(JSON.stringify({
method: 'subscribe',
subscription: { type: 'trades', coin: 'BTC' }
}));
});
ws.on('message', (data) => console.log(JSON.parse(data)));
```
## Subscription Types
### Trades
```json
{
"method": "subscribe",
"subscription": {
"type": "trades",
"coin": "BTC"
}
}
```
[Full Trades Documentation →](/hyperliquid/trades)
### L2 Order Book
```json
{
"method": "subscribe",
"subscription": {
"type": "l2Book",
"coin": "BTC",
"nSigFigs": 5,
"nLevels": 20
}
}
```
| Parameter | Default | Range | Description |
|-----------|---------|-------|-------------|
| `nSigFigs` | 5 | 2-5 | Price aggregation significant figures |
| `nLevels` | 20 | 1-100 | Number of price levels per side |
[Full L2 Documentation →](./l2-book)
### L4 Order Book
```json
{
"method": "subscribe",
"subscription": {
"type": "l4Book",
"coin": "BTC"
}
}
```
[Full L4 Documentation →](./l4-book)
## Unsubscribe
```json
{
"method": "unsubscribe",
"subscription": {
"type": "trades",
"coin": "BTC"
}
}
```
## Server Messages
### Subscription Confirmation
```json
{
"channel": "subscriptionResponse",
"data": {
"method": "subscribe",
"subscription": { "type": "trades", "coin": "BTC" }
}
}
```
### Error Response
```json
{
"channel": "error",
"data": "Invalid subscription: coin not found"
}
```
### Common Errors
| Error | Cause |
|-------|-------|
| `"coin not found"` | Invalid trading pair symbol |
| `"n_levels too high"` | Requested more than 100 levels |
| `"Already subscribed"` | Duplicate subscription |
| `"Order book not ready"` | Server initializing |
## Response Channels
| Channel | Subscription Type |
|---------|-------------------|
| `trades` | Trades stream |
| `l2Book` | L2 order book |
| `l4Book` | L4 order book |
| `subscriptionResponse` | Subscription confirmations |
| `error` | Error messages |
## Reconnection
The server may restart to resync state. Implement automatic reconnection:
```python
async def connect_with_retry():
delay = 1
while True:
try:
async with websockets.connect(ws_url) as ws:
delay = 1 # Reset on success
await handle_connection(ws)
except Exception:
await asyncio.sleep(delay)
delay = min(delay * 2, 60) # Exponential backoff
```
## Resources
- **[Code Examples](https://github.com/dwellir-public/hyperliquid-orderbook-server-code-examples)** - Complete Python examples
- **[Volume Calculator](https://www.dwellir.com/hyperliquid-orderbook#calculator)** - Estimate monthly usage
- **[Contact](mailto:ben@dwellir.com)** - Get access credentials
---
*For detailed documentation, visit the individual subscription pages: [Trades](/hyperliquid/trades) | [L2 Book](./l2-book) | [L4 Book](./l4-book)*
---
## Hyperliquid Pricing
Dwellir offers specialized Hyperliquid infrastructure with transparent, scalable pricing for high-performance trading applications.
## Service Tiers
### gRPC Streaming API
High-performance real-time streaming for order books, blocks, trades, and fills.
**$299/month + usage**
- Real-time block streaming
- Trade and fill notifications
- Order book snapshots
- WebSocket connections
- Production-grade reliability
- Dedicated support
**Usage charges**: Billed monthly based on API credits consumed (1 request = 1 credit)
:::tip Unlimited Usage with Dedicated Node
When paired with a **Dedicated Node**, gRPC streaming becomes **unmetered with unlimited RPS** at no additional cost beyond the node subscription.
:::
Get gRPC Access →
---
### Order Book Server
Low-latency WebSocket API for real-time order book data and market updates.
**$199/month + usage**
- WebSocket order book streams (L2 aggregated depth or L4 individual orders)
- Real-time market data from Singapore & Tokyo edge servers
- Trade execution feeds
- Optimized for trading bots
- Sub-millisecond updates (~10 messages/sec per pair)
- High availability
**Usage charges**: Billed monthly based on API credits consumed (1 request = 1 credit)
:::tip Estimate Your Volume
Use our [**Volume Calculator**](https://www.dwellir.com/hyperliquid-orderbook#calculator) to estimate your monthly message volume based on trading pairs and depth levels.
:::
:::tip Unlimited Usage with Dedicated Node
When paired with a **Dedicated Node**, order book access becomes **unmetered with unlimited RPS** at no additional cost beyond the node subscription.
:::
Learn More & Calculate Pricing →
---
### Dedicated Node
Your own isolated Hyperliquid infrastructure with uncapped throughput.
**$1,150/month** (unmetered, no usage fees)
- Dedicated HyperEVM JSON-RPC node
- **Unlimited RPS** - No rate limits whatsoever
- **Unmetered billing** - Flat monthly rate, no usage charges
- Isolated infrastructure
- Includes unlimited gRPC streaming at no extra cost
- Includes unlimited order book access at no extra cost
- SLA guarantees
- Priority support
- Custom configurations available
:::info Best Value for High Volume
If you're making more than ~10M requests per day, a Dedicated Node offers better value with **unlimited usage** and **no metering**. Bundle gRPC and Order Book services at no additional cost.
:::
Request Dedicated Node →
---
### Historical Data Access
#### Archival Fills Data
Complete historical trade fill data for backtesting and analysis.
**Custom pricing** - Contact us for details
- Full trade history
- Fill-level granularity
- Bulk data exports
- Optimized for analytics
- Flexible delivery formats
Request Fills Data →
#### Archival Replica Commands Data
Historical command and state data for comprehensive chain analysis.
**Custom pricing** - Contact us for details
- Complete command history
- State snapshots
- Chain replay capability
- Bulk data access
- Research-grade datasets
Request Replica Data →
---
## Usage-Based Billing
### Shared Services (gRPC API, Order Book Server)
For gRPC and Order Book Server tiers on **shared infrastructure**, usage is billed monthly in addition to the base subscription fee.
#### Simple Credit Model
- **1 API request = 1 credit**
- No complex compute unit calculations
- Transparent and predictable costs
- Real-time usage tracking in dashboard
#### Standard Usage Rates
Usage beyond the base subscription is billed at the following rates:
| Plan Tier | Rate per Million Credits |
|-----------|--------------------------|
| gRPC API | See [standard pricing](/docs/getting-started/pricing) |
| Order Book Server | See [standard pricing](/docs/getting-started/pricing) |
For high-volume users, custom volume discounts are available.
### Dedicated Node (Unmetered)
**Dedicated Node subscriptions are completely unmetered:**
- ✅ **Flat $1,150/month** - No usage charges ever
- ✅ **Unlimited RPS** - Make as many requests as your node can handle
- ✅ **Includes gRPC streaming** - Unlimited at no additional cost
- ✅ **Includes order book access** - Unlimited at no additional cost
- ✅ **No rate limits** - Scale to your application's needs
:::tip When to Choose Dedicated
Choose a Dedicated Node if you:
- Need more than ~2M requests per day
- Require guaranteed performance and isolation
- Want predictable monthly costs without usage surprises
- Need to bundle multiple services (JSON-RPC + gRPC + Order Book)
:::
---
## Enterprise Solutions
For institutional traders, market makers, and high-frequency trading firms requiring custom infrastructure:
**Custom pricing** based on your needs
### Enterprise Features
- Custom SLA agreements
- Multi-region deployment
- Dedicated infrastructure
- Direct engineering support
- Custom data feeds
- Volume discounts
- Flexible payment terms
- Priority feature requests
Contact Sales →
---
## Comparison Table
| Feature | gRPC API | Order Book Server | Dedicated Node | Enterprise |
|---------|----------|-------------------|----------------|------------|
| **Base Price** | $699/mo | $199/mo | $1,150/mo | Custom |
| **Usage Billing** | ✅ Metered | ✅ Metered | ❌ **Unmetered** | Custom |
| **Request Limits** | Rate limited | Rate limited | ♾️ **Unlimited RPS** | Custom |
---
## Getting Started
1. **Choose your tier** - Select the service that matches your trading needs
2. **Contact us** - Reach out via email to set up your account
3. **Get credentials** - Receive your API keys and endpoint URLs
4. **Start building** - Integrate with our comprehensive documentation
5. **Scale seamlessly** - Upgrade anytime as your needs grow
### Questions About Pricing?
Our team is happy to help you choose the right plan for your use case:
- 📧 **Email**: support@dwellir.com
- 📚 **Documentation**: [Hyperliquid Docs](/docs/hyperliquid)
- 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com)
---
## Frequently Asked Questions
### How is usage calculated?
**For shared services** (gRPC API and Order Book Server), usage is calculated based on API credits consumed. Each API request counts as 1 credit. Usage is tracked in real-time and displayed in your dashboard.
**For Dedicated Nodes**, there is no usage calculation or metering. You pay a flat monthly rate of $1,150 with completely unlimited usage.
### Can I switch between tiers?
Yes! You can upgrade or downgrade your service tier at any time. Changes take effect at the next billing cycle, and we'll help with any migration needed.
### What payment methods do you accept?
We accept credit/debit cards and bank transfers. Enterprise customers can also pay via cryptocurrency or negotiate custom payment terms.
### Is there a free trial?
Contact our sales team to discuss trial options for your specific use case. We're happy to provide demo access to evaluate our infrastructure.
### What happens if I exceed my usage limits?
**For shared services**, usage beyond your plan's allocation is automatically billed at the end of the month at the per-credit rate. You can set spending limits in your dashboard to prevent unexpected charges.
**For Dedicated Nodes**, there are no usage limits to exceed. Your node provides unlimited RPS at a flat monthly rate with no overage charges possible.
### Do you offer volume discounts?
Yes! High-volume users and enterprise customers can negotiate volume discounts. Contact our sales team to discuss custom pricing.
---
*Need help choosing the right plan? [Contact our team](mailto:support@dwellir.com) for personalized recommendations.*
---
## trace_block - Hyperliquid RPC Method
# trace_block
Returns traces for all transactions in a block on Hyperliquid.
:::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 perpetual futures trading, onchain order books, and institutional-grade derivatives
## 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-hyperliquid-mainnet-evm.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-hyperliquid-mainnet-evm.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-hyperliquid-mainnet-evm.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 - Hyperliquid RPC Method
# trace_call
Traces a call without creating a transaction on Hyperliquid, 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 perpetual futures trading, onchain order books, and institutional-grade derivatives
## 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": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea",
"data": "0x70a0823100000000000000000000000030e54c9bc205e19d693d53c0b0be92299d4191ea"
},
["trace"],
"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": "trace_call",
"params": [
{"to": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "data": "0x70a0823100000000000000000000000030e54c9bc205e19d693d53c0b0be92299d4191ea"},
["trace"],
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY');
const result = await provider.send('trace_call', [
{
to: '0x30e54c9bc205e19d693d53c0b0be92299d4191ea',
data: '0x70a0823100000000000000000000000030e54c9bc205e19d693d53c0b0be92299d4191ea'
},
['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-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'))
result = w3.provider.make_request('trace_call', [
{
'to': '0x30e54c9bc205e19d693d53c0b0be92299d4191ea',
'data': '0x70a0823100000000000000000000000030e54c9bc205e19d693d53c0b0be92299d4191ea'
},
['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 - Hyperliquid RPC Method
# trace_callMany
Traces multiple calls in sequence on Hyperliquid, 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 perpetual futures trading, onchain order books, and institutional-grade derivatives
## 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": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "data": "0x70a0823100000000000000000000000030e54c9bc205e19d693d53c0b0be92299d4191ea"}, ["trace"]],
[{"to": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "data": "0x18160ddd"}, ["trace"]]
],
"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": "trace_callMany",
"params": [
[
[{"to": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "data": "0x70a0823100000000000000000000000030e54c9bc205e19d693d53c0b0be92299d4191ea"}, ["trace"]],
[{"to": "0x30e54c9bc205e19d693d53c0b0be92299d4191ea", "data": "0x18160ddd"}, ["trace"]]
],
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY');
const results = await provider.send('trace_callMany', [
[
[{ to: '0x30e54c9bc205e19d693d53c0b0be92299d4191ea', data: '0x70a0823100000000000000000000000030e54c9bc205e19d693d53c0b0be92299d4191ea' }, ['trace']],
[{ to: '0x30e54c9bc205e19d693d53c0b0be92299d4191ea', 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-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'))
results = w3.provider.make_request('trace_callMany', [
[
[{'to': '0x30e54c9bc205e19d693d53c0b0be92299d4191ea', 'data': '0x70a0823100000000000000000000000030e54c9bc205e19d693d53c0b0be92299d4191ea'}, ['trace']],
[{'to': '0x30e54c9bc205e19d693d53c0b0be92299d4191ea', '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 - Hyperliquid RPC Method
# trace_filter
Returns traces matching a filter on Hyperliquid.
:::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 perpetual futures trading, onchain order books, and institutional-grade derivatives
## 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": ["0x30e54c9bc205e19d693d53c0b0be92299d4191ea"],
"count": 10
}],
"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": "trace_filter",
"params": [{
"fromBlock": "latest",
"toBlock": "latest",
"toAddress": ["0x30e54c9bc205e19d693d53c0b0be92299d4191ea"],
"count": 10
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY');
const traces = await provider.send('trace_filter', [{
fromBlock: 'latest',
toBlock: 'latest',
toAddress: ['0x30e54c9bc205e19d693d53c0b0be92299d4191ea'],
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-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'))
traces = w3.provider.make_request('trace_filter', [{
'fromBlock': 'latest',
'toBlock': 'latest',
'toAddress': ['0x30e54c9bc205e19d693d53c0b0be92299d4191ea'],
'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 - Hyperliquid RPC Method
# trace_get
Returns a trace at a specific position within a transaction on Hyperliquid.
:::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 perpetual futures trading, onchain order books, and institutional-grade derivatives
## 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": ["0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614", ["0x0"]],
"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": "trace_get",
"params": ["0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614", ["0x0"]],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY');
const trace = await provider.send('trace_get', [
'0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614',
['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-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'))
trace = w3.provider.make_request('trace_get', [
'0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614',
['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 - Hyperliquid RPC Method
# trace_replayBlockTransactions
Replays all transactions in a block on Hyperliquid 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 perpetual futures trading, onchain order books, and institutional-grade derivatives
## 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-hyperliquid-mainnet-evm.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-hyperliquid-mainnet-evm.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-hyperliquid-mainnet-evm.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 - Hyperliquid RPC Method
# trace_replayTransaction
Replays a transaction on Hyperliquid 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 perpetual futures trading, onchain order books, and institutional-grade derivatives
## 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": ["0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614", ["trace"]],
"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": "trace_replayTransaction",
"params": ["0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614", ["trace"]],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY');
const result = await provider.send('trace_replayTransaction', [
'0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614',
['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-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'))
result = w3.provider.make_request('trace_replayTransaction', [
'0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614',
['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 - Hyperliquid RPC Method
# trace_transaction
Returns all traces for a specific transaction on Hyperliquid.
:::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 perpetual futures trading, onchain order books, and institutional-grade derivatives
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `txHash` | `DATA` | Yes | 32-byte transaction hash |
## Request
```json
{
"jsonrpc": "2.0",
"method": "trace_transaction",
"params": ["0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614"],
"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": "trace_transaction",
"params": ["0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY');
const traces = await provider.send('trace_transaction', [
'0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614'
]);
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-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY'))
traces = w3.provider.make_request('trace_transaction', [
'0x090cd1f41962604b7efbc2b3c93b536dc7716c8c3487bfe2ba3ff4fe57df0614'
])
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 - Hyperliquid RPC Method
# web3_clientVersion
Returns the current client version on Hyperliquid.
## 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-hyperliquid-mainnet-evm.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-hyperliquid-mainnet-evm.n.dwellir.com/YOUR_API_KEY');
const version = await provider.send('web3_clientVersion', []);
console.log('Client version:', version);
```
---
## web3_sha3 - Hyperliquid RPC Method
# web3_sha3
Returns Keccak-256 (not standard SHA3-256) of the given data on Hyperliquid.
## 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-hyperliquid-mainnet-evm.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-hyperliquid-mainnet-evm.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 - Immutable RPC Method
# debug_traceBlock
Traces all transactions in a block on Immutable 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 Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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-immutable-zkevm-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-immutable-zkevm-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 - Immutable RPC Method
# debug_traceBlockByHash
Traces all transactions in a block on Immutable 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": ["0xdc3499901b5e089b0f67baeb512939f2949bf62cf1158e69bb458e7e43397136", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceBlockByHash",
"params": ["0xdc3499901b5e089b0f67baeb512939f2949bf62cf1158e69bb458e7e43397136", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0xdc3499901b5e089b0f67baeb512939f2949bf62cf1158e69bb458e7e43397136';
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 - Immutable RPC Method
# debug_traceBlockByNumber
Traces all transactions in a block on Immutable 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-immutable-zkevm-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-immutable-zkevm-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 - Immutable RPC Method
# debug_traceCall
Traces a call without creating a transaction on Immutable.
:::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 Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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": "0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"data": "0x70a082310000000000000000000000003A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D"
},
"latest",
{}
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceCall",
"params": [
{"to": "0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D", "data": "0x70a082310000000000000000000000003A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D"},
"latest",
{"tracer": "callTracer"}
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY');
const trace = await provider.send('debug_traceCall', [
{ to: '0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D', data: '0x70a082310000000000000000000000003A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D' },
'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 - Immutable RPC Method
# debug_traceTransaction
Traces a transaction execution on Immutable 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 Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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": ["0x63d1ef279d87a451bc017ca70614ea90270040a2e4b7fcadb1c6115ffcb29486", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceTransaction",
"params": ["0x63d1ef279d87a451bc017ca70614ea90270040a2e4b7fcadb1c6115ffcb29486", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY');
const txHash = '0x63d1ef279d87a451bc017ca70614ea90270040a2e4b7fcadb1c6115ffcb29486';
// 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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0x63d1ef279d87a451bc017ca70614ea90270040a2e4b7fcadb1c6115ffcb29486'
# 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 - Immutable RPC Method
# eth_accounts
Returns a list of addresses owned by the client on Immutable.
> **Why Immutable?** Build on the gaming-optimized zkEVM with 660+ games, 5.5M+ Passport signups, and $40M TVL with first EVM chain with enforceable royalties, Polygon zkEVM technology, $2B+ ecosystem funding, and Agglayer cross-chain liquidity.
## 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 AAA game studios, indie game developers, and NFT gaming teams seeking enforceable royalties 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-immutable-zkevm-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-immutable-zkevm-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-immutable-zkevm-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-immutable-zkevm-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-immutable-zkevm-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-immutable-zkevm-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 - Immutable RPC Method
# eth_blockNumber
Returns the number of the most recent block on Immutable.
> **Why Immutable?** Build on the gaming-optimized zkEVM with 660+ games, 5.5M+ Passport signups, and $40M TVL with first EVM chain with enforceable royalties, Polygon zkEVM technology, $2B+ ecosystem funding, and Agglayer cross-chain liquidity.
## When to Use This Method
`eth_blockNumber` is fundamental for AAA game studios, indie game developers, and NFT gaming teams seeking enforceable royalties:
- **Syncing Applications** — Keep your dApp in sync with the latest Immutable blockchain state
- **Transaction Monitoring** — Verify confirmations by comparing block numbers
- **Event Filtering** — Set the correct block range for querying logs on Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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-immutable-zkevm-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-immutable-zkevm-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('Immutable block:', blockNumber);
// Using ethers.js
const provider = new JsonRpcProvider('https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockNumber = await provider.getBlockNumber();
console.log('Immutable block:', blockNumber);
```
```python
def get_block_number():
response = requests.post(
'https://api-immutable-zkevm-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'Immutable block: {block_number}')
# Using web3.py
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY'))
print(f'Immutable 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-immutable-zkevm-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("Immutable block: %d\n", blockNumber)
}
```
## Common Use Cases
### 1. Block Confirmation Counter
Monitor transaction confirmations on Immutable:
```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 Immutable:
```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 Immutable 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-immutable-zkevm-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 - Immutable RPC Method
# eth_call
Executes a new message call immediately without creating a transaction on Immutable. Used for reading smart contract state.
> **Why Immutable?** Build on the gaming-optimized zkEVM with 660+ games, 5.5M+ Passport signups, and $40M TVL with first EVM chain with enforceable royalties, Polygon zkEVM technology, $2B+ ecosystem funding, and Agglayer cross-chain liquidity.
## 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 Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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": "0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"data": "0x70a082310000000000000000000000003A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D"
},
"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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_call",
"params": [{
"to": "0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"data": "0x70a082310000000000000000000000003A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D"
}, "latest"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-immutable-zkevm-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-immutable-zkevm-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(
'0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D',
'0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D'
)
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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
contractAddress := common.HexToAddress("0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D")
data := common.FromHex("0x70a082310000000000000000000000003A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D")
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 - Immutable RPC Method
# eth_chainId
Returns the chain ID used for transaction signing on Immutable.
> **Why Immutable?** Build on the gaming-optimized zkEVM with 660+ games, 5.5M+ Passport signups, and $40M TVL with first EVM chain with enforceable royalties, Polygon zkEVM technology, $2B+ ecosystem funding, and Agglayer cross-chain liquidity.
## 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-immutable-zkevm-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-immutable-zkevm-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-immutable-zkevm-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-immutable-zkevm-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(Immutable)
# eth_coinbase
Get coinbase address on the Immutable zkEVM 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-immutable-zkevm-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-immutable-zkevm-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 [Immutable zkEVM documentation](/docs/immutable).*
---
## eth_estimateGas - Immutable RPC Method
# eth_estimateGas
Estimates the gas necessary to execute a transaction on Immutable.
> **Why Immutable?** Build on the gaming-optimized zkEVM with 660+ games, 5.5M+ Passport signups, and $40M TVL with first EVM chain with enforceable royalties, Polygon zkEVM technology, $2B+ ecosystem funding, and Agglayer cross-chain liquidity.
## 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 Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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": "0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"to": "0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_estimateGas",
"params": [{
"from": "0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"to": "0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"value": "0x1"
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-immutable-zkevm-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-immutable-zkevm-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('0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D', 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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
toAddress := common.HexToAddress("0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D")
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 - Immutable RPC Method
# eth_feeHistory
Returns historical gas information on Immutable 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 Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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-immutable-zkevm-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-immutable-zkevm-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-immutable-zkevm-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 - Immutable RPC Method
# eth_gasPrice
Returns the current gas price on Immutable in wei.
> **Why Immutable?** Build on the gaming-optimized zkEVM with 660+ games, 5.5M+ Passport signups, and $40M TVL with first EVM chain with enforceable royalties, Polygon zkEVM technology, $2B+ ecosystem funding, and Agglayer cross-chain liquidity.
## 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 Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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-immutable-zkevm-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-immutable-zkevm-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-immutable-zkevm-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-immutable-zkevm-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 - Immutable RPC Method
# eth_getBalance
Returns the balance of a given address on Immutable.
> **Why Immutable?** Build on the gaming-optimized zkEVM with 660+ games, 5.5M+ Passport signups, and $40M TVL with first EVM chain with enforceable royalties, Polygon zkEVM technology, $2B+ ecosystem funding, and Agglayer cross-chain liquidity.
## 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 Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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": [
"0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY');
const address = '0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D';
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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY'))
address = '0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D'
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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
address := common.HexToAddress("0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D")
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 - Immutable RPC Method
# eth_getBlockByHash
Returns information about a block by hash on Immutable.
> **Why Immutable?** Build on the gaming-optimized zkEVM with 660+ games, 5.5M+ Passport signups, and $40M TVL with first EVM chain with enforceable royalties, Polygon zkEVM technology, $2B+ ecosystem funding, and Agglayer cross-chain liquidity.
## 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 Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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": [
"0xdc3499901b5e089b0f67baeb512939f2949bf62cf1158e69bb458e7e43397136",
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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByHash",
"params": [
"0xdc3499901b5e089b0f67baeb512939f2949bf62cf1158e69bb458e7e43397136",
false
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0xdc3499901b5e089b0f67baeb512939f2949bf62cf1158e69bb458e7e43397136';
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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY'))
block_hash = '0xdc3499901b5e089b0f67baeb512939f2949bf62cf1158e69bb458e7e43397136'
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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
blockHash := common.HexToHash("0xdc3499901b5e089b0f67baeb512939f2949bf62cf1158e69bb458e7e43397136")
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 - Immutable RPC Method
# eth_getBlockByNumber
Returns information about a block by block number on Immutable.
> **Why Immutable?** Build on the gaming-optimized zkEVM with 660+ games, 5.5M+ Passport signups, and $40M TVL with first EVM chain with enforceable royalties, Polygon zkEVM technology, $2B+ ecosystem funding, and Agglayer cross-chain liquidity.
## 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 Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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": "0xdc3499901b5e089b0f67baeb512939f2949bf62cf1158e69bb458e7e43397136",
"parentHash": "0x...",
"timestamp": "0x64d8f6d0",
"gasUsed": "0x1234",
"gasLimit": "0x1c9c380",
"transactions": [],
"baseFeePerGas": "0x5f5e100"
}
}
```
## Code Examples
```bash
curl -X POST https://api-immutable-zkevm-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-immutable-zkevm-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-immutable-zkevm-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-immutable-zkevm-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 - Immutable RPC Method
# eth_getCode
Returns the bytecode at a given address on Immutable.
> **Why Immutable?** Build on the gaming-optimized zkEVM with 660+ games, 5.5M+ Passport signups, and $40M TVL with first EVM chain with enforceable royalties, Polygon zkEVM technology, $2B+ ecosystem funding, and Agglayer cross-chain liquidity.
## 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 Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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": [
"0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"latest"
],
"id": 1
}
```
## Returns
| Type | Description |
|------|-------------|
| `DATA` | Contract bytecode or `0x` if EOA |
## Code Examples
```bash
curl -X POST https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getCode",
"params": [
"0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY');
const address = '0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D';
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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY'))
address = '0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D'
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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
address := common.HexToAddress("0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D")
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 - Immutable RPC Method
# eth_getFilterChanges
Polling method for a filter on Immutable, returns an array of logs since last poll.
## Use Cases
- **Event streaming** - Get new events incrementally
- **Real-time monitoring** - Track contract activity for Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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-immutable-zkevm-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-immutable-zkevm-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 - Immutable RPC Method
# eth_getFilterLogs
Returns an array of all logs matching filter with given ID on Immutable.
## Use Cases
- **Historical queries** - Get all matching logs for a filter
- **Full event history** - Retrieve complete event data for Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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-immutable-zkevm-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-immutable-zkevm-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 - Immutable RPC Method
# eth_getLogs
Returns an array of all logs matching a given filter object on Immutable.
> **Why Immutable?** Build on the gaming-optimized zkEVM with 660+ games, 5.5M+ Passport signups, and $40M TVL with first EVM chain with enforceable royalties, Polygon zkEVM technology, $2B+ ecosystem funding, and Agglayer cross-chain liquidity.
## Use Cases
The `eth_getLogs` method is essential for:
- **Event indexing** - Track contract events for Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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": "0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"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": "0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."],
"data": "0x...",
"blockNumber": "0x5BAD55",
"transactionHash": "0x...",
"logIndex": "0x0"
}]
}
```
## Code Examples
```bash
curl -X POST https://api-immutable-zkevm-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": "0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-immutable-zkevm-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(
'0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D',
'latest',
'latest'
);
console.log('Transfer events:', events);
```
```python
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-immutable-zkevm-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(
'0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D',
'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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
contractAddress := common.HexToAddress("0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D")
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 - Immutable RPC Method
# eth_getStorageAt
Returns the value from a storage position at a given address on Immutable.
## Use Cases
- **Contract analysis** - Read raw storage values
- **State verification** - Verify contract state
- **Security auditing** - Analyze storage layout for Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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": [
"0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"0x0",
"latest"
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getStorageAt",
"params": [
"0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"0x0",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY');
const address = '0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D';
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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY'))
address = '0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D'
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 - Immutable RPC Method
# eth_getTransactionByHash
Returns the information about a transaction by transaction hash on Immutable.
> **Why Immutable?** Build on the gaming-optimized zkEVM with 660+ games, 5.5M+ Passport signups, and $40M TVL with first EVM chain with enforceable royalties, Polygon zkEVM technology, $2B+ ecosystem funding, and Agglayer cross-chain liquidity.
## 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 Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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": ["0x63d1ef279d87a451bc017ca70614ea90270040a2e4b7fcadb1c6115ffcb29486"],
"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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionByHash",
"params": ["0x63d1ef279d87a451bc017ca70614ea90270040a2e4b7fcadb1c6115ffcb29486"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY');
const txHash = '0x63d1ef279d87a451bc017ca70614ea90270040a2e4b7fcadb1c6115ffcb29486';
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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0x63d1ef279d87a451bc017ca70614ea90270040a2e4b7fcadb1c6115ffcb29486'
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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0x63d1ef279d87a451bc017ca70614ea90270040a2e4b7fcadb1c6115ffcb29486")
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 - Immutable RPC Method
# eth_getTransactionCount
Returns the number of transactions sent from an address on Immutable (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 Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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": [
"0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"latest"
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [
"0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY');
const address = '0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D';
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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY'))
address = '0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D'
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 - Immutable RPC Method
# eth_getTransactionReceipt
Returns the receipt of a transaction by transaction hash on Immutable. Receipt is only available for mined transactions.
> **Why Immutable?** Build on the gaming-optimized zkEVM with 660+ games, 5.5M+ Passport signups, and $40M TVL with first EVM chain with enforceable royalties, Polygon zkEVM technology, $2B+ ecosystem funding, and Agglayer cross-chain liquidity.
## 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 Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game assets
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `transactionHash` | `DATA` | Yes | 32-byte transaction hash |
## Request
```json
{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0x63d1ef279d87a451bc017ca70614ea90270040a2e4b7fcadb1c6115ffcb29486"],
"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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0x63d1ef279d87a451bc017ca70614ea90270040a2e4b7fcadb1c6115ffcb29486"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY');
const txHash = '0x63d1ef279d87a451bc017ca70614ea90270040a2e4b7fcadb1c6115ffcb29486';
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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0x63d1ef279d87a451bc017ca70614ea90270040a2e4b7fcadb1c6115ffcb29486'
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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0x63d1ef279d87a451bc017ca70614ea90270040a2e4b7fcadb1c6115ffcb29486")
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(Immutable)
# eth_hashrate
Get node hashrate on the Immutable zkEVM 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-immutable-zkevm-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-immutable-zkevm-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 [Immutable zkEVM documentation](/docs/immutable).*
---
## eth_maxPriorityFeePerGas - Immutable RPC Method
# eth_maxPriorityFeePerGas
Returns the current recommended priority fee per gas on Immutable 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 Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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-immutable-zkevm-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-immutable-zkevm-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-immutable-zkevm-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(Immutable)
# eth_mining
Check if node is mining on the Immutable zkEVM 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-immutable-zkevm-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-immutable-zkevm-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 [Immutable zkEVM documentation](/docs/immutable).*
---
## eth_newBlockFilter - Immutable RPC Method
# eth_newBlockFilter
Creates a filter on Immutable 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-immutable-zkevm-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-immutable-zkevm-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 - Immutable RPC Method
# eth_newFilter
Creates a filter object on Immutable to notify when state changes (logs).
## Use Cases
- **Event monitoring** - Subscribe to contract events
- **Real-time updates** - Track events for Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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": "0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
}],
"id": 1
}
```
## Returns
| Type | Description |
|------|-------------|
| `QUANTITY` | Filter ID |
## Code Examples
```bash
curl -X POST https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_newFilter",
"params": [{
"fromBlock": "latest",
"address": "0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D"
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY');
// Create filter
const filterId = await provider.send('eth_newFilter', [{
fromBlock: 'latest',
address: '0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D',
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 - Immutable RPC Method
# eth_newPendingTransactionFilter
Creates a filter on Immutable 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-immutable-zkevm-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-immutable-zkevm-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 v...
# eth_protocolVersion
Get protocol version on the Immutable zkEVM 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-immutable-zkevm-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-immutable-zkevm-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 [Immutable zkEVM documentation](/docs/immutable).*
---
## eth_sendRawTransaction - Immutable RPC Method
# eth_sendRawTransaction
Submits a pre-signed transaction for broadcast to Immutable.
> **Why Immutable?** Build on the gaming-optimized zkEVM with 660+ games, 5.5M+ Passport signups, and $40M TVL with first EVM chain with enforceable royalties, Polygon zkEVM technology, $2B+ ecosystem funding, and Agglayer cross-chain liquidity.
## 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 Web3 gaming (Gods Unchained, RavenQuest), gaming NFTs with enforced royalties, and cross-chain game 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-immutable-zkevm-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-immutable-zkevm-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-immutable-zkevm-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-immutable-zkevm-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("0x3A0C2Ba54D6CBd3121f01b96DFd20e99D1696c9D")
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 transacti...
# eth_sendTransaction
> **Important**: Dwellir's shared Immutable zkEVM 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-immutable-zkevm-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 transacti...
# 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-immutable-zkevm-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-immutable-zkevm-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 [Immutable zkEVM documentation](/docs/immutable).*
---
## eth_syncing - Immutable RPC Method
# eth_syncing
Returns syncing status of Immutable 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-immutable-zkevm-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-immutable-zkevm-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 - Immutable RPC Method
# eth_uninstallFilter
Uninstalls a filter on Immutable. 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-immutable-zkevm-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-immutable-zkevm-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
---
## Immutable zkEVM - Gaming L2
# Immutable zkEVM - Build on the Premier Gaming Blockchain
## Why Build on Immutable zkEVM?
Immutable zkEVM is the first EVM-compatible blockchain built specifically for gaming, offering seamless Web3 integration for game developers. Powered by zero-knowledge technology, Immutable zkEVM delivers:
### 🎮 **Gaming-First Design**
- **Purpose-built for games** - Optimized infrastructure for gaming workloads
- **Seamless Web3 integration** - Add blockchain features without sacrificing UX
- **Developer-friendly tools** - Comprehensive SDK and gaming-specific APIs
### ⚡ **High-Performance Infrastructure**
- **Instant transactions** - Fast block times for real-time gaming
- **Massive scale** - Handle thousands of concurrent players
- **Zero-knowledge proofs** - Efficient transaction batching and verification
### 🛡️ **Enterprise-Grade Security**
- **Ethereum security** - Inherits L1 security guarantees
- **Battle-tested technology** - Built on proven zkEVM architecture
- **Immutable backing** - Supported by leading Web3 gaming infrastructure
## Quick Start with Immutable zkEVM
Connect to Immutable zkEVM in seconds with Dwellir's optimized endpoints:
### Installation & Setup
```javascript
// Connect to Immutable zkEVM mainnet
const provider = new JsonRpcProvider(
'https://api-immutable-zkevm-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 Immutable zkEVM mainnet
const web3 = new Web3(
'https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY'
);
// Get chain ID to verify connection
const chainId = await web3.eth.getChainId();
console.log('Connected to Immutable zkEVM:', chainId === 13371);
// Get gas price for optimal transaction pricing
const gasPrice = await web3.eth.getGasPrice();
console.log('Current gas price:', gasPrice);
```
```typescript
// Define Immutable zkEVM chain
const immutableZkEvm = defineChain({
id: 13371,
name: 'Immutable zkEVM',
network: 'immutable-zkevm',
nativeCurrency: { name: 'IMX', symbol: 'IMX', decimals: 18 },
rpcUrls: {
default: { http: ['https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY'] },
public: { http: ['https://rpc.immutable.com'] },
},
blockExplorers: {
default: { name: 'Immutable Explorer', url: 'https://explorer.immutable.com' },
},
});
// Create Immutable zkEVM client
const client = createPublicClient({
chain: immutableZkEvm,
transport: http('https://api-immutable-zkevm-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
13371
Mainnet
Block Time
2 seconds
Average
Gas Token
IMX
Native token
RPC Standard
Ethereum
JSON-RPC 2.0
## JSON-RPC API Reference
Immutable zkEVM supports the full [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/). Access all standard methods optimized for gaming workloads.
## Common Integration Patterns
### 🎮 Gaming Transaction Patterns
Handle high-frequency gaming transactions efficiently:
```javascript
// Batch multiple game actions in a single transaction
async function batchGameActions(actions) {
const receipt = await provider.waitForTransaction(txHash, 1);
// Fast confirmation for real-time gaming
console.log('Transaction confirmed in:', receipt.blockNumber);
return receipt;
}
```
### 💎 NFT and Asset Management
Optimize for gaming assets and NFTs:
```javascript
// Efficient gas estimation for gaming transactions
const gasEstimate = await provider.estimateGas(tx);
// Immutable zkEVM optimized for gaming workloads
const optimizedGas = Math.ceil(gasEstimate * 1.1); // 10% buffer
// Set gas with gaming-optimized pricing
const txWithGas = {
...tx,
gasLimit: optimizedGas,
maxFeePerGas: await provider.getFeeData().maxFeePerGas
};
```
### 🔍 Game Event Tracking
Efficiently query game-related events:
```javascript
// Query game events with optimized batching
async function getGameEvents(contract, eventName, fromBlock = 0) {
const filter = contract.filters[eventName]();
const events = [];
const batchSize = 5000; // Immutable zkEVM optimized 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 ImmutableProvider {
static instance = null;
static getInstance() {
if (!this.instance) {
this.instance = new JsonRpcProvider(
'https://api-immutable-zkevm-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"
Immutable zkEVM transactions require IMX for gas fees:
```javascript
// Check IMX 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 || 0n);
if (balance < totalRequired) {
throw new Error(`Need ${totalRequired - balance} more IMX`);
}
```
### Error: "Transaction underpriced"
Immutable zkEVM uses EIP-1559 pricing with minimum 10 gwei priority fee:
```javascript
// Get current fee data with gaming-optimized settings
const feeData = await provider.getFeeData();
const tx = {
to: recipient,
value: amount,
maxFeePerGas: feeData.maxFeePerGas,
maxPriorityFeePerGas: Math.max(
feeData.maxPriorityFeePerGas,
10000000000n // 10 gwei minimum
),
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 Immutable zkEVM requires minimal changes:
```javascript
// Before (Ethereum)
const provider = new JsonRpcProvider('https://eth-rpc.example.com');
// After (Immutable zkEVM)
const provider = new JsonRpcProvider(
'https://api-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY'
);
// ✅ Smart contracts work identically
// ✅ Same tooling and libraries
// ⚠️ Different chain ID (13371)
// ⚠️ Separate block numbers
// ⚠️ IMX used for gas fees
// ⚠️ Minimum 10 gwei priority fee
```
### From Other Gaming Chains
Migrating gaming applications to Immutable zkEVM:
```javascript
// Enhanced gaming features available
const gameContract = new Contract(address, abi, provider);
// Optimized for high-frequency gaming transactions
const batchTx = await gameContract.batchMint(
playerAddresses,
tokenIds,
{ gasLimit: 500000 } // Gaming-optimized gas limits
);
```
## Resources & Tools
### Official Resources
- [Immutable Documentation](https://docs.immutable.com)
- [Immutable Block Explorer](https://explorer.immutable.com)
### Developer Tools
- [Immutable SDK](https://docs.immutable.com/reference/typescript)
- [Unity SDK](https://docs.immutable.com/sdks/zkevm/unity/)
- [Passport Integration](https://docs.immutable.com/sdks/zkevm/unity/passport/)
### Gaming Ecosystem
- [Gods Unchained](https://godsunchained.com) - Leading TCG on Immutable
- [Guild of Guardians](https://guildofguardians.com) - Mobile RPG
- [Illuvium](https://illuvium.io) - Open-world RPG
### Need Help?
- 📧 **Email**: support@dwellir.com
- 📚 **Docs**: You're here!
- 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com)
---
*Start building games on Immutable zkEVM with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## net_listening - Immutable RPC Method
# net_listening
Returns `true` if client is actively listening for network connections on Immutable.
## 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-immutable-zkevm-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-immutable-zkevm-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 - Immutable RPC Method
# net_peerCount
Returns number of peers currently connected to Immutable 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-immutable-zkevm-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-immutable-zkevm-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 - Immutable RPC Method
# net_version
Returns the current network ID on Immutable.
## 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-immutable-zkevm-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-immutable-zkevm-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 - Immutable RPC Method
# web3_clientVersion
Returns the current client version on Immutable.
## 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-immutable-zkevm-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-immutable-zkevm-mainnet.n.dwellir.com/YOUR_API_KEY');
const version = await provider.send('web3_clientVersion', []);
console.log('Client version:', version);
```
---
## web3_sha3 - Immutable RPC Method
# web3_sha3
Returns Keccak-256 (not standard SHA3-256) of the given data on Immutable.
## 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-immutable-zkevm-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-immutable-zkevm-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);
```
---
## Home
## Documentation Overview
### Core Concepts
- **[Getting Started Guide](/getting-started)** - Quick setup and first steps
- **[Pricing Plans](/getting-started/pricing)** - Flexible pricing for every project
- **[Rate Limits](/getting-started/rate-limits)** - Understanding and managing limits
- **[Supported Chains](/getting-started/supported-chains)** - 150+ blockchain networks
- **[CLI](/cli)** - Manage keys, endpoints, and usage from your terminal
### Network Guides
Browse our comprehensive guides for supported networks:
#### Ethereum & Layer 2s
- **[Base L2](/base)** - Complete Base Layer 2 documentation with JSON-RPC and Debug API methods
- **[Arbitrum One](/arbitrum)** - Leading Ethereum L2 with comprehensive JSON-RPC and Debug API documentation
- **[World Chain](/world-chain)** - Human-first Ethereum L2 with World ID integration for free gas and priority blockspace
- **[Avalanche C-Chain](/avalanche)** - High-performance platform with sub-second finality and 4,500+ TPS
- **[Polygon PoS](/polygon)** - Ethereum-compatible Layer 2 with massive ecosystem and ultra-low fees
- **[Unichain](/unichain)** - Uniswap's DeFi-optimized L2 with built-in MEV protection and fast finality
#### Next-Generation Blockchains
- **[Aptos](/aptos)** - Layer 1 blockchain with parallel execution, Move VM, and sub-second finality
- **[Sui Network](/sui)** - Object-centric blockchain with parallel execution and sub-second finality
- **[HyperLiquid](/hyperliquid)** - High-performance perpetuals DEX chain with native order book
- **[Bittensor](/bittensor)** - Decentralized AI network with machine learning consensus
- **[IoTeX](/iotex)** - Leading blockchain for IoT devices and DePIN infrastructure
- **[Manta Pacific](/manta-pacific)** - EVM rollup with archive, trace, and debug RPC coverage
- **[Manta Atlantic](/manta-atlantic)** - Polkadot zk identity parachain with enterprise archive RPC
More network documentation coming soon. Check our [supported chains](/getting-started/supported-chains) for the full list of available networks.
### Best Practices
- **Rate Limiting** - Understand and optimize your API usage
- **Error Handling** - Robust error handling patterns
- **Security** - Secure key management and best practices
- **Performance** - Optimization tips for production workloads
## Need Help?
Our support team is available 24/7 to help you succeed:
- **Email** - support@dwellir.com
- **Documentation** - You're already here!
Start building with confidence on Dwellir's enterprise-grade infrastructure.
---
## debug_traceBlock - IoTeX RPC Method
# debug_traceBlock
Traces all transactions in a block on IoTeX 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 decentralized physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
## 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-iotex-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-iotex-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 - IoTeX RPC Method
# debug_traceBlockByHash
Traces all transactions in a block on IoTeX 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": ["0xc5bd9f787bec85feee50f013caebb999107e5ba47da16ac194a5dbb06b5f4ff2", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceBlockByHash",
"params": ["0xc5bd9f787bec85feee50f013caebb999107e5ba47da16ac194a5dbb06b5f4ff2", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0xc5bd9f787bec85feee50f013caebb999107e5ba47da16ac194a5dbb06b5f4ff2';
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 - IoTeX RPC Method
# debug_traceBlockByNumber
Traces all transactions in a block on IoTeX 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-iotex-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-iotex-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 - IoTeX RPC Method
# debug_traceCall
Traces a call without creating a transaction on IoTeX.
:::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 decentralized physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
## 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": "0xA00744882684C3e4747fAEFd68D283eA44099D03",
"data": "0x70a08231000000000000000000000000A00744882684C3e4747fAEFd68D283eA44099D03"
},
"latest",
{}
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceCall",
"params": [
{"to": "0xA00744882684C3e4747fAEFd68D283eA44099D03", "data": "0x70a08231000000000000000000000000A00744882684C3e4747fAEFd68D283eA44099D03"},
"latest",
{"tracer": "callTracer"}
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY');
const trace = await provider.send('debug_traceCall', [
{ to: '0xA00744882684C3e4747fAEFd68D283eA44099D03', data: '0x70a08231000000000000000000000000A00744882684C3e4747fAEFd68D283eA44099D03' },
'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 - IoTeX RPC Method
# debug_traceTransaction
Traces a transaction execution on IoTeX 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 decentralized physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
## 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": ["0x839fcf7f5deeefd02960f393f67a9a2b8ee993683d397757c74edf1667ffb0f8", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceTransaction",
"params": ["0x839fcf7f5deeefd02960f393f67a9a2b8ee993683d397757c74edf1667ffb0f8", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY');
const txHash = '0x839fcf7f5deeefd02960f393f67a9a2b8ee993683d397757c74edf1667ffb0f8';
// 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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0x839fcf7f5deeefd02960f393f67a9a2b8ee993683d397757c74edf1667ffb0f8'
# 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 - IoTeX RPC Method
# eth_accounts
Returns a list of addresses owned by the client on IoTeX.
> **Why IoTeX?** Build on the leading DePIN infrastructure blockchain powering 130+ applications in the $27B+ DePIN ecosystem with W3bstream offchain compute, Quicksilver AI data verification, Vodafone partnership for 5M+ cell tower integration, and ioID device identity.
## 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 DePIN builders, IoT device manufacturers, and real-world AI application 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-iotex-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-iotex-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-iotex-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-iotex-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-iotex-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-iotex-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 - IoTeX RPC Method
# eth_blockNumber
Returns the number of the most recent block on IoTeX.
> **Why IoTeX?** Build on the leading DePIN infrastructure blockchain powering 130+ applications in the $27B+ DePIN ecosystem with W3bstream offchain compute, Quicksilver AI data verification, Vodafone partnership for 5M+ cell tower integration, and ioID device identity.
## When to Use This Method
`eth_blockNumber` is fundamental for DePIN builders, IoT device manufacturers, and real-world AI application developers:
- **Syncing Applications** — Keep your dApp in sync with the latest IoTeX blockchain state
- **Transaction Monitoring** — Verify confirmations by comparing block numbers
- **Event Filtering** — Set the correct block range for querying logs on decentralized physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
- **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-iotex-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-iotex-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('IoTeX block:', blockNumber);
// Using ethers.js
const provider = new JsonRpcProvider('https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockNumber = await provider.getBlockNumber();
console.log('IoTeX block:', blockNumber);
```
```python
def get_block_number():
response = requests.post(
'https://api-iotex-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'IoTeX block: {block_number}')
# Using web3.py
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'))
print(f'IoTeX 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-iotex-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("IoTeX block: %d\n", blockNumber)
}
```
## Common Use Cases
### 1. Block Confirmation Counter
Monitor transaction confirmations on IoTeX:
```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 IoTeX:
```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 IoTeX 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-iotex-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 - IoTeX RPC Method
# eth_call
Executes a new message call immediately without creating a transaction on IoTeX. Used for reading smart contract state.
> **Why IoTeX?** Build on the leading DePIN infrastructure blockchain powering 130+ applications in the $27B+ DePIN ecosystem with W3bstream offchain compute, Quicksilver AI data verification, Vodafone partnership for 5M+ cell tower integration, and ioID device identity.
## 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 physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
- **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": "0xA00744882684C3e4747fAEFd68D283eA44099D03",
"data": "0x70a08231000000000000000000000000A00744882684C3e4747fAEFd68D283eA44099D03"
},
"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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_call",
"params": [{
"to": "0xA00744882684C3e4747fAEFd68D283eA44099D03",
"data": "0x70a08231000000000000000000000000A00744882684C3e4747fAEFd68D283eA44099D03"
}, "latest"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-iotex-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-iotex-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(
'0xA00744882684C3e4747fAEFd68D283eA44099D03',
'0xA00744882684C3e4747fAEFd68D283eA44099D03'
)
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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
contractAddress := common.HexToAddress("0xA00744882684C3e4747fAEFd68D283eA44099D03")
data := common.FromHex("0x70a08231000000000000000000000000A00744882684C3e4747fAEFd68D283eA44099D03")
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 - IoTeX RPC Method
# eth_chainId
Returns the chain ID used for transaction signing on IoTeX.
> **Why IoTeX?** Build on the leading DePIN infrastructure blockchain powering 130+ applications in the $27B+ DePIN ecosystem with W3bstream offchain compute, Quicksilver AI data verification, Vodafone partnership for 5M+ cell tower integration, and ioID device identity.
## 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-iotex-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-iotex-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-iotex-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-iotex-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(Iotex)
# eth_coinbase
Get coinbase address on the IoTeX 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-iotex-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-iotex-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 [IoTeX documentation](/docs/arbitrum).*
---
## eth_estimateGas - IoTeX RPC Method
# eth_estimateGas
Estimates the gas necessary to execute a transaction on IoTeX.
> **Why IoTeX?** Build on the leading DePIN infrastructure blockchain powering 130+ applications in the $27B+ DePIN ecosystem with W3bstream offchain compute, Quicksilver AI data verification, Vodafone partnership for 5M+ cell tower integration, and ioID device identity.
## 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 physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
## 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": "0xA00744882684C3e4747fAEFd68D283eA44099D03",
"to": "0xA00744882684C3e4747fAEFd68D283eA44099D03",
"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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_estimateGas",
"params": [{
"from": "0xA00744882684C3e4747fAEFd68D283eA44099D03",
"to": "0xA00744882684C3e4747fAEFd68D283eA44099D03",
"value": "0x1"
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-iotex-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-iotex-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('0xA00744882684C3e4747fAEFd68D283eA44099D03', 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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
toAddress := common.HexToAddress("0xA00744882684C3e4747fAEFd68D283eA44099D03")
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 - IoTeX RPC Method
# eth_feeHistory
Returns historical gas information on IoTeX 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 physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
## 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-iotex-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-iotex-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-iotex-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 - IoTeX RPC Method
# eth_gasPrice
Returns the current gas price on IoTeX in wei.
> **Why IoTeX?** Build on the leading DePIN infrastructure blockchain powering 130+ applications in the $27B+ DePIN ecosystem with W3bstream offchain compute, Quicksilver AI data verification, Vodafone partnership for 5M+ cell tower integration, and ioID device identity.
## 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 physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
## 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-iotex-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-iotex-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-iotex-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-iotex-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 - IoTeX RPC Method
# eth_getBalance
Returns the balance of a given address on IoTeX.
> **Why IoTeX?** Build on the leading DePIN infrastructure blockchain powering 130+ applications in the $27B+ DePIN ecosystem with W3bstream offchain compute, Quicksilver AI data verification, Vodafone partnership for 5M+ cell tower integration, and ioID device identity.
## 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 physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
- **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": [
"0xA00744882684C3e4747fAEFd68D283eA44099D03",
"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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0xA00744882684C3e4747fAEFd68D283eA44099D03",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY');
const address = '0xA00744882684C3e4747fAEFd68D283eA44099D03';
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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'))
address = '0xA00744882684C3e4747fAEFd68D283eA44099D03'
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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
address := common.HexToAddress("0xA00744882684C3e4747fAEFd68D283eA44099D03")
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 - IoTeX RPC Method
# eth_getBlockByHash
Returns information about a block by hash on IoTeX.
> **Why IoTeX?** Build on the leading DePIN infrastructure blockchain powering 130+ applications in the $27B+ DePIN ecosystem with W3bstream offchain compute, Quicksilver AI data verification, Vodafone partnership for 5M+ cell tower integration, and ioID device identity.
## 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 physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
- **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": [
"0xc5bd9f787bec85feee50f013caebb999107e5ba47da16ac194a5dbb06b5f4ff2",
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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByHash",
"params": [
"0xc5bd9f787bec85feee50f013caebb999107e5ba47da16ac194a5dbb06b5f4ff2",
false
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0xc5bd9f787bec85feee50f013caebb999107e5ba47da16ac194a5dbb06b5f4ff2';
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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'))
block_hash = '0xc5bd9f787bec85feee50f013caebb999107e5ba47da16ac194a5dbb06b5f4ff2'
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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
blockHash := common.HexToHash("0xc5bd9f787bec85feee50f013caebb999107e5ba47da16ac194a5dbb06b5f4ff2")
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 - IoTeX RPC Method
# eth_getBlockByNumber
Returns information about a block by block number on IoTeX.
> **Why IoTeX?** Build on the leading DePIN infrastructure blockchain powering 130+ applications in the $27B+ DePIN ecosystem with W3bstream offchain compute, Quicksilver AI data verification, Vodafone partnership for 5M+ cell tower integration, and ioID device identity.
## 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 physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
- **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": "0xc5bd9f787bec85feee50f013caebb999107e5ba47da16ac194a5dbb06b5f4ff2",
"parentHash": "0x...",
"timestamp": "0x64d8f6d0",
"gasUsed": "0x1234",
"gasLimit": "0x1c9c380",
"transactions": [],
"baseFeePerGas": "0x5f5e100"
}
}
```
## Code Examples
```bash
curl -X POST https://api-iotex-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-iotex-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-iotex-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-iotex-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 - IoTeX RPC Method
# eth_getCode
Returns the bytecode at a given address on IoTeX.
> **Why IoTeX?** Build on the leading DePIN infrastructure blockchain powering 130+ applications in the $27B+ DePIN ecosystem with W3bstream offchain compute, Quicksilver AI data verification, Vodafone partnership for 5M+ cell tower integration, and ioID device identity.
## 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 physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
## 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": [
"0xA00744882684C3e4747fAEFd68D283eA44099D03",
"latest"
],
"id": 1
}
```
## Returns
| Type | Description |
|------|-------------|
| `DATA` | Contract bytecode or `0x` if EOA |
## Code Examples
```bash
curl -X POST https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getCode",
"params": [
"0xA00744882684C3e4747fAEFd68D283eA44099D03",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY');
const address = '0xA00744882684C3e4747fAEFd68D283eA44099D03';
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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'))
address = '0xA00744882684C3e4747fAEFd68D283eA44099D03'
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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
address := common.HexToAddress("0xA00744882684C3e4747fAEFd68D283eA44099D03")
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 - IoTeX RPC Method
# eth_getFilterChanges
Polling method for a filter on IoTeX, returns an array of logs since last poll.
## Use Cases
- **Event streaming** - Get new events incrementally
- **Real-time monitoring** - Track contract activity for decentralized physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
- **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-iotex-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-iotex-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 - IoTeX RPC Method
# eth_getFilterLogs
Returns an array of all logs matching filter with given ID on IoTeX.
## Use Cases
- **Historical queries** - Get all matching logs for a filter
- **Full event history** - Retrieve complete event data for decentralized physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
## 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-iotex-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-iotex-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 - IoTeX RPC Method
# eth_getLogs
Returns an array of all logs matching a given filter object on IoTeX.
> **Why IoTeX?** Build on the leading DePIN infrastructure blockchain powering 130+ applications in the $27B+ DePIN ecosystem with W3bstream offchain compute, Quicksilver AI data verification, Vodafone partnership for 5M+ cell tower integration, and ioID device identity.
## Use Cases
The `eth_getLogs` method is essential for:
- **Event indexing** - Track contract events for decentralized physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
- **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": "0xA00744882684C3e4747fAEFd68D283eA44099D03",
"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": "0xA00744882684C3e4747fAEFd68D283eA44099D03",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."],
"data": "0x...",
"blockNumber": "0x5BAD55",
"transactionHash": "0x...",
"logIndex": "0x0"
}]
}
```
## Code Examples
```bash
curl -X POST https://api-iotex-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": "0xA00744882684C3e4747fAEFd68D283eA44099D03",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-iotex-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(
'0xA00744882684C3e4747fAEFd68D283eA44099D03',
'latest',
'latest'
);
console.log('Transfer events:', events);
```
```python
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-iotex-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(
'0xA00744882684C3e4747fAEFd68D283eA44099D03',
'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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
contractAddress := common.HexToAddress("0xA00744882684C3e4747fAEFd68D283eA44099D03")
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 - IoTeX RPC Method
# eth_getStorageAt
Returns the value from a storage position at a given address on IoTeX.
## Use Cases
- **Contract analysis** - Read raw storage values
- **State verification** - Verify contract state
- **Security auditing** - Analyze storage layout for decentralized physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
- **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": [
"0xA00744882684C3e4747fAEFd68D283eA44099D03",
"0x0",
"latest"
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getStorageAt",
"params": [
"0xA00744882684C3e4747fAEFd68D283eA44099D03",
"0x0",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY');
const address = '0xA00744882684C3e4747fAEFd68D283eA44099D03';
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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'))
address = '0xA00744882684C3e4747fAEFd68D283eA44099D03'
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 - IoTeX RPC Method
# eth_getTransactionByHash
Returns the information about a transaction by transaction hash on IoTeX.
> **Why IoTeX?** Build on the leading DePIN infrastructure blockchain powering 130+ applications in the $27B+ DePIN ecosystem with W3bstream offchain compute, Quicksilver AI data verification, Vodafone partnership for 5M+ cell tower integration, and ioID device identity.
## 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 physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
- **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": ["0x839fcf7f5deeefd02960f393f67a9a2b8ee993683d397757c74edf1667ffb0f8"],
"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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionByHash",
"params": ["0x839fcf7f5deeefd02960f393f67a9a2b8ee993683d397757c74edf1667ffb0f8"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY');
const txHash = '0x839fcf7f5deeefd02960f393f67a9a2b8ee993683d397757c74edf1667ffb0f8';
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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0x839fcf7f5deeefd02960f393f67a9a2b8ee993683d397757c74edf1667ffb0f8'
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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0x839fcf7f5deeefd02960f393f67a9a2b8ee993683d397757c74edf1667ffb0f8")
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 - IoTeX RPC Method
# eth_getTransactionCount
Returns the number of transactions sent from an address on IoTeX (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 physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
## 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": [
"0xA00744882684C3e4747fAEFd68D283eA44099D03",
"latest"
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [
"0xA00744882684C3e4747fAEFd68D283eA44099D03",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY');
const address = '0xA00744882684C3e4747fAEFd68D283eA44099D03';
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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'))
address = '0xA00744882684C3e4747fAEFd68D283eA44099D03'
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 - IoTeX RPC Method
# eth_getTransactionReceipt
Returns the receipt of a transaction by transaction hash on IoTeX. Receipt is only available for mined transactions.
> **Why IoTeX?** Build on the leading DePIN infrastructure blockchain powering 130+ applications in the $27B+ DePIN ecosystem with W3bstream offchain compute, Quicksilver AI data verification, Vodafone partnership for 5M+ cell tower integration, and ioID device identity.
## 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 physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `transactionHash` | `DATA` | Yes | 32-byte transaction hash |
## Request
```json
{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0x839fcf7f5deeefd02960f393f67a9a2b8ee993683d397757c74edf1667ffb0f8"],
"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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0x839fcf7f5deeefd02960f393f67a9a2b8ee993683d397757c74edf1667ffb0f8"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY');
const txHash = '0x839fcf7f5deeefd02960f393f67a9a2b8ee993683d397757c74edf1667ffb0f8';
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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0x839fcf7f5deeefd02960f393f67a9a2b8ee993683d397757c74edf1667ffb0f8'
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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0x839fcf7f5deeefd02960f393f67a9a2b8ee993683d397757c74edf1667ffb0f8")
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(Iotex)
# eth_hashrate
Get node hashrate on the IoTeX 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-iotex-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-iotex-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 [IoTeX documentation](/docs/arbitrum).*
---
## eth_maxPriorityFeePerGas - IoTeX RPC Method
# eth_maxPriorityFeePerGas
Returns the current recommended priority fee per gas on IoTeX 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 physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
## 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-iotex-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-iotex-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-iotex-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(Iotex)
# eth_mining
Check if node is mining on the IoTeX 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-iotex-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-iotex-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 [IoTeX documentation](/docs/arbitrum).*
---
## eth_newBlockFilter - IoTeX RPC Method
# eth_newBlockFilter
Creates a filter on IoTeX 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-iotex-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-iotex-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 - IoTeX RPC Method
# eth_newFilter
Creates a filter object on IoTeX to notify when state changes (logs).
## Use Cases
- **Event monitoring** - Subscribe to contract events
- **Real-time updates** - Track events for decentralized physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
- **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": "0xA00744882684C3e4747fAEFd68D283eA44099D03",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
}],
"id": 1
}
```
## Returns
| Type | Description |
|------|-------------|
| `QUANTITY` | Filter ID |
## Code Examples
```bash
curl -X POST https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_newFilter",
"params": [{
"fromBlock": "latest",
"address": "0xA00744882684C3e4747fAEFd68D283eA44099D03"
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY');
// Create filter
const filterId = await provider.send('eth_newFilter', [{
fromBlock: 'latest',
address: '0xA00744882684C3e4747fAEFd68D283eA44099D03',
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 - IoTeX RPC Method
# eth_newPendingTransactionFilter
Creates a filter on IoTeX 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-iotex-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-iotex-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(Iotex)
# eth_protocolVersion
Get protocol version on the IoTeX 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-iotex-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-iotex-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 [IoTeX documentation](/docs/arbitrum).*
---
## eth_sendRawTransaction - IoTeX RPC Method
# eth_sendRawTransaction
Submits a pre-signed transaction for broadcast to IoTeX.
> **Why IoTeX?** Build on the leading DePIN infrastructure blockchain powering 130+ applications in the $27B+ DePIN ecosystem with W3bstream offchain compute, Quicksilver AI data verification, Vodafone partnership for 5M+ cell tower integration, and ioID device identity.
## 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 physical infrastructure (DePIN), IoT device identity (ioID), and AI-verified real-world data
- **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-iotex-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-iotex-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-iotex-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-iotex-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("0xA00744882684C3e4747fAEFd68D283eA44099D03")
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...(Iotex)
# eth_sendTransaction
> **Important**: Dwellir's shared IoTeX 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-iotex-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":-32603,"message":"method not implemented"}}
```
Need help? Contact our [support team](mailto:support@dwellir.com) or use the dedicated [`eth_sendRawTransaction`](./eth_sendRawTransaction) guide.
---
## eth_signTransaction - Sign transaction (rarely...(Iotex)
# 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-iotex-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-iotex-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 [IoTeX documentation](/docs/iotex).*
---
## eth_syncing - IoTeX RPC Method
# eth_syncing
Returns syncing status of IoTeX 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-iotex-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-iotex-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 - IoTeX RPC Method
# eth_uninstallFilter
Uninstalls a filter on IoTeX. 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-iotex-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-iotex-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
---
## IoTeX - The Leading Blockchain for IoT and DePIN
# IoTeX - The Blockchain for Real-World Data and Devices
## Why Build on IoTeX?
IoTeX is the leading blockchain platform for Internet of Things (IoT) and Decentralized Physical Infrastructure Networks (DePIN). Purpose-built for connecting the physical and digital worlds, IoTeX offers:
### 🌐 **IoT & Machine Integration**
- **Native device connectivity** - Direct integration with billions of IoT devices
- **W3bstream** - Off-chain compute for real-world data processing
- **MachineFi** - Financialize machine resources and data
- **Trusted IoT data** - Verifiable proofs for device-generated data
### ⚡ **High Performance Infrastructure**
- **5-second block time** - Fast finality for real-time applications
- **Ultra-low fees** - Optimized for high-frequency IoT transactions
- **10,000+ TPS** - Scale for billions of device interactions
- **EVM compatibility** - Deploy existing Ethereum dApps instantly
### 🔒 **Privacy & Security**
- **Roll-DPoS consensus** - Randomized delegated proof-of-stake
- **Trusted Execution Environment** - Secure computation for sensitive data
- **Privacy-preserving computation** - Process data without exposure
- **Device identity** - Decentralized identity for IoT devices
### 🏗️ **DePIN Ecosystem Leader**
- **$3B+ market cap** - Top DePIN infrastructure blockchain
- **100+ DePIN projects** - Largest decentralized infrastructure ecosystem
- **Real-world assets** - Tokenize and trade physical infrastructure
- **Global device network** - Connected devices across 70+ countries
## Quick Start with IoTeX
Connect to IoTeX in seconds with Dwellir's optimized endpoints:
### Installation & Setup
```javascript
// Connect to IoTeX mainnet
const provider = new JsonRpcProvider(
'https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'
);
// Get the latest block
const block = await provider.getBlock('latest');
console.log('Latest block:', block.number);
// Query IOTX balance
const balance = await provider.getBalance('0x...');
console.log('IOTX Balance:', balance.toString());
// Interact with IoT device registry
const deviceRegistry = new Contract(registryAddress, abi, provider);
const deviceData = await deviceRegistry.getDeviceData('device_id');
```
```javascript
const Web3 = require('web3');
// Connect to IoTeX mainnet
const web3 = new Web3(
'https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'
);
// Verify connection to IoTeX (Chain ID: 4689)
const chainId = await web3.eth.getChainId();
console.log('Connected to IoTeX:', chainId === 4689);
// Get gas price optimized for IoT transactions
const gasPrice = await web3.eth.getGasPrice();
console.log('IoT-optimized gas price:', gasPrice);
// Read IoT sensor data from smart contract
const sensorContract = new web3.eth.Contract(abi, contractAddress);
const data = await sensorContract.methods.getLatestReading().call();
```
```typescript
// Define IoTeX chain
const iotex = defineChain({
id: 4689,
name: 'IoTeX',
network: 'iotex',
nativeCurrency: {
decimals: 18,
name: 'IoTeX',
symbol: 'IOTX',
},
rpcUrls: {
default: {
http: ['https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'],
},
},
blockExplorers: {
default: { name: 'IoTeXScan', url: 'https://iotexscan.io' },
},
});
// Create IoTeX client
const client = createPublicClient({
chain: iotex,
transport: http(),
});
// Read IoT device data
const deviceStatus = await client.readContract({
address: '0x...',
abi: deviceAbi,
functionName: 'getDeviceStatus',
args: ['device_001'],
});
```
## Network Information
Chain ID
4689
Mainnet
Block Time
5 seconds
Average
Gas Token
IOTX
Native token
Consensus
Roll-DPoS
Randomized DPoS
## JSON-RPC API Reference
IoTeX supports the full [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/) plus custom methods for IoT and DePIN functionality. Access all standard EVM methods for seamless integration.
## IoT & DePIN Integration Patterns
### 🔌 Device Registration & Management
Register and manage IoT devices on-chain:
```javascript
// Device registration contract
const DeviceRegistry = {
// Register new IoT device
async registerDevice(deviceId, metadata) {
const tx = await contract.registerDevice(
deviceId,
metadata.manufacturer,
metadata.model,
metadata.location,
{ gasLimit: 100000 }
);
return tx.wait();
},
// Update device status
async updateDeviceStatus(deviceId, status, timestamp) {
const signature = await signDeviceData(deviceId, status, timestamp);
return contract.updateStatus(deviceId, status, timestamp, signature);
},
// Query device history
async getDeviceHistory(deviceId, fromBlock = 0) {
const filter = contract.filters.DeviceUpdate(deviceId);
return contract.queryFilter(filter, fromBlock);
}
};
```
### 📊 W3bstream Data Processing
Process IoT data off-chain with verifiable proofs:
```javascript
// W3bstream integration for IoT data
class W3bstreamProcessor {
constructor(endpoint) {
this.endpoint = endpoint;
this.provider = new JsonRpcProvider(
'https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'
);
}
// Submit IoT data for processing
async submitData(deviceId, data) {
// Create data proof
const proof = await this.createProof(deviceId, data);
// Submit to W3bstream
const result = await fetch(`${this.endpoint}/submit`, {
method: 'POST',
body: JSON.stringify({
deviceId,
data,
proof,
timestamp: Date.now()
})
});
// Store proof on-chain
const tx = await this.storeProof(proof);
return { proofId: tx.hash, result: await result.json() };
}
// Verify data authenticity
async verifyData(proofId) {
const proof = await this.contract.getProof(proofId);
return this.verifyProof(proof);
}
}
```
### 🏭 DePIN Infrastructure
Build decentralized physical infrastructure:
```javascript
// DePIN node management
const DePINManager = {
// Register infrastructure node
async registerNode(nodeInfo) {
const stake = ethers.parseEther('1000'); // Minimum stake
const tx = await contract.registerNode(
nodeInfo.id,
nodeInfo.type, // 'sensor', 'gateway', 'compute'
nodeInfo.location,
nodeInfo.capabilities,
{ value: stake }
);
return tx.wait();
},
// Submit proof of work
async submitProofOfWork(nodeId, data) {
const proof = await generateWorkProof(nodeId, data);
return contract.submitProof(nodeId, proof);
},
// Claim rewards
async claimRewards(nodeId) {
const rewards = await contract.pendingRewards(nodeId);
if (rewards > 0) {
return contract.claimRewards(nodeId);
}
}
};
```
## Performance Best Practices
### 1. **Batch IoT Data Submissions**
Optimize for high-frequency sensor data:
```javascript
class BatchProcessor {
constructor() {
this.batch = [];
this.batchSize = 100;
}
async addReading(deviceId, data) {
this.batch.push({ deviceId, data, timestamp: Date.now() });
if (this.batch.length >= this.batchSize) {
await this.submitBatch();
}
}
async submitBatch() {
if (this.batch.length === 0) return;
const merkleRoot = this.calculateMerkleRoot(this.batch);
// Submit only merkle root on-chain
const tx = await contract.submitBatch(
merkleRoot,
this.batch.length,
{ gasLimit: 200000 }
);
// Store full data off-chain
await this.storeOffchain(this.batch, tx.hash);
this.batch = [];
return tx;
}
}
```
### 2. **Device Connection Pooling**
Manage multiple IoT device connections efficiently:
```javascript
class DeviceConnectionPool {
constructor(maxConnections = 100) {
this.pool = new Map();
this.maxConnections = maxConnections;
}
async getConnection(deviceId) {
if (!this.pool.has(deviceId)) {
if (this.pool.size >= this.maxConnections) {
this.evictOldest();
}
const connection = await this.createConnection(deviceId);
this.pool.set(deviceId, {
connection,
lastUsed: Date.now()
});
}
const poolEntry = this.pool.get(deviceId);
poolEntry.lastUsed = Date.now();
return poolEntry.connection;
}
evictOldest() {
let oldest = Date.now();
let oldestId = null;
for (const [id, entry] of this.pool.entries()) {
if (entry.lastUsed < oldest) {
oldest = entry.lastUsed;
oldestId = id;
}
}
if (oldestId) {
this.pool.delete(oldestId);
}
}
}
```
### 3. **Efficient Event Monitoring**
Monitor device events with minimal overhead:
```javascript
class EventMonitor {
constructor(provider) {
this.provider = provider;
this.filters = new Map();
}
async watchDevice(deviceId, callback) {
// Create optimized filter
const filter = {
address: CONTRACT_ADDRESS,
topics: [
ethers.id('DeviceUpdate(string,uint256,bytes32)'),
ethers.id(deviceId)
]
};
// Use WebSocket for real-time updates
this.provider.on(filter, async (log) => {
const parsed = this.parseLog(log);
await callback(parsed);
});
this.filters.set(deviceId, filter);
}
stopWatching(deviceId) {
const filter = this.filters.get(deviceId);
if (filter) {
this.provider.off(filter);
this.filters.delete(deviceId);
}
}
}
```
## Troubleshooting Common Issues
### Error: "Device not registered"
Ensure IoT devices are properly registered before submitting data:
```javascript
async function ensureDeviceRegistered(deviceId) {
try {
const device = await contract.getDevice(deviceId);
return device.isActive;
} catch (error) {
if (error.message.includes('Device not found')) {
// Auto-register device
await contract.registerDevice(
deviceId,
DEFAULT_METADATA,
{ gasLimit: 150000 }
);
return true;
}
throw error;
}
}
```
### Error: "Invalid sensor data format"
Validate IoT data before submission:
```javascript
function validateSensorData(data) {
const required = ['deviceId', 'timestamp', 'value'];
for (const field of required) {
if (!data[field]) {
throw new Error(`Missing required field: ${field}`);
}
}
// Validate timestamp is recent (within 5 minutes)
const fiveMinutes = 5 * 60 * 1000;
if (Date.now() - data.timestamp > fiveMinutes) {
throw new Error('Timestamp too old');
}
// Validate value ranges
if (data.value < MIN_VALUE || data.value > MAX_VALUE) {
throw new Error('Value out of range');
}
return true;
}
```
### Error: "W3bstream proof verification failed"
Handle W3bstream proof errors:
```javascript
async function submitWithRetry(data, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const proof = await w3bstream.generateProof(data);
const tx = await contract.submitProof(proof);
return tx;
} catch (error) {
if (error.message.includes('proof verification')) {
// Regenerate proof with fresh nonce
data.nonce = Date.now();
continue;
}
throw error;
}
}
throw new Error('Failed to submit proof after retries');
}
```
## Migration Guide
### From Ethereum/EVM Chains
IoTeX is fully EVM-compatible with additional IoT features:
```javascript
// Before (Ethereum)
const provider = new JsonRpcProvider('https://eth-mainnet.example.com');
const contract = new Contract(address, abi, provider);
// After (IoTeX)
const provider = new JsonRpcProvider(
'https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'
);
const contract = new Contract(address, abi, provider);
// ✅ All Ethereum tools work
// ✅ Same development workflow
// ✅ Additional IoT capabilities
// ⚠️ Different chain ID (4689)
// ⚠️ IOTX as gas token (not ETH)
// 🎉 Access to W3bstream and MachineFi
```
### Integrating IoT Devices
Connect physical devices to IoTeX:
```javascript
// Device SDK integration
const device = new IoTeXDevice({
deviceId: 'sensor_001',
privateKey: process.env.DEVICE_KEY,
endpoint: 'https://api-iotex-mainnet.n.dwellir.com/YOUR_API_KEY'
});
// Auto-submit sensor readings
device.on('reading', async (data) => {
await device.submitToBlockchain(data);
});
// Start monitoring
device.startMonitoring({
interval: 60000, // Every minute
sensors: ['temperature', 'humidity']
});
```
## Resources & Tools
### Official Resources
- [IoTeX Documentation](https://docs.iotex.io)
- [IoTeX Explorer](https://iotexscan.io)
- [W3bstream Docs](https://docs.w3bstream.com)
### Developer Tools
- [IoTeX Developer Portal](https://developers.iotex.io/)
- [IoTeX GitHub](https://github.com/iotexproject)
- [IoTeX Core](https://github.com/iotexproject/iotex-core)
### DePIN Resources
- [DePINscan Explorer](https://depinscan.io)
- [MachineFi Portal](https://machinefi.com)
- [IoTeX DePIN Guide](https://docs.iotex.io/depin)
### Need Help?
- 📧 **Email**: support@dwellir.com
- 📚 **Docs**: You're here!
- 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com)
---
*Start building IoT and DePIN applications on IoTeX with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## net_listening - IoTeX RPC Method
# net_listening
Returns `true` if client is actively listening for network connections on IoTeX.
## 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-iotex-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-iotex-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 - IoTeX RPC Method
# net_peerCount
Returns number of peers currently connected to IoTeX 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-iotex-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-iotex-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 - IoTeX RPC Method
# net_version
Returns the current network ID on IoTeX.
## 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-iotex-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-iotex-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 - IoTeX RPC Method
# web3_clientVersion
Returns the current client version on IoTeX.
## 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-iotex-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-iotex-mainnet.n.dwellir.com/YOUR_API_KEY');
const version = await provider.send('web3_clientVersion', []);
console.log('Client version:', version);
```
---
## web3_sha3 - IoTeX RPC Method
# web3_sha3
Returns Keccak-256 (not standard SHA3-256) of the given data on IoTeX.
## 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-iotex-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-iotex-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 - Kusama RPC Method
# author_pendingExtrinsics
Returns all pending extrinsics in the transaction pool on Kusama.
## Use Cases
- **Mempool monitoring** - Track pending transactions
- **Transaction status** - Check if your transaction is pending for parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "author_pendingExtrinsics",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Kusama RPC Method
# author_rotateKeys
Generate a new set of session keys on Kusama. 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 parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "author_rotateKeys",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Kusama 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 parachain experimentation, early feature deployment, and production-grade testing with real value
- **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('');
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 = ''
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 - Kusama RPC Method
# author_submitExtrinsic
Submit a signed extrinsic to Kusama for inclusion in a block.
## Use Cases
- **Transaction submission** - Broadcast signed transactions
- **dApp interactions** - Execute on-chain operations for parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "author_submitExtrinsic",
"params": ["0x..."],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Kusama RPC Method
# beefy_getFinalizedHead
Returns the block hash of the latest BEEFY-finalized block on Kusama. 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 parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "beefy_getFinalizedHead",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Kusama RPC Method
# chain_getBlock
Retrieves complete block information from Kusama, including the block header, extrinsics, and justifications.
> **Why Kusama?** Build on Polkadot's canary network for real-world testing with live economic conditions with 7-day governance cycles (vs 1 month on Polkadot), lower bonding requirements, live KSM token economy, and first-to-market feature testing.
## 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 parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "chain_getBlock",
"params": [],
"id": 1
}'
# Get specific block
curl \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "chain_getBlock",
"params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Kusama RPC Method
# chain_getBlockHash
Returns the block hash for a given block number on Kusama.
## Use Cases
- **Historical queries** - Convert block numbers to hashes
- **Block navigation** - Navigate blockchain history for parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "chain_getBlockHash",
"params": [1000000],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Kusama RPC Method
# chain_getFinalizedHead
Returns the hash of the last finalized block on Kusama.
## Use Cases
- **Confirmed state** - Query state that cannot be reverted
- **Transaction confirmation** - Verify transaction finality for parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "chain_getFinalizedHead",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Kusama RPC Method
# chain_getHeader
Returns the block header for a given hash on Kusama.
## Use Cases
- **Lightweight queries** - Get header without full block data
- **Chain synchronization** - Track block production for parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "chain_getHeader",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Kusama RPC Method
# chain_subscribeFinalizedHeads
Subscribe to receive notifications when blocks are finalized on Kusama. 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 parachain experimentation, early feature deployment, and production-grade testing with real value
- **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('');
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 = ''
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 - Kusama RPC Method
# chain_subscribeNewHeads
Subscribe to receive notifications when new block headers are produced on Kusama. This WebSocket subscription provides real-time updates for each new block.
## Use Cases
- **Block monitoring** - Track new blocks in real-time for parachain experimentation, early feature deployment, and production-grade testing with real value
- **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('');
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 = ''
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 - Kusama RPC Method
# grandpa_roundState
Returns the state of the current GRANDPA finality round on Kusama. GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) is the finality gadget used by Substrate chains.
## Use Cases
- **Finality monitoring** - Track consensus progress for parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "grandpa_roundState",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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)
---
## Kusama RPC with Dwellir
# Kusama – Polkadot's Canary Network for Rapid Innovation
## Why Build on Kusama?
Kusama is Polkadot’s canary network, offering the same Substrate architecture with faster governance and real economic conditions. It is the proving ground for runtime features before they ship to Polkadot, making it ideal for teams that need production-grade infrastructure with rapid iteration cycles.
### 🚀 **Fast Iteration with Economic Finality**
- Governance cycles finalize upgrades in **7 days**, letting you ship runtime changes weeks before Polkadot equivalents.
- Real staking economics and on-chain treasury make Kusama suitable for live user pilots and incentivized testing.
- Shared validator set delivers secure finality (~6s blocks) while preserving flexibility for experimental features.
### 🧪 **Early Access to Substrate Innovations**
- New runtime pallets, XCM improvements, and networking upgrades land on Kusama first, giving you a head start on upcoming Polkadot capabilities.
- Developers can validate performance at scale without waiting for Polkadot release windows.
- Canary parachains (Statemine, Karura, Hydration, and more) provide a rich ecosystem for cross-chain experimentation.
### 🌐 **Production Tooling & Ecosystem Depth**
- Fully compatible with the Polkadot JS stack, Subxt, py-substrate-interface, and Dwellir Sidecar REST APIs.
- Rich telemetry, explorers (Subscan, Statescan), and infrastructure partners support monitoring and analytics.
- Seamlessly migrate winning features to Polkadot once product-market fit is proven.
## Quick Start with Kusama
Connect to Kusama’s relay chain endpoints and Sidecar REST surface with Dwellir.
### Installation & Setup
```bash
curl -s https://api-kusama.n.dwellir.com/YOUR_API_KEY \
-H 'Content-Type: application/json' \
-d '{
"jsonrpc": "2.0",
"method": "chain_getHeader",
"params": [],
"id": 1
}'
```
```typescript
async function main() {
const provider = new WsProvider('wss://api-kusama.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 finalized blocks
const unsub = await api.rpc.chain.subscribeFinalizedHeads((header) => {
console.log(`Finalized block #${header.number} at ${header.hash}`);
});
// Stop subscription after 3 blocks
setTimeout(async () => {
await unsub();
await api.disconnect();
}, 18000);
}
main().catch(console.error);
```
```rust
use subxt::{OnlineClient, PolkadotConfig};
#[subxt::subxt(runtime_metadata_path = "./metadata/kusama.scale" )]
pub mod kusama {}
#[tokio::main]
async fn main() -> Result<(), Box> {
let api = OnlineClient::::from_url(
"wss://api-kusama.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());
let account = api.storage().system().account(
&"E8MByjWbS49hmzFM1U5rvFJES1Xgz1TSBAZLiYqZQiFTNUY".parse()?
).await?;
println!("Free balance: {} KSM", account.data.free);
Ok(())
}
```
```python
from substrateinterface import SubstrateInterface
substrate = SubstrateInterface(
url="wss://api-kusama.n.dwellir.com/YOUR_API_KEY",
type_registry_preset="kusama"
)
chain = substrate.rpc_request("system_chain", [])
print(f"Connected to {chain['result']}")
head = substrate.rpc_request("chain_getFinalizedHead", [])
print(f"Finalized head: {head['result']}")
account_info = substrate.query(
module='System',
storage_function='Account',
params=['E8MByjWbS49hmzFM1U5rvFJES1Xgz1TSBAZLiYqZQiFTNUY']
)
print(f"Free: {account_info['data']['free']}")
```
## Network Information
Genesis Hash
0xb0a8d493…3dafe
Relay chain
Native Token
KSM
12 decimals
SS58 Prefix
2
Address format
Runtime Spec Version
1007001
As of 3 Oct 2025
Transaction Version
26
state_getRuntimeVersion
Explorer
Subscan
kusama.subscan.io
Kusama operates as a relay chain without a parent relay. Parachain IDs are allocated per project; refer to individual parachain docs for cross-chain calls. Runtime and transaction versions above reflect the live values queried via `state_getRuntimeVersion` on 3 October 2025.
## Substrate JSON-RPC API Reference
Kusama exposes the same Substrate RPC namespaces as Polkadot, covering node telemetry, block production, storage access, and finality tracking. Use the tables below to open the method guides for each namespace.
### Core Substrate namespaces
| Namespace | Purpose | Key Methods |
|-----------|---------|-------------|
| `system_*` | Inspect node state, peers, and runtime metadata. | [`system_chain`](/kusama/system_chain), [`system_health`](/kusama/system_health), [`system_properties`](/kusama/system_properties), [`system_version`](/kusama/system_version) |
| `chain_*` | Retrieve blocks, headers, and follow finality streams. | [`chain_getHeader`](/kusama/chain_getHeader), [`chain_getBlockHash`](/kusama/chain_getBlockHash), [`chain_getFinalizedHead`](/kusama/chain_getFinalizedHead), [`chain_subscribeNewHeads`](/kusama/chain_subscribeNewHeads), [`chain_subscribeFinalizedHeads`](/kusama/chain_subscribeFinalizedHeads) |
| `state_*` | Read storage, fetch metadata, and call runtime APIs. | [`state_getStorage`](/kusama/state_getStorage), [`state_getKeys`](/kusama/state_getKeys), [`state_getKeysPaged`](/kusama/state_getKeysPaged), [`state_getMetadata`](/kusama/state_getMetadata), [`state_getRuntimeVersion`](/kusama/state_getRuntimeVersion), [`state_call`](/kusama/state_call) |
| `author_*` | Submit extrinsics and manage transaction queues. | [`author_submitExtrinsic`](/kusama/author_submitExtrinsic), [`author_submitAndWatchExtrinsic`](/kusama/author_submitAndWatchExtrinsic), [`author_pendingExtrinsics`](/kusama/author_pendingExtrinsics), [`author_rotateKeys`](/kusama/author_rotateKeys) |
| `rpc_methods` | Discover every RPC namespace exposed by the node. | [`rpc_methods`](/kusama/rpc_methods) |
### Finality and relay tracking
| Namespace | Purpose | Key Methods |
|-----------|---------|-------------|
| `grandpa_*` | Inspect GRANDPA voting rounds and validator thresholds. | [`grandpa_roundState`](/kusama/grandpa_roundState) |
| `beefy_*` | Track parachain proofs relayed through BEEFY. | [`beefy_getFinalizedHead`](/kusama/beefy_getFinalizedHead) |
## Common Integration Patterns
### Track Finality with GRANDPA and BEEFY
```typescript
const finalizedHeads = await api.rpc.chain.subscribeFinalizedHeads((header) => {
console.log(`GRANDPA finalized #${header.number}`);
});
const beefySub = await api.rpc.beefy.subscribeJustifications((event) => {
console.log('BEEFY justification', event);
});
```
Combine GRANDPA finalized heads with `beefy_subscribeJustifications` to monitor parachain finality for bridges and XCMP relayers.
### Paginate Large Storage Scans
```typescript
const page = await api.rpc.state.getKeysPaged(
'0x26aa394eea5630e07c48ae0c9558cef7b99d880ec681799c0cf30e8886371da9',
100,
'0x',
null
);
console.log('Fetched', page.length, 'System.Account keys');
```
Use `state_getKeysPaged` with archive access to traverse large storage maps without overwhelming RPC quotas.
### Decode Fees Before Submission
```typescript
const ext = api.tx.balances.transferAllowDeath(dest, amount);
const info = await api.rpc.payment.queryInfo(ext.toHex());
console.log(`PartialFee: ${info.partialFee.toHuman()}`);
```
Estimate transaction costs using `payment_queryInfo` so you can bound fees before broadcasting to Kusama.
## Performance Best Practices
- Prefer WebSocket connections for subscriptions, finality, and multi-round queries.
- Cache runtime metadata (`api.runtimeVersion`, type bundles) and reuse the ApiPromise instance across requests.
- Shard heavy workloads across archive nodes if you need deep historical access; avoid full-chain scans without pagination.
- Back off exponentially on retries when encountering `isSyncing` or transient `-32010` errors.
- Use Sidecar REST for read-heavy explorers when SCALE decoding is unnecessary.
## Troubleshooting
- **WebSocket handshake fails** – Confirm your API key is appended exactly as provided and outbound TCP/443 is open.
- **Invalid SS58 address** – Ensure addresses use prefix `2`. Convert from Polkadot (prefix 0) with `@polkadot/util-crypto` helpers.
- **Type errors in clients** – Refresh metadata (`api.runtimeMetadata`) after runtime upgrades; Kusama upgrades more frequently than Polkadot.
- **Extrinsic rejected** – Decode the dispatch error via `api.registry.findMetaError` to surface module/error details.
- **rateLimit/TooManyRequests** – Implement per-IP backoff and share a single connection pool across services.
## Smoke Tests
Run these baseline checks against production endpoints (values captured 3 Oct 2025):
```bash
# Node health (peers: 68, isSyncing: false)
curl -s https://api-kusama.n.dwellir.com/YOUR_API_KEY \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"system_health","params":[]}'
# Latest block header (#30363294)
curl -s https://api-kusama.n.dwellir.com/YOUR_API_KEY \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"chain_getHeader","params":[]}'
# Block hash for #30363295 (0x028651…2e0c)
curl -s https://api-kusama.n.dwellir.com/YOUR_API_KEY \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"chain_getBlockHash","params":["0x1cf4e9f"]}'
# Runtime version (specVersion 1007001, transactionVersion 26)
curl -s https://api-kusama.n.dwellir.com/YOUR_API_KEY \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"state_getRuntimeVersion","params":[]}'
```
Verify the response fields match the expected peers, block numbers, hashes, and version metadata before onboarding workloads.
## Migration Guide
- **Endpoints** – Replace Polkadot RPC URLs with `https://api-kusama.n.dwellir.com/YOUR_API_KEY` or `wss://api-kusama.n.dwellir.com/YOUR_API_KEY` across services.
- **Addresses** – Re-encode SS58 addresses with prefix `2`; Polkadot addresses (prefix 0) are not valid on Kusama.
- **Runtime Types** – Update your custom type bundles to match the Kusama spec (`specVersion 1007001` as of Oct 2025) and refresh metadata caches after each upgrade.
- **Fee Calibration** – Kusama uses different fee multipliers; re-run `payment_queryInfo` and adjust heuristics for tipping and priority fees.
- **Bridges & XCM** – Confirm target parachain IDs and HRMP channels; Kusama pairs differ from Polkadot equivalents.
## Resources & Tools
- [Kusama Network Portal](https://kusama.network/)
- [Kusama Subscan Explorer](https://kusama.subscan.io)
- [Polkadot Wiki – Kusama Section](https://wiki.polkadot.network/docs/kusama)
- [Parity Telemetry – Kusama](https://telemetry.polkadot.io/#list/Kusama)
- [Substrate Developer Hub](https://docs.substrate.io/)
- [Dwellir Dashboard – Get your API key](https://dashboard.dwellir.com/register)
---
## payment_queryFeeDetails - Kusama RPC Method
# payment_queryFeeDetails
Returns a detailed breakdown of fees for a given extrinsic on Kusama. 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 parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "payment_queryFeeDetails",
"params": ["0x...encodedExtrinsic"],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
# 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 - Kusama RPC Method
# payment_queryInfo
Estimates the fee for an extrinsic on Kusama.
## Use Cases
- **Fee estimation** - Calculate transaction costs before sending
- **UI display** - Show fees to users for parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "payment_queryInfo",
"params": ["0x..."],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Kusama RPC Method
# rpc_methods
Returns a list of all RPC methods available on Kusama.
## Use Cases
- **API discovery** - List all available methods
- **Compatibility checking** - Verify method availability for parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "rpc_methods",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Kusama RPC Method
# state_call
Calls a runtime API method on Kusama.
## Use Cases
- **Runtime computations** - Execute runtime logic without transactions
- **Account queries** - Use AccountNonceApi for parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-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('');
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(Kusama)
## 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-kusama.n.dwellir.com/YOUR_API_KEY/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-kusama.n.dwellir.com/YOUR_API_KEY/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-kusama.n.dwellir.com/YOUR_API_KEY/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-kusama.n.dwellir.com/YOUR_API_KEY/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`](/kusama/state_getKeysPaged) - Get keys with pagination
- [`state_getStorage`](/kusama/state_getStorage) - Get storage value
- [`state_getMetadata`](/kusama/state_getMetadata) - Get metadata to decode keys
---
## state_getKeysPaged - Kusama RPC Method
# state_getKeysPaged
Returns storage keys with pagination on Kusama.
## Use Cases
- **Storage iteration** - Enumerate storage map entries
- **Data export** - Bulk export chain data for parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "state_getKeysPaged",
"params": ["0x26aa394eea5630e07c48ae0c9558cef7", 100],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Kusama RPC Method
# state_getMetadata
Returns the runtime metadata on Kusama.
## Use Cases
- **Runtime introspection** - Discover available pallets and calls
- **Extrinsic building** - Get call and type information for parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "state_getMetadata",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Kusama RPC Method
# state_getRuntimeVersion
Returns the runtime version on Kusama.
## Use Cases
- **Version checking** - Verify runtime compatibility
- **Upgrade detection** - Monitor for runtime upgrades on parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "state_getRuntimeVersion",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Kusama RPC Method
# state_getStorage
Returns a storage entry at a specific key on Kusama.
> **Why Kusama?** Build on Polkadot's canary network for real-world testing with live economic conditions with 7-day governance cycles (vs 1 month on Polkadot), lower bonding requirements, live KSM token economy, and first-to-market feature testing.
## Use Cases
- **State queries** - Read on-chain storage values
- **Account balances** - Query account data for parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "state_getStorage",
"params": [""],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Kusama RPC Method
# state_queryStorageAt
Query multiple storage keys at a specific block on Kusama.
## Use Cases
- **Batch queries** - Efficiently query multiple storage items
- **Snapshot state** - Get consistent multi-key state for parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "state_queryStorageAt",
"params": [[""]],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Kusama RPC Method
# system_chain
Returns the chain name on Kusama.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_chain",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "system_chain",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Kusama RPC Method
# system_health
Returns the health status of the Kusama node.
## Use Cases
- **Health checks** - Monitor node availability
- **Load balancing** - Route traffic based on health for parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "system_health",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Kusama RPC Method
# system_name
Returns the node implementation name on Kusama.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_name",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "system_name",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Kusama RPC Method
# system_properties
Returns chain properties including token symbol and decimals on Kusama.
## Use Cases
- **Token formatting** - Get decimals and symbol for parachain experimentation, early feature deployment, and production-grade testing with real value
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "system_properties",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Kusama RPC Method
# system_version
Returns the node implementation version on Kusama.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_version",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "system_version",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Linea RPC Method
# debug_traceBlock
Traces all transactions in a block on Linea 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 enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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-linea-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-linea-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 - Linea RPC Method
# debug_traceBlockByHash
Traces all transactions in a block on Linea 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": ["0xa5de967d7d780c598c5568e1489bdf66613aa11f7acbd7de75725ee4382c027b", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceBlockByHash",
"params": ["0xa5de967d7d780c598c5568e1489bdf66613aa11f7acbd7de75725ee4382c027b", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0xa5de967d7d780c598c5568e1489bdf66613aa11f7acbd7de75725ee4382c027b';
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 - Linea RPC Method
# debug_traceBlockByNumber
Traces all transactions in a block on Linea 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-linea-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-linea-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 - Linea RPC Method
# debug_traceCall
Traces a call without creating a transaction on Linea.
:::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 enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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": "0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"data": "0x70a08231000000000000000000000000e5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f"
},
"latest",
{}
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceCall",
"params": [
{"to": "0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f", "data": "0x70a08231000000000000000000000000e5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f"},
"latest",
{"tracer": "callTracer"}
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const trace = await provider.send('debug_traceCall', [
{ to: '0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f', data: '0x70a08231000000000000000000000000e5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f' },
'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 - Linea RPC Method
# debug_traceTransaction
Traces a transaction execution on Linea 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 enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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": ["0xc9e9cb9405a8e526ee8eb21e2aae56fe6df29590f8e4d44148f15c8f6a263128", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceTransaction",
"params": ["0xc9e9cb9405a8e526ee8eb21e2aae56fe6df29590f8e4d44148f15c8f6a263128", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const txHash = '0xc9e9cb9405a8e526ee8eb21e2aae56fe6df29590f8e4d44148f15c8f6a263128';
// 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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0xc9e9cb9405a8e526ee8eb21e2aae56fe6df29590f8e4d44148f15c8f6a263128'
# 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 - Linea RPC Method
# eth_accounts
Returns a list of addresses owned by the client on Linea.
> **Why Linea?** Build on Consensys-backed zkEVM L2 with $1B+ TVL and 807% growth in 2025 with 15-30x lower fees than Ethereum mainnet, 6,200 TPS throughput, SWIFT integration with 12+ institutions, and $725M Consensys backing.
## 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, DeFi builders, and teams seeking Consensys ecosystem integration 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-linea-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-linea-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-linea-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-linea-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-linea-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-linea-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 - Linea RPC Method
# eth_blockNumber
Returns the number of the most recent block on Linea.
> **Why Linea?** Build on Consensys-backed zkEVM L2 with $1B+ TVL and 807% growth in 2025 with 15-30x lower fees than Ethereum mainnet, 6,200 TPS throughput, SWIFT integration with 12+ institutions, and $725M Consensys backing.
## When to Use This Method
`eth_blockNumber` is fundamental for enterprise developers, DeFi builders, and teams seeking Consensys ecosystem integration:
- **Syncing Applications** — Keep your dApp in sync with the latest Linea blockchain state
- **Transaction Monitoring** — Verify confirmations by comparing block numbers
- **Event Filtering** — Set the correct block range for querying logs on enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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-linea-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-linea-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('Linea block:', blockNumber);
// Using ethers.js
const provider = new JsonRpcProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const blockNumber = await provider.getBlockNumber();
console.log('Linea block:', blockNumber);
```
```python
def get_block_number():
response = requests.post(
'https://api-linea-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'Linea block: {block_number}')
# Using web3.py
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
print(f'Linea 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-linea-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("Linea block: %d\n", blockNumber)
}
```
## Common Use Cases
### 1. Block Confirmation Counter
Monitor transaction confirmations on Linea:
```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 Linea:
```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 Linea 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-linea-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 - Linea RPC Method
# eth_call
Executes a new message call immediately without creating a transaction on Linea. Used for reading smart contract state.
> **Why Linea?** Build on Consensys-backed zkEVM L2 with $1B+ TVL and 807% growth in 2025 with 15-30x lower fees than Ethereum mainnet, 6,200 TPS throughput, SWIFT integration with 12+ institutions, and $725M Consensys backing.
## 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 enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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": "0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"data": "0x70a08231000000000000000000000000e5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f"
},
"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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_call",
"params": [{
"to": "0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"data": "0x70a08231000000000000000000000000e5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f"
}, "latest"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-linea-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-linea-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(
'0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f',
'0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f'
)
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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
contractAddress := common.HexToAddress("0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f")
data := common.FromHex("0x70a08231000000000000000000000000e5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f")
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 - Linea RPC Method
# eth_chainId
Returns the chain ID used for transaction signing on Linea.
> **Why Linea?** Build on Consensys-backed zkEVM L2 with $1B+ TVL and 807% growth in 2025 with 15-30x lower fees than Ethereum mainnet, 6,200 TPS throughput, SWIFT integration with 12+ institutions, and $725M Consensys backing.
## 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-linea-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-linea-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-linea-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-linea-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(Linea)
# eth_coinbase
Get coinbase address on the Linea zkEVM 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-linea-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-linea-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 [Linea documentation](/docs/linea).*
---
## eth_estimateGas - Linea RPC Method
# eth_estimateGas
Estimates the gas necessary to execute a transaction on Linea.
> **Why Linea?** Build on Consensys-backed zkEVM L2 with $1B+ TVL and 807% growth in 2025 with 15-30x lower fees than Ethereum mainnet, 6,200 TPS throughput, SWIFT integration with 12+ institutions, and $725M Consensys backing.
## 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 enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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": "0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"to": "0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_estimateGas",
"params": [{
"from": "0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"to": "0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"value": "0x1"
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-linea-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-linea-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('0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f', 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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
toAddress := common.HexToAddress("0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f")
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(Linea)
# eth_estimateL1Fee
Estimate L1 data posting fee on the Linea zkEVM network. This method helps calculate the additional cost of posting transaction data to Ethereum L1 as part of Linea's zkEVM rollup architecture.
## Overview
Linea zkEVM is a Layer 2 rollup that periodically submits batched transaction data and proofs to Ethereum L1. While most transaction execution happens on L2 with low gas costs, there's an additional fee component for the L1 data availability costs.
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `transaction` | Object | Yes | Transaction object to estimate L1 fee for |
### Transaction Object
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `from` | Address | No | Sender address |
| `to` | Address | No | Recipient address |
| `gas` | Quantity | No | Gas limit |
| `gasPrice` | Quantity | No | Gas price in wei |
| `value` | Quantity | No | Value to transfer in wei |
| `data` | Data | No | Transaction data |
## Returns
| Type | Description |
|------|-------------|
| `QUANTITY` | Estimated L1 fee in wei |
## Implementation Example
```bash
curl -X POST https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_estimateL1Fee",
"params": [
{
"from": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5",
"to": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
"gas": "0x5208",
"gasPrice": "0x3b9aca00",
"value": "0x1bc16d674ec80000",
"data": "0x"
}
],
"id": 1
}'
```
```javascript
const response = await fetch('https://api-linea-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: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5',
to: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
gas: '0x5208',
gasPrice: '0x3b9aca00',
value: '0x1bc16d674ec80000',
data: '0x'
}
],
id: 1
})
});
const data = await response.json();
console.log('L1 Fee:', data.result);
// Advanced L1 fee estimation with transaction cost breakdown
class LineaFeeEstimator {
constructor(rpcUrl) {
this.rpcUrl = rpcUrl;
}
async estimateL1Fee(transaction) {
const response = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_estimateL1Fee',
params: [transaction],
id: 1
})
});
const data = await response.json();
if (data.error) {
throw new Error(`RPC Error: ${data.error.message}`);
}
return parseInt(data.result, 16);
}
async getFullFeeBreakdown(transaction) {
try {
// Estimate L2 gas cost
const l2GasResponse = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_estimateGas',
params: [transaction],
id: 1
})
});
const l2GasData = await l2GasResponse.json();
const l2GasEstimate = parseInt(l2GasData.result, 16);
// Get current gas price
const gasPriceResponse = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_gasPrice',
params: [],
id: 1
})
});
const gasPriceData = await gasPriceResponse.json();
const gasPrice = parseInt(gasPriceData.result, 16);
// Estimate L1 fee
const l1Fee = await this.estimateL1Fee(transaction);
// Calculate L2 execution cost
const l2ExecutionCost = l2GasEstimate * gasPrice;
return {
l1Fee: l1Fee,
l2ExecutionCost: l2ExecutionCost,
totalEstimatedCost: l1Fee + l2ExecutionCost,
gasEstimate: l2GasEstimate,
gasPrice: gasPrice,
breakdown: {
l1FeePercentage: ((l1Fee / (l1Fee + l2ExecutionCost)) * 100).toFixed(2),
l2FeePercentage: ((l2ExecutionCost / (l1Fee + l2ExecutionCost)) * 100).toFixed(2)
}
};
} catch (error) {
throw new Error(`Failed to get fee breakdown: ${error.message}`);
}
}
async compareFeesByDataSize(baseTransaction, dataSizes) {
const results = [];
for (const size of dataSizes) {
// Generate test data of specified size
const testData = '0x' + '00'.repeat(size);
const testTransaction = {
...baseTransaction,
data: testData
};
try {
const breakdown = await this.getFullFeeBreakdown(testTransaction);
results.push({
dataSize: size,
dataSizeKB: (size / 1024).toFixed(2),
l1Fee: breakdown.l1Fee,
l2ExecutionCost: breakdown.l2ExecutionCost,
totalCost: breakdown.totalEstimatedCost,
l1FeePerByte: breakdown.l1Fee / size,
costIncrease: size === dataSizes[0] ? 0 :
((breakdown.totalEstimatedCost - results[0].totalCost) / results[0].totalCost * 100).toFixed(2)
});
} catch (error) {
results.push({
dataSize: size,
error: error.message
});
}
}
return results;
}
async optimizeTransactionCost(transaction) {
const recommendations = [];
// Get baseline cost
const baseline = await this.getFullFeeBreakdown(transaction);
// Check if transaction has unnecessary data
if (transaction.data && transaction.data.length > 2) {
// Estimate with minimal data
const minimalTx = { ...transaction, data: '0x' };
const minimal = await this.getFullFeeBreakdown(minimalTx);
const dataCostSavings = baseline.l1Fee - minimal.l1Fee;
if (dataCostSavings > 0) {
recommendations.push({
type: 'data_optimization',
description: 'Consider reducing transaction data size',
potentialSavings: dataCostSavings,
savingsPercentage: ((dataCostSavings / baseline.totalEstimatedCost) * 100).toFixed(2)
});
}
}
// Check gas optimization
if (baseline.gasEstimate > 100000) {
recommendations.push({
type: 'gas_optimization',
description: 'High gas usage detected - consider optimizing contract calls',
currentGas: baseline.gasEstimate,
suggestion: 'Review contract logic for gas efficiency'
});
}
// Check if L1 fees dominate
if (parseFloat(baseline.breakdown.l1FeePercentage) > 70) {
recommendations.push({
type: 'l1_fee_dominance',
description: 'L1 fees represent majority of transaction cost',
l1Percentage: baseline.breakdown.l1FeePercentage,
suggestion: 'Consider batching transactions or reducing data payload'
});
}
return {
baseline: baseline,
recommendations: recommendations,
optimizationPotential: recommendations.length > 0
};
}
}
// Usage examples
const feeEstimator = new LineaFeeEstimator('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
// Basic L1 fee estimation
const l1Fee = await feeEstimator.estimateL1Fee({
from: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5',
to: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
value: '0x1bc16d674ec80000',
data: '0x'
});
console.log(`L1 Fee: ${l1Fee} wei`);
// Full fee breakdown
const breakdown = await feeEstimator.getFullFeeBreakdown({
from: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5',
to: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
value: '0x1bc16d674ec80000',
data: '0xa9059cbb000000000000000000000000recipient000000000000000000000000'
});
console.log('Fee Breakdown:', breakdown);
// Compare fees by data size
const dataSizeComparison = await feeEstimator.compareFeesByDataSize(
{
from: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5',
to: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913'
},
[0, 100, 500, 1000, 5000] // bytes
);
console.log('Data Size Impact:', dataSizeComparison);
// Optimization suggestions
const optimization = await feeEstimator.optimizeTransactionCost({
from: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5',
to: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
data: '0xa9059cbb' + '0'.repeat(1000) // Large data payload
});
console.log('Optimization Analysis:', optimization);
```
```python
from typing import Dict, List, Any, Optional
class LineaFeeEstimator:
"""Estimate L1 fees and analyze transaction costs on Linea zkEVM"""
def __init__(self, rpc_url: str):
self.rpc_url = rpc_url
def estimate_l1_fee(self, transaction: Dict[str, Any]) -> int:
"""Estimate L1 data posting fee for a transaction"""
payload = {
"jsonrpc": "2.0",
"method": "eth_estimateL1Fee",
"params": [transaction],
"id": 1
}
response = requests.post(self.rpc_url, json=payload)
data = response.json()
if 'error' in data:
raise Exception(f"RPC Error: {data['error']['message']}")
return int(data['result'], 16)
def _make_rpc_call(self, method: str, params: List = None) -> Any:
"""Helper method for RPC calls"""
payload = {
"jsonrpc": "2.0",
"method": method,
"params": params or [],
"id": 1
}
response = requests.post(self.rpc_url, json=payload)
data = response.json()
if 'error' in data:
raise Exception(f"RPC Error: {data['error']['message']}")
return data['result']
def get_full_fee_breakdown(self, transaction: Dict[str, Any]) -> Dict[str, Any]:
"""Get complete fee breakdown including L1 and L2 costs"""
# Estimate L2 gas
l2_gas_estimate = int(self._make_rpc_call('eth_estimateGas', [transaction]), 16)
# Get current gas price
gas_price = int(self._make_rpc_call('eth_gasPrice'), 16)
# Estimate L1 fee
l1_fee = self.estimate_l1_fee(transaction)
# Calculate L2 execution cost
l2_execution_cost = l2_gas_estimate * gas_price
total_cost = l1_fee + l2_execution_cost
return {
'l1_fee': l1_fee,
'l2_execution_cost': l2_execution_cost,
'total_estimated_cost': total_cost,
'gas_estimate': l2_gas_estimate,
'gas_price': gas_price,
'breakdown': {
'l1_fee_percentage': round((l1_fee / total_cost) * 100, 2) if total_cost > 0 else 0,
'l2_fee_percentage': round((l2_execution_cost / total_cost) * 100, 2) if total_cost > 0 else 0
}
}
def analyze_data_cost_impact(
self,
base_transaction: Dict[str, Any],
data_payloads: List[str]
) -> List[Dict[str, Any]]:
"""Analyze how different data payloads affect L1 fees"""
results = []
for i, data in enumerate(data_payloads):
test_tx = {**base_transaction, 'data': data}
try:
breakdown = self.get_full_fee_breakdown(test_tx)
data_size = (len(data) - 2) // 2 if data.startswith('0x') else len(data) // 2
result = {
'data_payload': data[:20] + '...' if len(data) > 20 else data,
'data_size_bytes': data_size,
'l1_fee': breakdown['l1_fee'],
'l2_execution_cost': breakdown['l2_execution_cost'],
'total_cost': breakdown['total_estimated_cost'],
'l1_fee_per_byte': breakdown['l1_fee'] / data_size if data_size > 0 else 0
}
# Calculate cost increase relative to first payload
if i > 0 and results:
base_cost = results[0]['total_cost']
result['cost_increase_pct'] = round(
((result['total_cost'] - base_cost) / base_cost) * 100, 2
) if base_cost > 0 else 0
else:
result['cost_increase_pct'] = 0
results.append(result)
except Exception as e:
results.append({
'data_payload': data[:20] + '...' if len(data) > 20 else data,
'error': str(e)
})
return results
def suggest_optimizations(self, transaction: Dict[str, Any]) -> Dict[str, Any]:
"""Analyze transaction and suggest cost optimizations"""
baseline = self.get_full_fee_breakdown(transaction)
suggestions = []
# Check data optimization potential
if transaction.get('data') and len(transaction['data']) > 2:
minimal_tx = {**transaction, 'data': '0x'}
minimal_cost = self.get_full_fee_breakdown(minimal_tx)
data_cost_impact = baseline['l1_fee'] - minimal_cost['l1_fee']
if data_cost_impact > 0:
suggestions.append({
'type': 'data_optimization',
'description': 'Transaction data contributes significantly to L1 costs',
'potential_savings_wei': data_cost_impact,
'potential_savings_pct': round(
(data_cost_impact / baseline['total_estimated_cost']) * 100, 2
),
'recommendation': 'Consider compressing data or using events for large payloads'
})
# Check gas efficiency
if baseline['gas_estimate'] > 200000:
suggestions.append({
'type': 'gas_optimization',
'description': f'High gas usage detected: {baseline["gas_estimate"]:,} gas',
'recommendation': 'Review contract logic for gas efficiency improvements'
})
# Check fee composition
if baseline['breakdown']['l1_fee_percentage'] > 80:
suggestions.append({
'type': 'l1_fee_dominance',
'description': f'L1 fees dominate total cost ({baseline["breakdown"]["l1_fee_percentage"]}%)',
'recommendation': 'Consider batching multiple operations into single transaction'
})
return {
'baseline_cost': baseline,
'optimization_suggestions': suggestions,
'total_potential_savings': sum(
s.get('potential_savings_wei', 0) for s in suggestions
)
}
def compare_transaction_efficiency(
self,
transactions: List[Dict[str, Any]],
labels: List[str] = None
) -> Dict[str, Any]:
"""Compare efficiency of different transaction approaches"""
if labels is None:
labels = [f"Transaction {i+1}" for i in range(len(transactions))]
comparisons = []
for i, (tx, label) in enumerate(zip(transactions, labels)):
try:
breakdown = self.get_full_fee_breakdown(tx)
comparisons.append({
'label': label,
'total_cost': breakdown['total_estimated_cost'],
'l1_fee': breakdown['l1_fee'],
'l2_cost': breakdown['l2_execution_cost'],
'gas_estimate': breakdown['gas_estimate'],
'efficiency_score': breakdown['gas_estimate'] / breakdown['total_estimated_cost']
})
except Exception as e:
comparisons.append({
'label': label,
'error': str(e)
})
# Find most efficient
valid_comparisons = [c for c in comparisons if 'error' not in c]
if valid_comparisons:
most_efficient = min(valid_comparisons, key=lambda x: x['total_cost'])
least_efficient = max(valid_comparisons, key=lambda x: x['total_cost'])
return {
'comparisons': comparisons,
'most_efficient': most_efficient,
'least_efficient': least_efficient,
'cost_difference': least_efficient['total_cost'] - most_efficient['total_cost'],
'efficiency_improvement_pct': round(
((least_efficient['total_cost'] - most_efficient['total_cost']) /
least_efficient['total_cost']) * 100, 2
)
}
return {'comparisons': comparisons}
# Usage examples
fee_estimator = LineaFeeEstimator('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY')
# Basic L1 fee estimation
transaction = {
'from': '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5',
'to': '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
'value': '0x1bc16d674ec80000',
'data': '0xa9059cbb000000000000000000000000recipient000000000000000000000000'
}
l1_fee = fee_estimator.estimate_l1_fee(transaction)
print(f"L1 Fee: {l1_fee:,} wei")
# Full breakdown
breakdown = fee_estimator.get_full_fee_breakdown(transaction)
print(f"Total Cost: {breakdown['total_estimated_cost']:,} wei")
print(f"L1 Fee: {breakdown['l1_fee']:,} wei ({breakdown['breakdown']['l1_fee_percentage']}%)")
print(f"L2 Cost: {breakdown['l2_execution_cost']:,} wei ({breakdown['breakdown']['l2_fee_percentage']}%)")
# Data impact analysis
data_payloads = [
'0x', # Empty
'0xa9059cbb' + '00' * 32, # Basic ERC20 transfer
'0xa9059cbb' + '00' * 100, # Larger payload
'0xa9059cbb' + '00' * 500 # Very large payload
]
data_analysis = fee_estimator.analyze_data_cost_impact(
{'from': '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5', 'to': '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913'},
data_payloads
)
print("\nData Size Impact Analysis:")
for result in data_analysis:
if 'error' not in result:
print(f" {result['data_size_bytes']} bytes: {result['total_cost']:,} wei "
f"(+{result['cost_increase_pct']}%)")
# Optimization suggestions
optimization = fee_estimator.suggest_optimizations(transaction)
print(f"\nOptimization Suggestions:")
for suggestion in optimization['optimization_suggestions']:
print(f" - {suggestion['description']}")
print(f" {suggestion['recommendation']}")
```
## Response Example
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x1c6bf526340"
}
```
## Understanding L1 Fees on Linea
### Fee Components
1. **L2 Execution Fee**: Standard gas cost for transaction execution on Linea
2. **L1 Data Fee**: Cost of posting transaction data to Ethereum L1 for data availability
### Data Size Impact
L1 fees scale with transaction data size:
- Simple transfers: Minimal L1 fee
- Contract interactions: Moderate L1 fee based on calldata
- Large data payloads: Significant L1 fee component
### Cost Optimization Strategies
1. **Minimize Data**: Reduce unnecessary data in transactions
2. **Batch Operations**: Combine multiple operations into single transaction
3. **Use Events**: Emit events instead of storing large data on-chain
4. **Optimize Encoding**: Use efficient data encoding methods
## Common Use Cases
### 1. Transaction Cost Planning
```javascript
// Plan transaction costs before execution
async function planTransactionCosts(transactions) {
const feeEstimator = new LineaFeeEstimator(rpcUrl);
const plans = [];
for (const tx of transactions) {
const breakdown = await feeEstimator.getFullFeeBreakdown(tx);
plans.push({
transaction: tx,
estimatedCost: breakdown.totalEstimatedCost,
l1FeeRatio: breakdown.breakdown.l1FeePercentage,
recommendation: breakdown.breakdown.l1FeePercentage > 70 ?
'Consider batching or data optimization' : 'Cost efficient'
});
}
return plans.sort((a, b) => a.estimatedCost - b.estimatedCost);
}
```
### 2. Data Optimization Analysis
```python
def optimize_contract_call_data(base_transaction, data_variations):
"""Find most cost-effective data encoding"""
fee_estimator = LineaFeeEstimator(rpc_url)
results = []
for name, data in data_variations.items():
tx = {**base_transaction, 'data': data}
breakdown = fee_estimator.get_full_fee_breakdown(tx)
results.append({
'encoding': name,
'data_size': len(data) // 2 - 1, # Hex bytes
'total_cost': breakdown['total_estimated_cost'],
'l1_fee': breakdown['l1_fee'],
'efficiency': breakdown['l1_fee'] / (len(data) // 2 - 1)
})
# Sort by total cost
return sorted(results, key=lambda x: x['total_cost'])
```
## Related Methods
- [`eth_estimateGas`](./eth_estimateGas) - Estimate L2 execution gas
- [`eth_gasPrice`](./eth_gasPrice) - Get current L2 gas price
- [`eth_feeHistory`](./eth_feeHistory) - Historical fee data
---
*Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Linea documentation](/docs/linea).*
---
## eth_feeHistory - Linea RPC Method
# eth_feeHistory
Returns historical gas information on Linea 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 enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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-linea-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-linea-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-linea-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 - Linea RPC Method
# eth_gasPrice
Returns the current gas price on Linea in wei.
> **Why Linea?** Build on Consensys-backed zkEVM L2 with $1B+ TVL and 807% growth in 2025 with 15-30x lower fees than Ethereum mainnet, 6,200 TPS throughput, SWIFT integration with 12+ institutions, and $725M Consensys backing.
## 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 enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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-linea-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-linea-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-linea-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-linea-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 - Linea RPC Method
# eth_getBalance
Returns the balance of a given address on Linea.
> **Why Linea?** Build on Consensys-backed zkEVM L2 with $1B+ TVL and 807% growth in 2025 with 15-30x lower fees than Ethereum mainnet, 6,200 TPS throughput, SWIFT integration with 12+ institutions, and $725M Consensys backing.
## 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 enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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": [
"0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const address = '0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f';
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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
address = '0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f'
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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
address := common.HexToAddress("0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f")
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 - Linea RPC Method
# eth_getBlockByHash
Returns information about a block by hash on Linea.
> **Why Linea?** Build on Consensys-backed zkEVM L2 with $1B+ TVL and 807% growth in 2025 with 15-30x lower fees than Ethereum mainnet, 6,200 TPS throughput, SWIFT integration with 12+ institutions, and $725M Consensys backing.
## 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 enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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": [
"0xa5de967d7d780c598c5568e1489bdf66613aa11f7acbd7de75725ee4382c027b",
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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByHash",
"params": [
"0xa5de967d7d780c598c5568e1489bdf66613aa11f7acbd7de75725ee4382c027b",
false
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0xa5de967d7d780c598c5568e1489bdf66613aa11f7acbd7de75725ee4382c027b';
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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
block_hash = '0xa5de967d7d780c598c5568e1489bdf66613aa11f7acbd7de75725ee4382c027b'
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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
blockHash := common.HexToHash("0xa5de967d7d780c598c5568e1489bdf66613aa11f7acbd7de75725ee4382c027b")
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 - Linea RPC Method
# eth_getBlockByNumber
Returns information about a block by block number on Linea.
> **Why Linea?** Build on Consensys-backed zkEVM L2 with $1B+ TVL and 807% growth in 2025 with 15-30x lower fees than Ethereum mainnet, 6,200 TPS throughput, SWIFT integration with 12+ institutions, and $725M Consensys backing.
## 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 enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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": "0xa5de967d7d780c598c5568e1489bdf66613aa11f7acbd7de75725ee4382c027b",
"parentHash": "0x...",
"timestamp": "0x64d8f6d0",
"gasUsed": "0x1234",
"gasLimit": "0x1c9c380",
"transactions": [],
"baseFeePerGas": "0x5f5e100"
}
}
```
## Code Examples
```bash
curl -X POST https://api-linea-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-linea-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-linea-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-linea-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 - Linea RPC Method
# eth_getCode
Returns the bytecode at a given address on Linea.
> **Why Linea?** Build on Consensys-backed zkEVM L2 with $1B+ TVL and 807% growth in 2025 with 15-30x lower fees than Ethereum mainnet, 6,200 TPS throughput, SWIFT integration with 12+ institutions, and $725M Consensys backing.
## 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 enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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": [
"0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"latest"
],
"id": 1
}
```
## Returns
| Type | Description |
|------|-------------|
| `DATA` | Contract bytecode or `0x` if EOA |
## Code Examples
```bash
curl -X POST https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getCode",
"params": [
"0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const address = '0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f';
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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
address = '0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f'
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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
address := common.HexToAddress("0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f")
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 - Linea RPC Method
# eth_getFilterChanges
Polling method for a filter on Linea, returns an array of logs since last poll.
## Use Cases
- **Event streaming** - Get new events incrementally
- **Real-time monitoring** - Track contract activity for enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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-linea-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-linea-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 - Linea RPC Method
# eth_getFilterLogs
Returns an array of all logs matching filter with given ID on Linea.
## Use Cases
- **Historical queries** - Get all matching logs for a filter
- **Full event history** - Retrieve complete event data for enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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-linea-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-linea-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 - Linea RPC Method
# eth_getLogs
Returns an array of all logs matching a given filter object on Linea.
> **Why Linea?** Build on Consensys-backed zkEVM L2 with $1B+ TVL and 807% growth in 2025 with 15-30x lower fees than Ethereum mainnet, 6,200 TPS throughput, SWIFT integration with 12+ institutions, and $725M Consensys backing.
## Use Cases
The `eth_getLogs` method is essential for:
- **Event indexing** - Track contract events for enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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": "0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"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": "0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."],
"data": "0x...",
"blockNumber": "0x5BAD55",
"transactionHash": "0x...",
"logIndex": "0x0"
}]
}
```
## Code Examples
```bash
curl -X POST https://api-linea-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": "0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-linea-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(
'0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f',
'latest',
'latest'
);
console.log('Transfer events:', events);
```
```python
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-linea-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(
'0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f',
'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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
contractAddress := common.HexToAddress("0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f")
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 - Linea RPC Method
# eth_getStorageAt
Returns the value from a storage position at a given address on Linea.
## Use Cases
- **Contract analysis** - Read raw storage values
- **State verification** - Verify contract state
- **Security auditing** - Analyze storage layout for enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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": [
"0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"0x0",
"latest"
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getStorageAt",
"params": [
"0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"0x0",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const address = '0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f';
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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
address = '0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f'
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 - Linea RPC Method
# eth_getTransactionByHash
Returns the information about a transaction by transaction hash on Linea.
> **Why Linea?** Build on Consensys-backed zkEVM L2 with $1B+ TVL and 807% growth in 2025 with 15-30x lower fees than Ethereum mainnet, 6,200 TPS throughput, SWIFT integration with 12+ institutions, and $725M Consensys backing.
## 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 enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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": ["0xc9e9cb9405a8e526ee8eb21e2aae56fe6df29590f8e4d44148f15c8f6a263128"],
"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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionByHash",
"params": ["0xc9e9cb9405a8e526ee8eb21e2aae56fe6df29590f8e4d44148f15c8f6a263128"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const txHash = '0xc9e9cb9405a8e526ee8eb21e2aae56fe6df29590f8e4d44148f15c8f6a263128';
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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0xc9e9cb9405a8e526ee8eb21e2aae56fe6df29590f8e4d44148f15c8f6a263128'
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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0xc9e9cb9405a8e526ee8eb21e2aae56fe6df29590f8e4d44148f15c8f6a263128")
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 - Linea RPC Method
# eth_getTransactionCount
Returns the number of transactions sent from an address on Linea (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 enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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": [
"0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"latest"
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [
"0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const address = '0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f';
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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
address = '0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f'
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 - Linea RPC Method
# eth_getTransactionReceipt
Returns the receipt of a transaction by transaction hash on Linea. Receipt is only available for mined transactions.
> **Why Linea?** Build on Consensys-backed zkEVM L2 with $1B+ TVL and 807% growth in 2025 with 15-30x lower fees than Ethereum mainnet, 6,200 TPS throughput, SWIFT integration with 12+ institutions, and $725M Consensys backing.
## 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 enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native applications
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `transactionHash` | `DATA` | Yes | 32-byte transaction hash |
## Request
```json
{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0xc9e9cb9405a8e526ee8eb21e2aae56fe6df29590f8e4d44148f15c8f6a263128"],
"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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0xc9e9cb9405a8e526ee8eb21e2aae56fe6df29590f8e4d44148f15c8f6a263128"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const txHash = '0xc9e9cb9405a8e526ee8eb21e2aae56fe6df29590f8e4d44148f15c8f6a263128';
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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0xc9e9cb9405a8e526ee8eb21e2aae56fe6df29590f8e4d44148f15c8f6a263128'
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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0xc9e9cb9405a8e526ee8eb21e2aae56fe6df29590f8e4d44148f15c8f6a263128")
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(Linea)
# eth_hashrate
Get node hashrate on the Linea zkEVM 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-linea-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-linea-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 [Linea documentation](/docs/linea).*
---
## eth_maxPriorityFeePerGas - Linea RPC Method
# eth_maxPriorityFeePerGas
Returns the current recommended priority fee per gas on Linea 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 enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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-linea-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-linea-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-linea-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(Linea)
# eth_mining
Check mining status on the Linea zkEVM 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-linea-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-linea-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 [Linea documentation](/docs/linea).*
---
## eth_newBlockFilter - Linea RPC Method
# eth_newBlockFilter
Creates a filter on Linea 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-linea-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-linea-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 - Linea RPC Method
# eth_newFilter
Creates a filter object on Linea to notify when state changes (logs).
## Use Cases
- **Event monitoring** - Subscribe to contract events
- **Real-time updates** - Track events for enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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": "0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
}],
"id": 1
}
```
## Returns
| Type | Description |
|------|-------------|
| `QUANTITY` | Filter ID |
## Code Examples
```bash
curl -X POST https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_newFilter",
"params": [{
"fromBlock": "latest",
"address": "0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f"
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
// Create filter
const filterId = await provider.send('eth_newFilter', [{
fromBlock: 'latest',
address: '0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f',
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 - Linea RPC Method
# eth_newPendingTransactionFilter
Creates a filter on Linea 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-linea-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-linea-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(Linea)
# eth_protocolVersion
Get protocol version on the Linea zkEVM 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-linea-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-linea-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 [Linea documentation](/docs/linea).*
---
## eth_sendRawTransaction - Linea RPC Method
# eth_sendRawTransaction
Submits a pre-signed transaction for broadcast to Linea.
> **Why Linea?** Build on Consensys-backed zkEVM L2 with $1B+ TVL and 807% growth in 2025 with 15-30x lower fees than Ethereum mainnet, 6,200 TPS throughput, SWIFT integration with 12+ institutions, and $725M Consensys backing.
## 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 enterprise DeFi (Aave, Renzo), institutional cross-border payments via SWIFT pilots, and zkEVM-native 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-linea-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-linea-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-linea-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-linea-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("0xe5D7C2a44FfDDf6b295A15c148167daaAf5Cf34f")
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(Linea)
# eth_sendTransaction
> **Important**: Dwellir's shared Linea 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-linea-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(Linea)
# eth_signTransaction
Sign transaction on the Linea zkEVM network.
## Parameters
Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_signTransaction](https://ethereum.org/developers/docs/apis/json-rpc/#eth_signtransaction) documentation for detailed parameter information.
## Returns
The return value depends on the specific method being called.
## Implementation Example
```bash
curl -X POST https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_signTransaction",
"params": [],
"id": 1
}'
```
```javascript
const response = await fetch('https://api-linea-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: [],
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 [Linea documentation](/docs/linea).*
---
## eth_syncing - Linea RPC Method
# eth_syncing
Returns syncing status of Linea 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-linea-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-linea-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 - Linea RPC Method
# eth_uninstallFilter
Uninstalls a filter on Linea. 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-linea-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-linea-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
---
## Linea - zkEVM Layer 2 Documentation
# Linea zkEVM - Build on ConsenSys's Zero-Knowledge Layer 2
## Why Build on Linea?
Linea is ConsenSys's zkEVM Layer 2 solution, leveraging zero-knowledge proofs to deliver unmatched scalability and security. As a Type 2 zkEVM, Linea offers complete EVM equivalence with powerful scaling benefits:
### ⚡ **Zero-Knowledge Performance**
- **12-second block times** - Fast finality with zkProof generation
- **Up to 100x lower costs** than Ethereum mainnet
- **3,000+ TPS capacity** - High throughput for demanding applications
### 🔒 **Cryptographic Security**
- **Zero-knowledge proofs** - Mathematical guarantees of correctness
- **ConsenSys engineering** - Built by Ethereum infrastructure leaders
- **Full EVM equivalence** - Type 2 zkEVM with complete compatibility
### 🛠️ **Developer Excellence**
- **MetaMask integration** - Native support from day one
- **Infura compatibility** - Seamless ConsenSys ecosystem integration
- **Truffle & Hardhat ready** - Use your existing development tools
## Quick Start with Linea
Connect to Linea in seconds with Dwellir's optimized endpoints:
### Installation & Setup
```javascript
// Connect to Linea mainnet
const provider = new JsonRpcProvider(
'https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY'
);
// Verify connection to Linea
const network = await provider.getNetwork();
console.log('Connected to Linea:', network.chainId === 59144n);
// Query account balance
const balance = await provider.getBalance('0x...');
console.log('Balance:', balance.toString());
```
```javascript
const Web3 = require('web3');
// Connect to Linea mainnet
const web3 = new Web3(
'https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY'
);
// Get chain ID to verify connection
const chainId = await web3.eth.getChainId();
console.log('Connected to Linea:', chainId === 59144);
// Get current gas price
const gasPrice = await web3.eth.getGasPrice();
console.log('Current gas price:', gasPrice);
```
```typescript
// Define Linea chain
const linea = defineChain({
id: 59144,
name: 'Linea',
network: 'linea',
nativeCurrency: {
decimals: 18,
name: 'Ether',
symbol: 'ETH',
},
rpcUrls: {
default: {
http: ['https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY'],
},
},
blockExplorers: {
default: { name: 'LineaScan', url: 'https://lineascan.build' },
},
});
// Create Linea client
const client = createPublicClient({
chain: linea,
transport: http(),
});
// Read contract data
const data = await client.readContract({
address: '0x...',
abi: contractAbi,
functionName: 'balanceOf',
args: ['0x...'],
});
```
## Network Information
Chain ID
59144
0xe708 (hex)
Block Time
12 seconds
Average
Gas Token
ETH
Native token
Rollup Type
zkEVM
Zero-Knowledge
## JSON-RPC API Reference
Linea supports the full [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/) with zkEVM-specific optimizations. Access all standard methods plus L2-specific features.
## zkEVM-Specific Features
### 🔐 Zero-Knowledge Proof Verification
Linea's zkEVM architecture provides unique capabilities:
```javascript
// Monitor L2 state root updates
async function getStateRoot(provider) {
const block = await provider.getBlock('latest');
// Access zkEVM-specific fields
const stateRoot = block.stateRoot;
const zkProofHash = block.zkProofHash; // Linea-specific
return {
blockNumber: block.number,
stateRoot,
zkProofHash,
timestamp: block.timestamp
};
}
```
### 📊 Gas Optimization for zkEVM
Optimize gas costs on Linea's zkEVM:
```javascript
// Estimate gas with zkEVM optimizations
async function estimateLineaGas(provider, tx) {
// Get L2 execution gas
const gasEstimate = await provider.estimateGas(tx);
// zkEVM has different gas dynamics than optimistic rollups
// No separate L1 data fee, but proof generation costs amortized
const gasPrice = await provider.getGasPrice();
// Add 10% buffer for zkEVM proof overhead
const bufferedGas = gasEstimate * 110n / 100n;
return {
gasLimit: bufferedGas,
gasPrice: gasPrice,
estimatedCost: bufferedGas * gasPrice
};
}
```
### 🔄 Batch Transaction Processing
Leverage Linea's efficient batch processing:
```javascript
// Batch multiple transactions for optimal zkProof generation
async function batchTransactions(provider, transactions) {
const wallet = new ethers.Wallet(privateKey, provider);
const nonce = await wallet.getTransactionCount();
const promises = transactions.map((tx, index) => {
return wallet.sendTransaction({
...tx,
nonce: nonce + index,
// Linea handles batching efficiently in zkProof generation
gasLimit: 100000n,
});
});
const receipts = await Promise.all(promises);
return receipts;
}
```
## Performance Optimizations
### 1. **Connection Pooling**
Maintain persistent connections for optimal performance:
```javascript
class LineaProvider {
static instance = null;
static getInstance() {
if (!this.instance) {
this.instance = new JsonRpcProvider(
'https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY',
{
chainId: 59144,
name: 'linea'
}
);
}
return this.instance;
}
}
```
### 2. **Smart Contract Deployment**
Deploy contracts optimized for zkEVM:
```javascript
async function deployContract(provider, bytecode, abi) {
const wallet = new ethers.Wallet(privateKey, provider);
// zkEVM-optimized deployment
const factory = new ethers.ContractFactory(abi, bytecode, wallet);
// Linea-specific gas settings
const contract = await factory.deploy({
gasLimit: 3000000n, // Higher limit for complex contracts
gasPrice: await provider.getGasPrice()
});
// Wait for zkProof generation and confirmation
await contract.waitForDeployment();
return contract.address;
}
```
### 3. **Event Monitoring**
Efficiently monitor events on Linea:
```javascript
// Optimized event filtering for zkEVM
async function watchEvents(contract, eventName) {
const filter = contract.filters[eventName]();
// Linea processes events in zkProof batches
// Use larger block ranges for efficiency
const BATCH_SIZE = 5000;
contract.on(filter, (event) => {
console.log('Event detected:', event);
// Process event data
});
// For historical events
const events = await contract.queryFilter(
filter,
-BATCH_SIZE, // Last 5000 blocks
'latest'
);
return events;
}
```
## Common Integration Patterns
### 🌉 Cross-Layer Messaging
Interact between Ethereum L1 and Linea L2:
```javascript
// Bridge assets from Ethereum to Linea
async function bridgeToLinea(l1Provider, l2Provider, amount) {
// L1 bridge contract address
const L1_BRIDGE = '0x...'; // Official Linea bridge
const l1Wallet = new ethers.Wallet(privateKey, l1Provider);
const bridgeContract = new ethers.Contract(
L1_BRIDGE,
bridgeABI,
l1Wallet
);
// Initiate bridge transaction on L1
const tx = await bridgeContract.bridgeETH({
value: amount,
gasLimit: 200000n
});
// Wait for L1 confirmation
await tx.wait();
// Monitor L2 for bridge completion (typically 10-20 minutes)
// zkEVM finality is faster than optimistic rollups
return tx.hash;
}
```
### 🏭 DeFi Integration
Build DeFi applications on Linea:
```javascript
// Interact with DeFi protocols on Linea
async function swapTokens(provider, tokenA, tokenB, amount) {
const wallet = new ethers.Wallet(privateKey, provider);
// Connect to DEX on Linea
const router = new ethers.Contract(
ROUTER_ADDRESS,
routerABI,
wallet
);
// Approve token spending
const tokenContract = new ethers.Contract(tokenA, erc20ABI, wallet);
await tokenContract.approve(ROUTER_ADDRESS, amount);
// Execute swap with Linea-optimized gas
const tx = await router.swapExactTokensForTokens(
amount,
0, // Min amount out
[tokenA, tokenB],
wallet.address,
Math.floor(Date.now() / 1000) + 3600, // 1 hour deadline
{
gasLimit: 250000n,
gasPrice: await provider.getGasPrice()
}
);
return tx;
}
```
## Troubleshooting
### Error: "Invalid chain ID"
Ensure you're using the correct chain ID for Linea:
```javascript
// Correct chain ID for Linea mainnet
const LINEA_CHAIN_ID = 59144; // or 0xe708 in hex
// Verify connection
const chainId = await provider.getNetwork().then(n => n.chainId);
if (chainId !== 59144n) {
throw new Error(`Wrong network: expected Linea (59144), got ${chainId}`);
}
```
### Error: "Transaction underpriced"
Linea uses dynamic gas pricing. Always fetch current prices:
```javascript
// Get optimal gas price for Linea
async function getOptimalGasPrice(provider) {
const gasPrice = await provider.getGasPrice();
// Add 10% buffer for zkEVM processing
const bufferedPrice = gasPrice * 110n / 100n;
return bufferedPrice;
}
```
### Error: "Execution reverted"
Debug failed transactions with trace data:
```javascript
// Debug transaction on Linea
async function debugTransaction(provider, txHash) {
try {
// Get transaction receipt
const receipt = await provider.getTransactionReceipt(txHash);
if (receipt.status === 0) {
// Use debug_traceTransaction for detailed error
const trace = await provider.send('debug_traceTransaction', [
txHash,
{ tracer: 'callTracer' }
]);
console.log('Revert reason:', trace);
}
return receipt;
} catch (error) {
console.error('Debug failed:', error);
}
}
```
## Migration Guide
### From Ethereum Mainnet
Moving from L1 to Linea zkEVM:
```javascript
// Before (Ethereum)
const provider = new JsonRpcProvider('https://eth-mainnet.example.com');
// After (Linea)
const provider = new JsonRpcProvider(
'https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY'
);
// ✅ Full EVM equivalence - contracts work identically
// ✅ Same development tools and libraries
// ✅ MetaMask and wallet support
// ⚠️ Different chain ID (59144)
// ⚠️ zkEVM gas dynamics differ from L1
// ⚠️ Finality achieved through zkProofs
```
### From Other L2s
Migrating from optimistic rollups to Linea zkEVM:
```javascript
// Key differences from Optimistic L2s:
// 1. No challenge period - zkProofs provide instant finality
// 2. Different gas model - no separate L1 data fee
// 3. Faster withdrawals - hours instead of days
// Optimistic L2 (e.g., Optimism, Arbitrum)
const withdrawalPeriod = 7 * 24 * 60 * 60; // 7 days
// Linea zkEVM
const withdrawalPeriod = 8 * 60 * 60; // ~8 hours for zkProof generation
```
## Developer Resources
### Essential Tools
- [Linea Documentation](https://docs.linea.build)
- [LineaScan Explorer](https://lineascan.build)
- [Linea Bridge](https://bridge.linea.build)
- [Linea SDK](https://www.npmjs.com/package/@consensys/linea-sdk)
### Development Frameworks
- [Hardhat Configuration](https://docs.linea.build/developers/quickstart/deploy-smart-contract/hardhat)
- [Build on Linea Quickstart](https://docs.linea.build/developers/quickstart)
### Need Help?
- 📧 **Email**: support@dwellir.com
- 💬 **Discord**: Join our developer community
- 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com)
---
*Build the future of Web3 on Linea zkEVM with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## net_listening - Linea RPC Method
# net_listening
Returns `true` if client is actively listening for network connections on Linea.
## 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-linea-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-linea-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 - Linea RPC Method
# net_peerCount
Returns number of peers currently connected to Linea 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-linea-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-linea-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 - Linea RPC Method
# net_version
Returns the current network ID on Linea.
## 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-linea-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-linea-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 zkEVM gas price oracle...
# rollup_gasPrices
Get zkEVM gas price oracle data on the Linea network. This method provides comprehensive gas pricing information for the zkEVM rollup, including both L2 execution costs and L1 data availability fees.
## Overview
Linea zkEVM uses a sophisticated gas pricing mechanism that accounts for:
- **L2 Execution Costs**: Gas costs for transaction execution on the zkEVM
- **L1 Data Availability**: Costs for posting transaction data to Ethereum L1
- **Proof Generation**: Costs associated with generating zero-knowledge proofs
## Parameters
This method typically takes no parameters, but implementation may vary. Please refer to the official [Linea documentation](https://docs.linea.build/) for the most current parameter specifications.
## Returns
Gas price oracle data object containing current pricing information for the zkEVM rollup.
## Implementation Example
```bash
curl -X POST https://api-linea-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-linea-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('Gas Prices:', data.result);
// Advanced gas price monitoring for Linea zkEVM
class LineaGasPriceMonitor {
constructor(rpcUrl) {
this.rpcUrl = rpcUrl;
this.priceHistory = [];
}
async getGasPrices() {
const response = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'rollup_gasPrices',
params: [],
id: 1
})
});
const data = await response.json();
if (data.error) {
throw new Error(`RPC Error: ${data.error.message}`);
}
return data.result;
}
async getCurrentPricing() {
try {
// Get rollup gas prices
const rollupPrices = await this.getGasPrices();
// Get standard gas price for comparison
const standardGasResponse = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_gasPrice',
params: [],
id: 1
})
});
const standardGasData = await standardGasResponse.json();
const standardGasPrice = parseInt(standardGasData.result, 16);
return {
timestamp: Date.now(),
rollupPrices: rollupPrices,
standardGasPrice: standardGasPrice,
formattedPrices: this.formatPrices(rollupPrices, standardGasPrice)
};
} catch (error) {
throw new Error(`Failed to get pricing: ${error.message}`);
}
}
formatPrices(rollupPrices, standardGasPrice) {
return {
standardGasPrice: {
wei: standardGasPrice,
gwei: (standardGasPrice / 1e9).toFixed(2),
eth: (standardGasPrice / 1e18).toFixed(8)
},
rollupData: rollupPrices // This will depend on actual response format
};
}
async trackPriceHistory(duration = 3600000, interval = 60000) {
// Track gas prices for specified duration (default 1 hour) at intervals (default 1 minute)
const startTime = Date.now();
const endTime = startTime + duration;
console.log(`Starting price tracking for ${duration / 60000} minutes...`);
while (Date.now() < endTime) {
try {
const pricing = await this.getCurrentPricing();
this.priceHistory.push(pricing);
console.log(`Price update: ${pricing.formattedPrices.standardGasPrice.gwei} gwei`);
await new Promise(resolve => setTimeout(resolve, interval));
} catch (error) {
console.error('Price tracking error:', error.message);
await new Promise(resolve => setTimeout(resolve, interval));
}
}
return this.analyzePriceHistory();
}
analyzePriceHistory() {
if (this.priceHistory.length === 0) {
return { error: 'No price history available' };
}
const prices = this.priceHistory.map(p => p.standardGasPrice);
const sortedPrices = [...prices].sort((a, b) => a - b);
const analysis = {
duration: {
start: new Date(this.priceHistory[0].timestamp).toISOString(),
end: new Date(this.priceHistory[this.priceHistory.length - 1].timestamp).toISOString(),
dataPoints: this.priceHistory.length
},
statistics: {
min: Math.min(...prices),
max: Math.max(...prices),
average: prices.reduce((sum, p) => sum + p, 0) / prices.length,
median: sortedPrices[Math.floor(sortedPrices.length / 2)],
volatility: this.calculateVolatility(prices)
},
trends: {
direction: this.getTrend(prices),
priceChange: prices[prices.length - 1] - prices[0],
percentageChange: ((prices[prices.length - 1] - prices[0]) / prices[0] * 100).toFixed(2)
},
recommendations: this.generateRecommendations(prices)
};
return analysis;
}
calculateVolatility(prices) {
if (prices.length < 2) return 0;
const mean = prices.reduce((sum, p) => sum + p, 0) / prices.length;
const variance = prices.reduce((sum, p) => sum + Math.pow(p - mean, 2), 0) / prices.length;
return Math.sqrt(variance);
}
getTrend(prices) {
if (prices.length < 2) return 'insufficient_data';
const firstHalf = prices.slice(0, Math.floor(prices.length / 2));
const secondHalf = prices.slice(Math.floor(prices.length / 2));
const firstAvg = firstHalf.reduce((sum, p) => sum + p, 0) / firstHalf.length;
const secondAvg = secondHalf.reduce((sum, p) => sum + p, 0) / secondHalf.length;
const changePct = ((secondAvg - firstAvg) / firstAvg) * 100;
if (changePct > 5) return 'increasing';
if (changePct < -5) return 'decreasing';
return 'stable';
}
generateRecommendations(prices) {
const recommendations = [];
const currentPrice = prices[prices.length - 1];
const avgPrice = prices.reduce((sum, p) => sum + p, 0) / prices.length;
const minPrice = Math.min(...prices);
if (currentPrice > avgPrice * 1.2) {
recommendations.push({
type: 'high_gas_warning',
message: 'Current gas price is significantly above average',
suggestion: 'Consider waiting for lower gas prices or using lower priority'
});
}
if (currentPrice <= minPrice * 1.1) {
recommendations.push({
type: 'optimal_timing',
message: 'Current gas price is near historical low',
suggestion: 'Good time to execute transactions'
});
}
const volatility = this.calculateVolatility(prices);
if (volatility > avgPrice * 0.1) {
recommendations.push({
type: 'high_volatility',
message: 'Gas prices are highly volatile',
suggestion: 'Monitor prices closely and be prepared to adjust'
});
}
return recommendations;
}
async predictOptimalTiming(targetGasPrice) {
const pricing = await this.getCurrentPricing();
const currentPrice = pricing.standardGasPrice;
if (currentPrice <= targetGasPrice) {
return {
optimal: true,
currentPrice: currentPrice,
targetPrice: targetGasPrice,
recommendation: 'Execute transaction now'
};
}
// Simple prediction based on recent trend
const recentPrices = this.priceHistory.slice(-10).map(p => p.standardGasPrice);
const trend = this.getTrend(recentPrices);
let prediction = 'unknown';
let estimatedWait = 'unknown';
if (trend === 'decreasing') {
prediction = 'prices_likely_to_drop';
estimatedWait = 'monitor_for_15_30_minutes';
} else if (trend === 'increasing') {
prediction = 'prices_likely_to_rise';
estimatedWait = 'consider_executing_soon';
} else {
prediction = 'prices_stable';
estimatedWait = 'no_clear_trend';
}
return {
optimal: false,
currentPrice: currentPrice,
targetPrice: targetGasPrice,
prediction: prediction,
estimatedWait: estimatedWait,
recommendation: `Current: ${(currentPrice / 1e9).toFixed(2)} gwei, Target: ${(targetGasPrice / 1e9).toFixed(2)} gwei`
};
}
async compareWithL1Costs() {
try {
// Get Linea gas prices
const lineaPricing = await this.getCurrentPricing();
// For comparison with Ethereum L1, you would need to call Ethereum mainnet
// This is just an example structure
const comparison = {
linea: {
gasPrice: lineaPricing.standardGasPrice,
gasPriceGwei: lineaPricing.formattedPrices.standardGasPrice.gwei,
estimatedTransferCost: lineaPricing.standardGasPrice * 21000 // ETH transfer
},
savings: {
// This would be calculated with actual L1 data
estimatedSavings: 'Requires L1 comparison data',
savingsPercentage: 'Requires L1 comparison data'
}
};
return comparison;
} catch (error) {
throw new Error(`Failed to compare costs: ${error.message}`);
}
}
}
// Usage examples
const gasPriceMonitor = new LineaGasPriceMonitor('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
// Get current gas pricing
const currentPricing = await gasPriceMonitor.getCurrentPricing();
console.log('Current Gas Prices:', currentPricing.formattedPrices);
// Track prices for 10 minutes
const priceAnalysis = await gasPriceMonitor.trackPriceHistory(600000, 30000);
console.log('Price Analysis:', priceAnalysis);
// Check optimal timing for transaction
const optimalTiming = await gasPriceMonitor.predictOptimalTiming(20000000000); // 20 gwei target
console.log('Optimal Timing:', optimalTiming);
// Compare with L1 costs
const costComparison = await gasPriceMonitor.compareWithL1Costs();
console.log('Cost Comparison:', costComparison);
```
```python
from typing import Dict, List, Any, Optional
from datetime import datetime, timedelta
class LineaGasPriceAnalyzer:
"""Analyze and monitor gas prices on Linea zkEVM"""
def __init__(self, rpc_url: str):
self.rpc_url = rpc_url
self.price_history = []
def get_rollup_gas_prices(self) -> Dict[str, Any]:
"""Get current rollup gas prices"""
payload = {
"jsonrpc": "2.0",
"method": "rollup_gasPrices",
"params": [],
"id": 1
}
response = requests.post(self.rpc_url, json=payload)
data = response.json()
if 'error' in data:
raise Exception(f"RPC Error: {data['error']['message']}")
return data['result']
def get_standard_gas_price(self) -> int:
"""Get standard gas price for comparison"""
payload = {
"jsonrpc": "2.0",
"method": "eth_gasPrice",
"params": [],
"id": 1
}
response = requests.post(self.rpc_url, json=payload)
data = response.json()
if 'error' in data:
raise Exception(f"RPC Error: {data['error']['message']}")
return int(data['result'], 16)
def get_comprehensive_pricing(self) -> Dict[str, Any]:
"""Get comprehensive gas pricing information"""
rollup_prices = self.get_rollup_gas_prices()
standard_gas_price = self.get_standard_gas_price()
return {
'timestamp': datetime.now().isoformat(),
'rollup_data': rollup_prices,
'standard_gas_price': standard_gas_price,
'formatted': {
'gas_price_wei': standard_gas_price,
'gas_price_gwei': round(standard_gas_price / 1e9, 2),
'gas_price_eth': round(standard_gas_price / 1e18, 8)
},
'transaction_costs': {
'eth_transfer': standard_gas_price * 21000, # Standard ETH transfer
'erc20_transfer': standard_gas_price * 65000, # Typical ERC20 transfer
'swap': standard_gas_price * 150000 # Typical DEX swap
}
}
def monitor_prices(
self,
duration_minutes: int = 60,
interval_seconds: int = 60
) -> Dict[str, Any]:
"""Monitor gas prices over time"""
start_time = datetime.now()
end_time = start_time + timedelta(minutes=duration_minutes)
print(f"Monitoring gas prices for {duration_minutes} minutes...")
price_data = []
while datetime.now() < end_time:
try:
pricing = self.get_comprehensive_pricing()
price_data.append(pricing)
self.price_history.append(pricing)
print(f"Price update: {pricing['formatted']['gas_price_gwei']} gwei")
time.sleep(interval_seconds)
except Exception as e:
print(f"Error monitoring prices: {e}")
time.sleep(interval_seconds)
return self._analyze_price_data(price_data)
def _analyze_price_data(self, price_data: List[Dict]) -> Dict[str, Any]:
"""Analyze collected price data"""
if not price_data:
return {'error': 'No price data available'}
gas_prices = [p['standard_gas_price'] for p in price_data]
gwei_prices = [p['formatted']['gas_price_gwei'] for p in price_data]
analysis = {
'period': {
'start': price_data[0]['timestamp'],
'end': price_data[-1]['timestamp'],
'data_points': len(price_data)
},
'statistics': {
'min_wei': min(gas_prices),
'max_wei': max(gas_prices),
'average_wei': statistics.mean(gas_prices),
'median_wei': statistics.median(gas_prices),
'min_gwei': min(gwei_prices),
'max_gwei': max(gwei_prices),
'average_gwei': round(statistics.mean(gwei_prices), 2),
'median_gwei': round(statistics.median(gwei_prices), 2),
'std_dev_gwei': round(statistics.stdev(gwei_prices) if len(gwei_prices) > 1 else 0, 2)
},
'trends': self._calculate_trends(gas_prices),
'volatility': self._calculate_volatility(gas_prices),
'cost_analysis': self._analyze_transaction_costs(price_data)
}
return analysis
def _calculate_trends(self, prices: List[int]) -> Dict[str, Any]:
"""Calculate price trends"""
if len(prices) < 2:
return {'trend': 'insufficient_data'}
# Simple linear trend
x = list(range(len(prices)))
n = len(prices)
# Calculate slope using least squares
sum_x = sum(x)
sum_y = sum(prices)
sum_xy = sum(x[i] * prices[i] for i in range(n))
sum_x2 = sum(x[i] ** 2 for i in range(n))
slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x ** 2)
# Percentage change
price_change = prices[-1] - prices[0]
pct_change = (price_change / prices[0]) * 100
trend_direction = 'increasing' if slope > 0 else 'decreasing' if slope < 0 else 'stable'
return {
'trend': trend_direction,
'slope': slope,
'price_change_wei': price_change,
'percentage_change': round(pct_change, 2),
'is_volatile': abs(pct_change) > 10
}
def _calculate_volatility(self, prices: List[int]) -> Dict[str, Any]:
"""Calculate price volatility metrics"""
if len(prices) < 2:
return {'volatility': 0}
mean_price = statistics.mean(prices)
variance = statistics.variance(prices)
std_dev = statistics.stdev(prices)
# Coefficient of variation (relative volatility)
cv = (std_dev / mean_price) * 100 if mean_price > 0 else 0
return {
'standard_deviation': round(std_dev, 2),
'variance': round(variance, 2),
'coefficient_of_variation': round(cv, 2),
'volatility_level': (
'high' if cv > 15 else
'medium' if cv > 5 else
'low'
)
}
def _analyze_transaction_costs(self, price_data: List[Dict]) -> Dict[str, Any]:
"""Analyze transaction costs over time"""
cost_analysis = {
'eth_transfer': [],
'erc20_transfer': [],
'swap': []
}
for data in price_data:
costs = data['transaction_costs']
cost_analysis['eth_transfer'].append(costs['eth_transfer'])
cost_analysis['erc20_transfer'].append(costs['erc20_transfer'])
cost_analysis['swap'].append(costs['swap'])
result = {}
for tx_type, costs in cost_analysis.items():
result[tx_type] = {
'min_cost_wei': min(costs),
'max_cost_wei': max(costs),
'avg_cost_wei': round(statistics.mean(costs)),
'cost_range_wei': max(costs) - min(costs),
'min_cost_usd': 'Requires ETH price data',
'max_cost_usd': 'Requires ETH price data'
}
return result
def recommend_optimal_timing(
self,
target_gas_price_gwei: float,
transaction_type: str = 'eth_transfer'
) -> Dict[str, Any]:
"""Recommend optimal timing for transaction execution"""
current_pricing = self.get_comprehensive_pricing()
current_gwei = current_pricing['formatted']['gas_price_gwei']
recommendation = {
'current_price_gwei': current_gwei,
'target_price_gwei': target_gas_price_gwei,
'execute_now': current_gwei <= target_gas_price_gwei
}
if recommendation['execute_now']:
recommendation['message'] = 'Current gas price meets target - execute now'
recommendation['estimated_cost'] = current_pricing['transaction_costs'][transaction_type]
else:
price_diff = current_gwei - target_gas_price_gwei
recommendation['message'] = f'Wait for lower prices (current: {current_gwei}, target: {target_gas_price_gwei})'
recommendation['price_difference_gwei'] = round(price_diff, 2)
# Simple prediction based on recent trend if available
if len(self.price_history) > 5:
recent_prices = [p['standard_gas_price'] for p in self.price_history[-5:]]
trends = self._calculate_trends(recent_prices)
if trends['trend'] == 'decreasing':
recommendation['prediction'] = 'Prices trending down - may reach target soon'
elif trends['trend'] == 'increasing':
recommendation['prediction'] = 'Prices trending up - consider executing soon'
else:
recommendation['prediction'] = 'Prices stable - monitor for changes'
return recommendation
def compare_with_ethereum_l1(self, eth_l1_gas_price_gwei: float) -> Dict[str, Any]:
"""Compare Linea costs with Ethereum L1"""
linea_pricing = self.get_comprehensive_pricing()
linea_gwei = linea_pricing['formatted']['gas_price_gwei']
# Calculate savings for different transaction types
savings_analysis = {}
for tx_type, linea_gas_units in [
('eth_transfer', 21000),
('erc20_transfer', 65000),
('swap', 150000)
]:
l1_cost_wei = int(eth_l1_gas_price_gwei * 1e9 * linea_gas_units)
linea_cost_wei = linea_pricing['transaction_costs'][tx_type]
savings_wei = l1_cost_wei - linea_cost_wei
savings_pct = (savings_wei / l1_cost_wei) * 100 if l1_cost_wei > 0 else 0
savings_analysis[tx_type] = {
'l1_cost_wei': l1_cost_wei,
'linea_cost_wei': linea_cost_wei,
'savings_wei': savings_wei,
'savings_percentage': round(savings_pct, 2),
'cost_ratio': round(linea_cost_wei / l1_cost_wei, 3) if l1_cost_wei > 0 else 0
}
return {
'comparison_timestamp': datetime.now().isoformat(),
'l1_gas_price_gwei': eth_l1_gas_price_gwei,
'linea_gas_price_gwei': linea_gwei,
'price_ratio': round(linea_gwei / eth_l1_gas_price_gwei, 3) if eth_l1_gas_price_gwei > 0 else 0,
'transaction_savings': savings_analysis
}
# Usage examples
analyzer = LineaGasPriceAnalyzer('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY')
# Get current comprehensive pricing
pricing = analyzer.get_comprehensive_pricing()
print(f"Current gas price: {pricing['formatted']['gas_price_gwei']} gwei")
print(f"ETH transfer cost: {pricing['transaction_costs']['eth_transfer']:,} wei")
# Monitor prices for 30 minutes
price_analysis = analyzer.monitor_prices(duration_minutes=30, interval_seconds=120)
print("\nPrice Analysis:")
print(f"Average: {price_analysis['statistics']['average_gwei']} gwei")
print(f"Volatility: {price_analysis['volatility']['volatility_level']}")
print(f"Trend: {price_analysis['trends']['trend']}")
# Get timing recommendation
timing = analyzer.recommend_optimal_timing(target_gas_price_gwei=15.0)
print(f"\nTiming recommendation: {timing['message']}")
# Compare with Ethereum L1 (example with 50 gwei L1 price)
comparison = analyzer.compare_with_ethereum_l1(eth_l1_gas_price_gwei=50.0)
print(f"\nL1 vs Linea savings:")
for tx_type, data in comparison['transaction_savings'].items():
print(f" {tx_type}: {data['savings_percentage']}% savings")
```
## Response Example
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"l1GasPrice": "0x12a05f200",
"l2GasPrice": "0x3b9aca00",
"overhead": "0xbc0",
"scalar": "0x684000",
"decimals": "0x6"
}
}
```
## Understanding Gas Prices on Linea
### Price Components
1. **L2 Gas Price**: Cost per gas unit for execution on Linea zkEVM
2. **L1 Gas Price**: Current Ethereum L1 gas price for data posting
3. **Overhead**: Fixed overhead cost for L1 data posting
4. **Scalar**: Scaling factor for L1 cost calculation
5. **Decimals**: Decimal precision for calculations
### Cost Calculation
Total transaction cost = (L2 Gas × L2 Gas Price) + L1 Data Fee
Where L1 Data Fee considers:
- Transaction data size
- Current L1 gas price
- Overhead and scalar factors
## Common Use Cases
### 1. Gas Price Monitoring
```javascript
// Monitor gas prices for optimal transaction timing
async function monitorForOptimalGas(targetGwei, callback) {
const monitor = new LineaGasPriceMonitor(rpcUrl);
const checkPrice = async () => {
const pricing = await monitor.getCurrentPricing();
const currentGwei = pricing.formattedPrices.standardGasPrice.gwei;
if (currentGwei <= targetGwei) {
callback({
optimal: true,
currentPrice: currentGwei,
targetPrice: targetGwei,
message: 'Target price reached!'
});
return true;
}
return false;
};
// Check every 30 seconds
const interval = setInterval(async () => {
const optimal = await checkPrice();
if (optimal) {
clearInterval(interval);
}
}, 30000);
// Initial check
await checkPrice();
}
```
### 2. Cost Optimization
```python
def optimize_transaction_timing(analyzer, transactions, budget_gwei):
"""Find optimal timing for multiple transactions within budget"""
optimization_plan = []
for i, tx in enumerate(transactions):
# Estimate transaction cost at different gas prices
cost_estimates = []
for gas_price_gwei in [10, 15, 20, 25, 30]:
gas_price_wei = int(gas_price_gwei * 1e9)
estimated_cost = tx['gas_estimate'] * gas_price_wei
cost_estimates.append({
'gas_price_gwei': gas_price_gwei,
'estimated_cost_wei': estimated_cost,
'within_budget': gas_price_gwei <= budget_gwei
})
# Find optimal price point
optimal = next(
(est for est in cost_estimates if est['within_budget']),
cost_estimates[0]
)
optimization_plan.append({
'transaction_id': i,
'optimal_gas_price': optimal['gas_price_gwei'],
'estimated_cost': optimal['estimated_cost_wei'],
'cost_estimates': cost_estimates
})
return optimization_plan
```
### 3. Historical Analysis
```javascript
// Analyze historical gas price patterns
async function analyzeGasPricePatterns(monitor, days = 7) {
const patterns = {
hourlyAverages: {},
dailyTrends: [],
optimalTimes: []
};
// This would require storing historical data
// For demonstration, showing structure
// Simulate hourly analysis
for (let hour = 0; hour < 24; hour++) {
patterns.hourlyAverages[hour] = {
averageGwei: 0, // Would be calculated from historical data
transactionVolume: 0,
volatility: 0
};
}
// Identify optimal transaction times
const sortedHours = Object.entries(patterns.hourlyAverages)
.sort((a, b) => a[1].averageGwei - b[1].averageGwei);
patterns.optimalTimes = sortedHours.slice(0, 6).map(([hour, data]) => ({
hour: parseInt(hour),
averageGwei: data.averageGwei,
timeRange: `${hour}:00-${hour}:59 UTC`
}));
return patterns;
}
```
## Related Methods
- [`eth_gasPrice`](./eth_gasPrice) - Get current L2 gas price
- [`eth_feeHistory`](./eth_feeHistory) - Historical fee data
- [`eth_estimateGas`](./eth_estimateGas) - Estimate transaction gas
- [`rollup_getInfo`](./rollup_getInfo) - Get rollup configuration
---
*Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Linea documentation](/docs/linea).*
---
## rollup_getInfo - Get zkEVM rollup configuration
# rollup_getInfo
Get zkEVM rollup configuration on the Linea network. This method provides essential information about the zkEVM rollup parameters, settings, and operational details.
## Overview
Linea zkEVM is a Layer 2 scaling solution that uses zero-knowledge proofs to provide high throughput while maintaining Ethereum's security. The rollup configuration includes important parameters for:
- **Batch Processing**: How transactions are batched and processed
- **Proof Generation**: Zero-knowledge proof parameters
- **Bridge Operations**: L1 ↔ L2 asset bridging configuration
- **Network Parameters**: Chain ID, block times, and operational settings
## Parameters
This method typically takes no parameters, but implementation may vary. Please refer to the official [Linea documentation](https://docs.linea.build/) for the most current parameter specifications.
## Returns
Rollup configuration object containing comprehensive information about the zkEVM rollup setup.
## Implementation Example
```bash
curl -X POST https://api-linea-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-linea-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('Rollup Info:', data.result);
// Advanced Linea zkEVM rollup information analyzer
class LineaRollupAnalyzer {
constructor(rpcUrl) {
this.rpcUrl = rpcUrl;
}
async getRollupInfo() {
const response = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'rollup_getInfo',
params: [],
id: 1
})
});
const data = await response.json();
if (data.error) {
throw new Error(`RPC Error: ${data.error.message}`);
}
return data.result;
}
async getComprehensiveRollupStatus() {
try {
// Get rollup info
const rollupInfo = await this.getRollupInfo();
// Get current chain info
const chainIdResponse = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_chainId',
params: [],
id: 1
})
});
const chainData = await chainIdResponse.json();
const chainId = parseInt(chainData.result, 16);
// Get latest block info
const blockResponse = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_getBlockByNumber',
params: ['latest', false],
id: 1
})
});
const blockData = await blockResponse.json();
const latestBlock = blockData.result;
return {
timestamp: new Date().toISOString(),
network: {
name: 'Linea',
chainId: chainId,
type: 'zkEVM'
},
rollupConfig: rollupInfo,
currentState: {
latestBlock: parseInt(latestBlock.number, 16),
blockHash: latestBlock.hash,
timestamp: parseInt(latestBlock.timestamp, 16),
gasLimit: parseInt(latestBlock.gasLimit, 16),
gasUsed: parseInt(latestBlock.gasUsed, 16),
utilization: ((parseInt(latestBlock.gasUsed, 16) / parseInt(latestBlock.gasLimit, 16)) * 100).toFixed(2)
},
analysis: this.analyzeRollupConfig(rollupInfo, chainId)
};
} catch (error) {
throw new Error(`Failed to get comprehensive status: ${error.message}`);
}
}
analyzeRollupConfig(rollupInfo, chainId) {
const analysis = {
networkType: 'zkEVM Rollup',
securityModel: 'Zero-Knowledge Proofs',
dataAvailability: 'Ethereum L1',
features: [],
optimizations: [],
considerations: []
};
// Analyze chain ID
if (chainId === 59144) {
analysis.features.push('Linea Mainnet');
analysis.features.push('Production Network');
} else if (chainId === 59140) {
analysis.features.push('Linea Testnet');
analysis.features.push('Development Network');
}
// General zkEVM features
analysis.features.push('EVM Compatibility');
analysis.features.push('Zero-Knowledge Proofs');
analysis.features.push('L1 Data Availability');
analysis.features.push('Ethereum Security');
// Optimizations
analysis.optimizations.push('High Throughput');
analysis.optimizations.push('Low Transaction Costs');
analysis.optimizations.push('Fast Finality');
analysis.optimizations.push('Ethereum Virtual Machine Compatibility');
// Considerations
analysis.considerations.push('Proof Generation Time');
analysis.considerations.push('L1 Data Posting Costs');
analysis.considerations.push('Bridge Withdrawal Delays');
return analysis;
}
async compareWithOtherL2s() {
const lineaInfo = await this.getComprehensiveRollupStatus();
// This would be expanded with actual data from other L2s
const comparison = {
linea: {
type: 'zkEVM',
proofSystem: 'Zero-Knowledge',
evmCompatibility: 'Full',
dataAvailability: 'On-chain (Ethereum L1)',
finality: 'Probabilistic → Proven',
withdrawalTime: '~7 days (pending finalization)',
advantages: [
'Full EVM compatibility',
'Strong security guarantees',
'No trust assumptions beyond Ethereum',
'Privacy-preserving proofs'
]
},
optimisticRollups: {
type: 'Optimistic',
proofSystem: 'Fraud Proofs',
evmCompatibility: 'Full',
dataAvailability: 'On-chain (Ethereum L1)',
finality: 'Optimistic → Proven',
withdrawalTime: '~7 days (challenge period)',
tradeoffs: [
'Faster transaction processing',
'Lower computational overhead',
'Challenge period required',
'Potential for fraud challenges'
]
},
comparison: {
security: 'zkEVM provides stronger guarantees',
performance: 'Similar transaction throughput',
costs: 'Comparable transaction fees',
devExperience: 'Both offer full EVM compatibility'
}
};
return comparison;
}
async monitorRollupHealth() {
const health = {
timestamp: new Date().toISOString(),
status: 'unknown',
metrics: {},
alerts: []
};
try {
const status = await this.getComprehensiveRollupStatus();
// Check basic connectivity and latest block
const blockAge = Date.now() / 1000 - status.currentState.timestamp;
health.metrics = {
latestBlock: status.currentState.latestBlock,
blockAge: blockAge,
gasUtilization: parseFloat(status.currentState.utilization),
chainId: status.network.chainId
};
// Health checks
if (blockAge > 300) { // 5 minutes
health.alerts.push({
severity: 'warning',
message: `Latest block is ${Math.floor(blockAge / 60)} minutes old`,
recommendation: 'Check network connectivity and block production'
});
}
if (health.metrics.gasUtilization > 90) {
health.alerts.push({
severity: 'info',
message: `High gas utilization: ${health.metrics.gasUtilization}%`,
recommendation: 'Network is experiencing high usage'
});
}
health.status = health.alerts.length === 0 ? 'healthy' :
health.alerts.some(a => a.severity === 'error') ? 'unhealthy' : 'warning';
} catch (error) {
health.status = 'error';
health.alerts.push({
severity: 'error',
message: `Failed to get rollup status: ${error.message}`,
recommendation: 'Check RPC endpoint connectivity'
});
}
return health;
}
async getNetworkCapacityInfo() {
try {
const status = await this.getComprehensiveRollupStatus();
const capacity = {
current: {
blockGasLimit: status.currentState.gasLimit,
blockGasUsed: status.currentState.gasUsed,
utilizationPercentage: parseFloat(status.currentState.utilization)
},
theoretical: {
maxTxPerSecond: 0, // Would be calculated based on average gas per tx
maxTxPerBlock: 0,
avgBlockTime: 0 // Would need historical data
},
estimates: {
simpleTransfers: Math.floor(status.currentState.gasLimit / 21000),
erc20Transfers: Math.floor(status.currentState.gasLimit / 65000),
complexContracts: Math.floor(status.currentState.gasLimit / 200000)
}
};
return capacity;
} catch (error) {
throw new Error(`Failed to get capacity info: ${error.message}`);
}
}
async analyzeUpgradeability() {
const rollupInfo = await this.getRollupInfo();
// This would analyze the actual rollup configuration
// For demonstration, providing general zkEVM upgrade analysis
return {
upgradeType: 'Governed Upgrades',
governanceModel: 'Multi-signature or DAO governance',
upgradeProcess: [
'Proposal submission',
'Community review',
'Governance voting',
'Implementation timeline',
'Upgrade execution'
],
considerations: [
'Proof system upgrades may require redeployment',
'Smart contract upgrades follow standard patterns',
'L1 contract upgrades need careful coordination',
'Backward compatibility maintenance'
],
riskMitigation: [
'Extensive testing on testnets',
'Gradual rollout procedures',
'Emergency pause mechanisms',
'Rollback capabilities where possible'
]
};
}
async getBridgeInfo() {
// This would integrate with bridge contracts
// For demonstration, providing general bridge information
return {
bridgeType: 'Canonical Bridge',
supportedAssets: [
'ETH (Native)',
'ERC-20 Tokens',
'ERC-721 NFTs',
'ERC-1155 Multi-tokens'
],
bridgeProcess: {
deposit: {
timeToL2: '~15 minutes',
steps: [
'Lock tokens on L1',
'Wait for L1 confirmation',
'Mint on L2',
'Tokens available on L2'
]
},
withdrawal: {
timeToL1: '~7 days',
steps: [
'Burn tokens on L2',
'Include in batch',
'Generate proof',
'Submit to L1',
'Finalization period',
'Claim on L1'
]
}
},
security: {
model: 'Cryptographic proofs',
assumptions: 'Ethereum L1 security',
risks: [
'Smart contract bugs',
'Proof system vulnerabilities',
'Bridge implementation issues'
]
}
};
}
}
// Usage examples
const rollupAnalyzer = new LineaRollupAnalyzer('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
// Get basic rollup info
const rollupInfo = await rollupAnalyzer.getRollupInfo();
console.log('Rollup Configuration:', rollupInfo);
// Get comprehensive status
const comprehensiveStatus = await rollupAnalyzer.getComprehensiveRollupStatus();
console.log('Network Status:', comprehensiveStatus);
// Monitor rollup health
const healthStatus = await rollupAnalyzer.monitorRollupHealth();
console.log('Health Status:', healthStatus.status);
console.log('Alerts:', healthStatus.alerts);
// Get network capacity info
const capacityInfo = await rollupAnalyzer.getNetworkCapacityInfo();
console.log('Network Capacity:', capacityInfo);
// Compare with other L2s
const comparison = await rollupAnalyzer.compareWithOtherL2s();
console.log('L2 Comparison:', comparison);
// Analyze upgradeability
const upgradeAnalysis = await rollupAnalyzer.analyzeUpgradeability();
console.log('Upgrade Model:', upgradeAnalysis);
// Get bridge information
const bridgeInfo = await rollupAnalyzer.getBridgeInfo();
console.log('Bridge Details:', bridgeInfo);
```
```python
from typing import Dict, List, Any, Optional
from datetime import datetime
class LineaRollupInfoAnalyzer:
"""Comprehensive analyzer for Linea zkEVM rollup information"""
def __init__(self, rpc_url: str):
self.rpc_url = rpc_url
def get_rollup_info(self) -> Dict[str, Any]:
"""Get basic rollup configuration information"""
payload = {
"jsonrpc": "2.0",
"method": "rollup_getInfo",
"params": [],
"id": 1
}
response = requests.post(self.rpc_url, json=payload)
data = response.json()
if 'error' in data:
raise Exception(f"RPC Error: {data['error']['message']}")
return data['result']
def _make_rpc_call(self, method: str, params: List = None) -> Any:
"""Helper method for making RPC calls"""
payload = {
"jsonrpc": "2.0",
"method": method,
"params": params or [],
"id": 1
}
response = requests.post(self.rpc_url, json=payload)
data = response.json()
if 'error' in data:
raise Exception(f"RPC Error: {data['error']['message']}")
return data['result']
def get_comprehensive_rollup_status(self) -> Dict[str, Any]:
"""Get comprehensive rollup status and configuration"""
rollup_info = self.get_rollup_info()
# Get additional network information
chain_id = int(self._make_rpc_call('eth_chainId'), 16)
latest_block = self._make_rpc_call('eth_getBlockByNumber', ['latest', False])
block_number = int(latest_block['number'], 16)
block_timestamp = int(latest_block['timestamp'], 16)
gas_limit = int(latest_block['gasLimit'], 16)
gas_used = int(latest_block['gasUsed'], 16)
return {
'timestamp': datetime.now().isoformat(),
'network_info': {
'name': 'Linea',
'chain_id': chain_id,
'type': 'zkEVM',
'consensus': 'Zero-Knowledge Proofs'
},
'rollup_config': rollup_info,
'current_state': {
'latest_block': block_number,
'block_hash': latest_block['hash'],
'block_timestamp': block_timestamp,
'gas_limit': gas_limit,
'gas_used': gas_used,
'gas_utilization': round((gas_used / gas_limit) * 100, 2),
'block_age_seconds': int(time.time()) - block_timestamp
},
'analysis': self._analyze_rollup_configuration(rollup_info, chain_id)
}
def _analyze_rollup_configuration(
self,
rollup_info: Dict[str, Any],
chain_id: int
) -> Dict[str, Any]:
"""Analyze rollup configuration and provide insights"""
analysis = {
'rollup_type': 'zkEVM (Zero-Knowledge Ethereum Virtual Machine)',
'security_model': 'Cryptographic proofs with L1 data availability',
'key_features': [
'Full EVM compatibility',
'Zero-knowledge proof validation',
'Ethereum L1 data availability',
'Trustless withdrawals',
'Privacy-preserving computations'
],
'network_classification': 'Mainnet' if chain_id == 59144 else 'Testnet',
'performance_characteristics': {
'finality': 'Probabilistic then cryptographically proven',
'withdrawal_time': '~7 days (proof generation + challenge period)',
'throughput': 'High (limited by gas limit)',
'costs': 'Low L2 execution + L1 data costs'
}
}
# Add specific insights based on chain
if chain_id == 59144: # Linea Mainnet
analysis['environment'] = 'Production'
analysis['considerations'] = [
'Real value at risk',
'Production-grade security',
'Full audit coverage',
'Mainnet gas costs apply'
]
elif chain_id == 59140: # Linea Testnet
analysis['environment'] = 'Testing'
analysis['considerations'] = [
'Testing and development use',
'No real value',
'Latest features may be experimental',
'Network resets possible'
]
return analysis
def monitor_rollup_performance(self, duration_minutes: int = 10) -> Dict[str, Any]:
"""Monitor rollup performance over time"""
monitoring_data = []
start_time = datetime.now()
print(f"Monitoring rollup for {duration_minutes} minutes...")
try:
while (datetime.now() - start_time).seconds < duration_minutes * 60:
status = self.get_comprehensive_rollup_status()
monitoring_data.append(status)
print(f"Block: {status['current_state']['latest_block']}, "
f"Utilization: {status['current_state']['gas_utilization']}%")
time.sleep(30) # Check every 30 seconds
except KeyboardInterrupt:
print("Monitoring stopped by user")
return self._analyze_performance_data(monitoring_data)
def _analyze_performance_data(self, monitoring_data: List[Dict]) -> Dict[str, Any]:
"""Analyze collected performance data"""
if not monitoring_data:
return {'error': 'No monitoring data collected'}
block_numbers = [d['current_state']['latest_block'] for d in monitoring_data]
gas_utilizations = [d['current_state']['gas_utilization'] for d in monitoring_data]
block_ages = [d['current_state']['block_age_seconds'] for d in monitoring_data]
# Calculate block production rate
if len(block_numbers) > 1:
blocks_produced = block_numbers[-1] - block_numbers[0]
time_elapsed = (
datetime.fromisoformat(monitoring_data[-1]['timestamp']) -
datetime.fromisoformat(monitoring_data[0]['timestamp'])
).seconds
avg_block_time = time_elapsed / blocks_produced if blocks_produced > 0 else 0
else:
avg_block_time = 0
blocks_produced = 0
return {
'monitoring_period': {
'start': monitoring_data[0]['timestamp'],
'end': monitoring_data[-1]['timestamp'],
'data_points': len(monitoring_data)
},
'block_production': {
'blocks_produced': blocks_produced,
'average_block_time': round(avg_block_time, 2),
'block_range': f"{block_numbers[0]} - {block_numbers[-1]}"
},
'gas_utilization': {
'average': round(sum(gas_utilizations) / len(gas_utilizations), 2),
'min': min(gas_utilizations),
'max': max(gas_utilizations),
'trend': self._calculate_trend(gas_utilizations)
},
'network_health': {
'consistent_block_production': blocks_produced > 0,
'average_block_age': round(sum(block_ages) / len(block_ages), 2),
'health_score': self._calculate_health_score(monitoring_data)
}
}
def _calculate_trend(self, values: List[float]) -> str:
"""Calculate trend direction for a series of values"""
if len(values) < 2:
return 'insufficient_data'
first_half = values[:len(values)//2]
second_half = values[len(values)//2:]
first_avg = sum(first_half) / len(first_half)
second_avg = sum(second_half) / len(second_half)
change_pct = ((second_avg - first_avg) / first_avg) * 100 if first_avg > 0 else 0
if change_pct > 5:
return 'increasing'
elif change_pct < -5:
return 'decreasing'
else:
return 'stable'
def _calculate_health_score(self, monitoring_data: List[Dict]) -> float:
"""Calculate a health score for the rollup"""
score = 100.0
# Check for stale blocks
avg_block_age = sum(d['current_state']['block_age_seconds'] for d in monitoring_data) / len(monitoring_data)
if avg_block_age > 300: # 5 minutes
score -= 20
elif avg_block_age > 120: # 2 minutes
score -= 10
# Check gas utilization patterns
gas_utils = [d['current_state']['gas_utilization'] for d in monitoring_data]
avg_util = sum(gas_utils) / len(gas_utils)
if avg_util > 95: # Very high utilization
score -= 15
elif avg_util < 5: # Very low utilization (might indicate issues)
score -= 10
return max(0, score)
def compare_with_ethereum_l1(self, eth_l1_rpc_url: str = None) -> Dict[str, Any]:
"""Compare Linea with Ethereum L1 characteristics"""
linea_status = self.get_comprehensive_rollup_status()
comparison = {
'linea_zkevm': {
'type': 'Layer 2 zkEVM',
'consensus': 'Zero-Knowledge Proofs',
'finality': 'Probabilistic → Proven',
'block_time': '~12 seconds',
'gas_limit': linea_status['current_state']['gas_limit'],
'transaction_throughput': 'High',
'transaction_costs': 'Low'
},
'ethereum_l1': {
'type': 'Layer 1 Blockchain',
'consensus': 'Proof of Stake',
'finality': 'Probabilistic',
'block_time': '~12 seconds',
'gas_limit': '~30M gas',
'transaction_throughput': 'Limited',
'transaction_costs': 'High'
},
'advantages_linea': [
'Lower transaction costs',
'Higher throughput capacity',
'EVM compatibility',
'Inherits Ethereum security',
'Privacy features via zk-proofs'
],
'advantages_l1': [
'No additional trust assumptions',
'Direct composability',
'Immediate finality',
'No bridge requirements',
'Maximum decentralization'
]
}
return comparison
def analyze_upgradeability_governance(self) -> Dict[str, Any]:
"""Analyze upgradeability and governance mechanisms"""
return {
'upgrade_mechanism': 'Governed Smart Contracts',
'governance_model': {
'type': 'Multi-signature or DAO governance',
'participants': [
'Core development team',
'Community stakeholders',
'Security auditors',
'Ecosystem partners'
]
},
'upgrade_process': {
'steps': [
'1. Proposal creation and review',
'2. Community discussion period',
'3. Technical evaluation',
'4. Governance voting',
'5. Implementation timeline',
'6. Staged rollout',
'7. Post-upgrade monitoring'
],
'timeframes': {
'discussion_period': '1-2 weeks',
'voting_period': '1 week',
'implementation_delay': '1-2 weeks',
'total_process': '4-6 weeks minimum'
}
},
'risk_mitigation': [
'Extensive testnet validation',
'Audit requirements',
'Emergency pause mechanisms',
'Gradual feature activation',
'Rollback procedures where possible'
],
'recent_upgrades': 'Check governance forum for latest information'
}
def get_bridge_integration_info(self) -> Dict[str, Any]:
"""Get information about bridge integrations and interoperability"""
return {
'canonical_bridge': {
'purpose': 'Official L1 ↔ L2 asset transfer',
'supported_assets': [
'ETH (native Ether)',
'ERC-20 tokens',
'ERC-721 NFTs',
'ERC-1155 multi-tokens'
],
'security_model': 'zkEVM proof validation'
},
'bridge_process': {
'deposits_l1_to_l2': {
'time': '~15 minutes',
'process': [
'Lock assets on L1',
'Wait for L1 confirmation',
'Automatic minting on L2',
'Assets available on L2'
]
},
'withdrawals_l2_to_l1': {
'time': '~7 days',
'process': [
'Burn assets on L2',
'Include in batch',
'Generate zk-proof',
'Submit proof to L1',
'Finalization period',
'Claim assets on L1'
]
}
},
'third_party_bridges': {
'availability': 'Multiple third-party bridge providers',
'considerations': [
'Different security models',
'Varying withdrawal times',
'Different supported assets',
'Additional trust assumptions'
]
}
}
# Usage examples
analyzer = LineaRollupInfoAnalyzer('https://api-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY')
# Get basic rollup information
rollup_info = analyzer.get_rollup_info()
print("Basic Rollup Info:", json.dumps(rollup_info, indent=2))
# Get comprehensive status
comprehensive_status = analyzer.get_comprehensive_rollup_status()
print(f"\nNetwork: {comprehensive_status['network_info']['name']}")
print(f"Chain ID: {comprehensive_status['network_info']['chain_id']}")
print(f"Latest Block: {comprehensive_status['current_state']['latest_block']}")
print(f"Gas Utilization: {comprehensive_status['current_state']['gas_utilization']}%")
# Analyze network type
analysis = comprehensive_status['analysis']
print(f"\nRollup Type: {analysis['rollup_type']}")
print(f"Environment: {analysis['environment']}")
print("Key Features:")
for feature in analysis['key_features']:
print(f" - {feature}")
# Monitor performance (short demo)
print("\nStarting performance monitoring...")
performance_data = analyzer.monitor_rollup_performance(duration_minutes=2)
print("Performance Analysis:")
print(f" Average block time: {performance_data['block_production']['average_block_time']}s")
print(f" Health score: {performance_data['network_health']['health_score']}/100")
# Compare with L1
comparison = analyzer.compare_with_ethereum_l1()
print("\nLinea Advantages:")
for advantage in comparison['advantages_linea']:
print(f" - {advantage}")
# Governance analysis
governance = analyzer.analyze_upgradeability_governance()
print(f"\nGovernance Model: {governance['governance_model']['type']}")
print(f"Upgrade Process Duration: {governance['upgrade_process']['timeframes']['total_process']}")
# Bridge information
bridge_info = analyzer.get_bridge_integration_info()
print(f"\nBridge Withdrawal Time: {bridge_info['bridge_process']['withdrawals_l2_to_l1']['time']}")
print("Supported Assets:")
for asset in bridge_info['canonical_bridge']['supported_assets']:
print(f" - {asset}")
```
## Response Example
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"mode": "zkevm",
"chainId": "0xe708",
"publicInputHash": "0x...",
"stateRoot": "0x...",
"withdrawalRoot": "0x...",
"batchCommitment": "0x...",
"prover": "0x...",
"version": "1.0.0"
}
}
```
## Understanding Linea zkEVM Configuration
### Key Components
1. **Mode**: Operating mode of the rollup (zkEVM)
2. **Chain ID**: Network identifier (59144 for mainnet, 59140 for testnet)
3. **State Root**: Root hash of the current state tree
4. **Batch Commitment**: Commitment to the current batch of transactions
5. **Prover**: Address of the proof generation system
6. **Version**: Current version of the rollup implementation
### zkEVM Architecture
- **Proof System**: Zero-knowledge proofs validate transaction execution
- **Data Availability**: Transaction data posted to Ethereum L1
- **EVM Compatibility**: Full compatibility with Ethereum Virtual Machine
- **Finality**: Probabilistic finality on L2, cryptographic finality via proofs
## Common Use Cases
### 1. Network Health Monitoring
```javascript
// Monitor rollup health and performance
async function monitorRollupHealth(analyzer) {
const healthCheck = async () => {
const status = await analyzer.getComprehensiveRollupStatus();
const alerts = [];
// Check block production
if (status.current_state.block_age_seconds > 300) {
alerts.push({
type: 'stale_blocks',
severity: 'warning',
message: 'Blocks are older than expected'
});
}
// Check gas utilization
if (status.current_state.gas_utilization > 95) {
alerts.push({
type: 'high_utilization',
severity: 'info',
message: 'Network experiencing high usage'
});
}
return {
status: alerts.length === 0 ? 'healthy' : 'warning',
alerts: alerts,
metrics: status.current_state
};
};
return healthCheck;
}
```
### 2. Integration Compatibility Check
```python
def check_integration_compatibility(analyzer):
"""Check if current rollup config is compatible with integration"""
status = analyzer.get_comprehensive_rollup_status()
rollup_info = status['rollup_config']
compatibility = {
'evm_compatible': True, # zkEVM is fully EVM compatible
'supported_features': [
'Standard Ethereum transactions',
'Smart contract deployment',
'ERC token standards',
'Event emission and filtering',
'eth_call and eth_estimateGas',
'Debug and trace methods'
],
'limitations': [
'Proof generation delays for finality',
'L1 data posting affects costs',
'Bridge withdrawals require waiting period'
],
'recommended_practices': [
'Use standard Ethereum tooling',
'Account for L1 fee components',
'Plan for withdrawal delays',
'Monitor gas price fluctuations'
]
}
return compatibility
```
### 3. Performance Benchmarking
```javascript
// Benchmark rollup performance characteristics
async function benchmarkRollupPerformance(analyzer) {
const benchmark = {
testDuration: '10 minutes',
metrics: {},
recommendations: []
};
// Monitor for performance data
const performanceData = await analyzer.monitorRollupPerformance(10);
benchmark.metrics = {
avgBlockTime: performanceData.block_production.average_block_time,
gasUtilization: performanceData.gas_utilization.average,
healthScore: performanceData.network_health.health_score
};
// Generate recommendations
if (benchmark.metrics.avgBlockTime > 15) {
benchmark.recommendations.push(
'Block times are longer than expected - monitor network congestion'
);
}
if (benchmark.metrics.gasUtilization > 80) {
benchmark.recommendations.push(
'High gas utilization - consider transaction timing optimization'
);
}
return benchmark;
}
```
## Integration Considerations
### Development
- **Tooling**: Use standard Ethereum development tools (Hardhat, Truffle, Remix)
- **RPC Compatibility**: Full JSON-RPC compatibility with additional rollup-specific methods
- **Gas Estimation**: Account for both L2 execution and L1 data posting costs
### Production Deployment
- **Security**: Leverage zkEVM's cryptographic security guarantees
- **Monitoring**: Monitor both L2 state and L1 proof submission
- **Bridge Integration**: Plan for canonical bridge usage and withdrawal delays
### User Experience
- **Transaction Speed**: Fast L2 confirmation with eventual L1 finality
- **Cost Optimization**: Optimize transaction data to minimize L1 costs
- **Bridge UX**: Clear communication about withdrawal timeframes
## Related Methods
- [`rollup_gasPrices`](./rollup_gasPrices) - Get gas price oracle data
- [`eth_chainId`](./eth_chainId) - Get network chain ID
- [`eth_getBlockByNumber`](./eth_getBlockByNumber) - Get block information
---
*Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Linea documentation](/docs/linea).*
---
## web3_clientVersion - Linea RPC Method
# web3_clientVersion
Returns the current client version on Linea.
## 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-linea-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-linea-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const version = await provider.send('web3_clientVersion', []);
console.log('Client version:', version);
```
---
## web3_sha3 - Linea RPC Method
# web3_sha3
Returns Keccak-256 (not standard SHA3-256) of the given data on Linea.
## 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-linea-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-linea-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 - LISK RPC Method
# debug_traceBlock
Traces all transactions in a block on LISK 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 real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
## 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-lisk-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-lisk-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 - LISK RPC Method
# debug_traceBlockByHash
Traces all transactions in a block on LISK 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": ["0x064ed396ec4bb9cd919f1ae9726064a32907a39da179a89fda4d094f0c0a89cf", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-lisk-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceBlockByHash",
"params": ["0x064ed396ec4bb9cd919f1ae9726064a32907a39da179a89fda4d094f0c0a89cf", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-lisk-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0x064ed396ec4bb9cd919f1ae9726064a32907a39da179a89fda4d094f0c0a89cf';
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 - LISK RPC Method
# debug_traceBlockByNumber
Traces all transactions in a block on LISK 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-lisk-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-lisk-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 - LISK RPC Method
# debug_traceCall
Traces a call without creating a transaction on LISK.
:::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 real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
## 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-lisk-mainnet.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-lisk-mainnet.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 - LISK RPC Method
# debug_traceTransaction
Traces a transaction execution on LISK 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 real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
## 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": ["0xc4ae02aa92a92ec161500444ec71945530760e062742f1745c0969a4fce864b9", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-lisk-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceTransaction",
"params": ["0xc4ae02aa92a92ec161500444ec71945530760e062742f1745c0969a4fce864b9", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-lisk-mainnet.n.dwellir.com/YOUR_API_KEY');
const txHash = '0xc4ae02aa92a92ec161500444ec71945530760e062742f1745c0969a4fce864b9';
// 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-lisk-mainnet.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0xc4ae02aa92a92ec161500444ec71945530760e062742f1745c0969a4fce864b9'
# 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 - LISK RPC Method
# eth_accounts
Returns a list of addresses owned by the client on LISK.
> **Why LISK?** Build on the first L1-to-Superchain L2 focused on real-world assets and emerging markets with OP Stack Superchain integration, Gelato rollup-as-a-service, 500K OP grant, and LSK token migration from L1.
## 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 RWA developers, DePIN builders, and teams targeting Southeast Asia and Africa 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-lisk-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-lisk-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-lisk-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-lisk-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-lisk-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-lisk-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 - LISK RPC Method
# eth_blockNumber
Returns the number of the most recent block on LISK.
> **Why LISK?** Build on the first L1-to-Superchain L2 focused on real-world assets and emerging markets with OP Stack Superchain integration, Gelato rollup-as-a-service, 500K OP grant, and LSK token migration from L1.
## When to Use This Method
`eth_blockNumber` is fundamental for RWA developers, DePIN builders, and teams targeting Southeast Asia and Africa markets:
- **Syncing Applications** — Keep your dApp in sync with the latest LISK blockchain state
- **Transaction Monitoring** — Verify confirmations by comparing block numbers
- **Event Filtering** — Set the correct block range for querying logs on real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
- **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-lisk-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-lisk-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('LISK block:', blockNumber);
// Using ethers.js
const provider = new JsonRpcProvider('https://api-lisk-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockNumber = await provider.getBlockNumber();
console.log('LISK block:', blockNumber);
```
```python
def get_block_number():
response = requests.post(
'https://api-lisk-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'LISK block: {block_number}')
# Using web3.py
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-lisk-mainnet.n.dwellir.com/YOUR_API_KEY'))
print(f'LISK 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-lisk-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("LISK block: %d\n", blockNumber)
}
```
## Common Use Cases
### 1. Block Confirmation Counter
Monitor transaction confirmations on LISK:
```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 LISK:
```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 LISK 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-lisk-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 - LISK RPC Method
# eth_call
Executes a new message call immediately without creating a transaction on LISK. Used for reading smart contract state.
> **Why LISK?** Build on the first L1-to-Superchain L2 focused on real-world assets and emerging markets with OP Stack Superchain integration, Gelato rollup-as-a-service, 500K OP grant, and LSK token migration from L1.
## 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 real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
- **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-lisk-mainnet.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-lisk-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-lisk-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(
'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-lisk-mainnet.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 - LISK RPC Method
# eth_chainId
Returns the chain ID used for transaction signing on LISK.
> **Why LISK?** Build on the first L1-to-Superchain L2 focused on real-world assets and emerging markets with OP Stack Superchain integration, Gelato rollup-as-a-service, 500K OP grant, and LSK token migration from L1.
## 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-lisk-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-lisk-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-lisk-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-lisk-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(Lisk)
# eth_coinbase
Get coinbase address on the Lisk 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-lisk-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-lisk-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 [Lisk documentation](/docs/lisk).*
---
## eth_estimateGas - LISK RPC Method
# eth_estimateGas
Estimates the gas necessary to execute a transaction on LISK.
> **Why LISK?** Build on the first L1-to-Superchain L2 focused on real-world assets and emerging markets with OP Stack Superchain integration, Gelato rollup-as-a-service, 500K OP grant, and LSK token migration from L1.
## 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 real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
## 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-lisk-mainnet.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-lisk-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-lisk-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('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-lisk-mainnet.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_feeHistory - LISK RPC Method
# eth_feeHistory
Returns historical gas information on LISK 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 real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
## 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-lisk-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-lisk-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-lisk-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 - LISK RPC Method
# eth_gasPrice
Returns the current gas price on LISK in wei.
> **Why LISK?** Build on the first L1-to-Superchain L2 focused on real-world assets and emerging markets with OP Stack Superchain integration, Gelato rollup-as-a-service, 500K OP grant, and LSK token migration from L1.
## 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 real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
## 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-lisk-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-lisk-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-lisk-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-lisk-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 - LISK RPC Method
# eth_getBalance
Returns the balance of a given address on LISK.
> **Why LISK?** Build on the first L1-to-Superchain L2 focused on real-world assets and emerging markets with OP Stack Superchain integration, Gelato rollup-as-a-service, 500K OP grant, and LSK token migration from L1.
## 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 real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
- **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-lisk-mainnet.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-lisk-mainnet.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-lisk-mainnet.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-lisk-mainnet.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 - LISK RPC Method
# eth_getBlockByHash
Returns information about a block by hash on LISK.
> **Why LISK?** Build on the first L1-to-Superchain L2 focused on real-world assets and emerging markets with OP Stack Superchain integration, Gelato rollup-as-a-service, 500K OP grant, and LSK token migration from L1.
## 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 real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
- **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": [
"0x064ed396ec4bb9cd919f1ae9726064a32907a39da179a89fda4d094f0c0a89cf",
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-lisk-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByHash",
"params": [
"0x064ed396ec4bb9cd919f1ae9726064a32907a39da179a89fda4d094f0c0a89cf",
false
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-lisk-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0x064ed396ec4bb9cd919f1ae9726064a32907a39da179a89fda4d094f0c0a89cf';
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-lisk-mainnet.n.dwellir.com/YOUR_API_KEY'))
block_hash = '0x064ed396ec4bb9cd919f1ae9726064a32907a39da179a89fda4d094f0c0a89cf'
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-lisk-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
blockHash := common.HexToHash("0x064ed396ec4bb9cd919f1ae9726064a32907a39da179a89fda4d094f0c0a89cf")
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 - LISK RPC Method
# eth_getBlockByNumber
Returns information about a block by block number on LISK.
> **Why LISK?** Build on the first L1-to-Superchain L2 focused on real-world assets and emerging markets with OP Stack Superchain integration, Gelato rollup-as-a-service, 500K OP grant, and LSK token migration from L1.
## 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 real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
- **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": "0x064ed396ec4bb9cd919f1ae9726064a32907a39da179a89fda4d094f0c0a89cf",
"parentHash": "0x...",
"timestamp": "0x64d8f6d0",
"gasUsed": "0x1234",
"gasLimit": "0x1c9c380",
"transactions": [],
"baseFeePerGas": "0x5f5e100"
}
}
```
## Code Examples
```bash
curl -X POST https://api-lisk-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-lisk-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-lisk-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-lisk-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 - LISK RPC Method
# eth_getCode
Returns the bytecode at a given address on LISK.
> **Why LISK?** Build on the first L1-to-Superchain L2 focused on real-world assets and emerging markets with OP Stack Superchain integration, Gelato rollup-as-a-service, 500K OP grant, and LSK token migration from L1.
## 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 real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
## 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-lisk-mainnet.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-lisk-mainnet.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-lisk-mainnet.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-lisk-mainnet.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 - LISK RPC Method
# eth_getFilterChanges
Polling method for a filter on LISK, returns an array of logs since last poll.
## Use Cases
- **Event streaming** - Get new events incrementally
- **Real-time monitoring** - Track contract activity for real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
- **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-lisk-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-lisk-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 - LISK RPC Method
# eth_getFilterLogs
Returns an array of all logs matching filter with given ID on LISK.
## Use Cases
- **Historical queries** - Get all matching logs for a filter
- **Full event history** - Retrieve complete event data for real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
## 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-lisk-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-lisk-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 - LISK RPC Method
# eth_getLogs
Returns an array of all logs matching a given filter object on LISK.
> **Why LISK?** Build on the first L1-to-Superchain L2 focused on real-world assets and emerging markets with OP Stack Superchain integration, Gelato rollup-as-a-service, 500K OP grant, and LSK token migration from L1.
## Use Cases
The `eth_getLogs` method is essential for:
- **Event indexing** - Track contract events for real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
- **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-lisk-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": "0x4200000000000000000000000000000000000006",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-lisk-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(
'0x4200000000000000000000000000000000000006',
'latest',
'latest'
);
console.log('Transfer events:', events);
```
```python
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-lisk-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(
'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-lisk-mainnet.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 - LISK RPC Method
# eth_getStorageAt
Returns the value from a storage position at a given address on LISK.
## Use Cases
- **Contract analysis** - Read raw storage values
- **State verification** - Verify contract state
- **Security auditing** - Analyze storage layout for real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
- **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-lisk-mainnet.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-lisk-mainnet.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-lisk-mainnet.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 - LISK RPC Method
# eth_getTransactionByHash
Returns the information about a transaction by transaction hash on LISK.
> **Why LISK?** Build on the first L1-to-Superchain L2 focused on real-world assets and emerging markets with OP Stack Superchain integration, Gelato rollup-as-a-service, 500K OP grant, and LSK token migration from L1.
## 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 real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
- **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": ["0xc4ae02aa92a92ec161500444ec71945530760e062742f1745c0969a4fce864b9"],
"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-lisk-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionByHash",
"params": ["0xc4ae02aa92a92ec161500444ec71945530760e062742f1745c0969a4fce864b9"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-lisk-mainnet.n.dwellir.com/YOUR_API_KEY');
const txHash = '0xc4ae02aa92a92ec161500444ec71945530760e062742f1745c0969a4fce864b9';
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-lisk-mainnet.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0xc4ae02aa92a92ec161500444ec71945530760e062742f1745c0969a4fce864b9'
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-lisk-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0xc4ae02aa92a92ec161500444ec71945530760e062742f1745c0969a4fce864b9")
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 - LISK RPC Method
# eth_getTransactionCount
Returns the number of transactions sent from an address on LISK (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 real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
## 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-lisk-mainnet.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-lisk-mainnet.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-lisk-mainnet.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 - LISK RPC Method
# eth_getTransactionReceipt
Returns the receipt of a transaction by transaction hash on LISK. Receipt is only available for mined transactions.
> **Why LISK?** Build on the first L1-to-Superchain L2 focused on real-world assets and emerging markets with OP Stack Superchain integration, Gelato rollup-as-a-service, 500K OP grant, and LSK token migration from L1.
## 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 real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `transactionHash` | `DATA` | Yes | 32-byte transaction hash |
## Request
```json
{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0xc4ae02aa92a92ec161500444ec71945530760e062742f1745c0969a4fce864b9"],
"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-lisk-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0xc4ae02aa92a92ec161500444ec71945530760e062742f1745c0969a4fce864b9"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-lisk-mainnet.n.dwellir.com/YOUR_API_KEY');
const txHash = '0xc4ae02aa92a92ec161500444ec71945530760e062742f1745c0969a4fce864b9';
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-lisk-mainnet.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0xc4ae02aa92a92ec161500444ec71945530760e062742f1745c0969a4fce864b9'
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-lisk-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0xc4ae02aa92a92ec161500444ec71945530760e062742f1745c0969a4fce864b9")
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(Lisk)
# eth_hashrate
Get node hashrate on the Lisk 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-lisk-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-lisk-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 [Lisk documentation](/docs/lisk).*
---
## eth_maxPriorityFeePerGas - LISK RPC Method
# eth_maxPriorityFeePerGas
Returns the current recommended priority fee per gas on LISK 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 real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
## 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-lisk-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-lisk-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-lisk-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(Lisk)
# eth_mining
Check if node is mining on the Lisk 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-lisk-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-lisk-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 [Lisk documentation](/docs/lisk).*
---
## eth_newBlockFilter - LISK RPC Method
# eth_newBlockFilter
Creates a filter on LISK 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-lisk-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-lisk-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 - LISK RPC Method
# eth_newFilter
Creates a filter object on LISK to notify when state changes (logs).
## Use Cases
- **Event monitoring** - Subscribe to contract events
- **Real-time updates** - Track events for real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
- **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-lisk-mainnet.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-lisk-mainnet.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 - LISK RPC Method
# eth_newPendingTransactionFilter
Creates a filter on LISK 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-lisk-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-lisk-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(Lisk)
# eth_protocolVersion
Get protocol version on the Lisk 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-lisk-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-lisk-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 [Lisk documentation](/docs/lisk).*
---
## eth_sendRawTransaction - LISK RPC Method
# eth_sendRawTransaction
Submits a pre-signed transaction for broadcast to LISK.
> **Why LISK?** Build on the first L1-to-Superchain L2 focused on real-world assets and emerging markets with OP Stack Superchain integration, Gelato rollup-as-a-service, 500K OP grant, and LSK token migration from L1.
## 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 real-world asset tokenization, decentralized physical infrastructure (DePIN), and emerging market financial access
- **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-lisk-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-lisk-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-lisk-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-lisk-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("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...(Lisk)
# eth_sendTransaction
> **Important**: Dwellir's shared Lisk 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-lisk-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 (rarely...(Lisk)
# 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-lisk-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-lisk-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 [Lisk documentation](/docs/lisk).*
---
## eth_syncing - LISK RPC Method
# eth_syncing
Returns syncing status of LISK 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-lisk-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-lisk-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 - LISK RPC Method
# eth_uninstallFilter
Uninstalls a filter on LISK. 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-lisk-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-lisk-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
---
## Lisk - Ethereum L2 Documentation
# Lisk L2 - Build for High-Growth Markets
## Why Build on Lisk?
Lisk is the first Layer 1 to successfully transition to an Ethereum Layer 2, focusing on real-world applications in emerging markets. Built on Optimism's OP Stack, Lisk offers:
### 🚀 **Optimized Performance**
- **2-second block times** - Fast transaction confirmations
- **10-100x lower costs** than Ethereum mainnet
- **Full EVM equivalence** - Deploy without modifications
### 🛡️ **Proven Security**
- **First L1 to L2 migration** - Successfully transitioned from Layer 1
- **Ethereum security** - Inherits L1 security guarantees via Optimism
- **OP Stack powered** - Built on battle-tested technology
### 🌍 **Emerging Markets Focus**
- **Real-world assets (RWA)** - Specialized for tokenization
- **DePIN applications** - Decentralized physical infrastructure
- **High-growth markets** - Optimized for emerging economies
## Quick Start with Lisk
Connect to Lisk in seconds with Dwellir's optimized endpoints:
### Installation & Setup
```javascript
// Connect to Lisk mainnet
const provider = new JsonRpcProvider(
'https://api-lisk-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 Lisk mainnet
const web3 = new Web3(
'https://api-lisk-mainnet.n.dwellir.com/YOUR_API_KEY'
);
// Get chain ID to verify connection
const chainId = await web3.eth.getChainId();
console.log('Connected to Lisk:', chainId === 1135);
// Get gas price for optimal transaction pricing
const gasPrice = await web3.eth.getGasPrice();
console.log('Current gas price:', gasPrice);
```
```typescript
// Create Lisk client
const client = createPublicClient({
chain: lisk,
transport: http('https://api-lisk-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
1135
Mainnet
Block Time
2 seconds
Average
Gas Token
ETH
Native token
RPC Standard
Ethereum
JSON-RPC 2.0
## JSON-RPC API Reference
Lisk supports the full [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/). Access all standard methods with L2 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 Lisk L2:
```javascript
// Estimate L2 execution gas
const l2Gas = await provider.estimateGas(tx);
// For L1 data fees on Lisk, fees are handled automatically
// Total gas cost includes both L2 execution and L1 data posting
```
### 🔍 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; // Lisk 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-lisk-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 transaction"
Lisk transactions require ETH for both L2 execution and L1 data availability:
```javascript
// Always account for total gas costs
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) {
throw new Error(`Need ${totalRequired - balance} more ETH`);
}
```
### Error: "Transaction underpriced"
Lisk 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 Lisk L2 requires minimal changes:
```javascript
// Before (Ethereum)
const provider = new JsonRpcProvider('https://eth-rpc.example.com');
// After (Lisk)
const provider = new JsonRpcProvider(
'https://api-lisk-mainnet.n.dwellir.com/YOUR_API_KEY'
);
// ✅ Smart contracts work identically
// ✅ Same tooling and libraries
// ⚠️ Different chain ID (1135)
// ⚠️ Separate block numbers
// ⚠️ L1 data fees apply
```
## Resources & Tools
### Official Resources
- [Lisk Documentation](https://docs.lisk.com)
- [Lisk Portal](https://portal.lisk.com)
- [Lisk Block Explorer](https://blockscout.lisk.com)
### Developer Tools
- [Hardhat Config](https://docs.lisk.com/tools/hardhat)
- [Foundry Setup](https://docs.lisk.com/tools/foundry)
- [Development Guide](https://docs.lisk.com/build)
### Need Help?
- 📧 **Email**: support@dwellir.com
- 📚 **Docs**: You're here!
- 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com)
---
*Start building on Lisk with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## net_listening - LISK RPC Method
# net_listening
Returns `true` if client is actively listening for network connections on LISK.
## 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-lisk-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-lisk-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 - LISK RPC Method
# net_peerCount
Returns number of peers currently connected to LISK 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-lisk-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-lisk-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 - LISK RPC Method
# net_version
Returns the current network ID on LISK.
## 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-lisk-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-lisk-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 - LISK RPC Method
# web3_clientVersion
Returns the current client version on LISK.
## 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-lisk-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-lisk-mainnet.n.dwellir.com/YOUR_API_KEY');
const version = await provider.send('web3_clientVersion', []);
console.log('Client version:', version);
```
---
## web3_sha3 - LISK RPC Method
# web3_sha3
Returns Keccak-256 (not standard SHA3-256) of the given data on LISK.
## 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-lisk-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-lisk-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 - Manta Atlantic RPC Method
# author_pendingExtrinsics
Returns all pending extrinsics in the transaction pool on Manta Atlantic.
## Use Cases
- **Mempool monitoring** - Track pending transactions
- **Transaction status** - Check if your transaction is pending for private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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 - Manta Atlantic RPC Method
# author_rotateKeys
Generate a new set of session keys on Manta Atlantic. 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 private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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-manta-atlantic-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 - Manta Atlantic 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 private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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 - Manta Atlantic RPC Method
# author_submitExtrinsic
Submit a signed extrinsic to Manta Atlantic for inclusion in a block.
## Use Cases
- **Transaction submission** - Broadcast signed transactions
- **dApp interactions** - Execute on-chain operations for private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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 - Manta Atlantic RPC Method
# beefy_getFinalizedHead
Returns the block hash of the latest BEEFY-finalized block on Manta Atlantic. 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 private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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-manta-atlantic-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
---
## chain_getBlock - Manta Atlantic RPC Method
# chain_getBlock
Retrieves complete block information from Manta Atlantic, including the block header, extrinsics, and justifications.
> **Why Manta Atlantic?** Build on the ZK Layer 1 on Polkadot enabling private transactions and on-chain compliance identities with zkSNARK-powered privacy, modular compliance identities, MANTA token staking hub, and end-to-end transaction privacy.
## 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 private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-mainnet.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-manta-atlantic-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 = '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-manta-atlantic-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('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 - Manta Atlantic RPC Method
# chain_getBlockHash
Returns the block hash for a given block number on Manta Atlantic.
## Use Cases
- **Historical queries** - Convert block numbers to hashes
- **Block navigation** - Navigate blockchain history for private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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-manta-atlantic-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 - Manta Atlantic RPC Method
# chain_getFinalizedHead
Returns the hash of the last finalized block on Manta Atlantic.
## Use Cases
- **Confirmed state** - Query state that cannot be reverted
- **Transaction confirmation** - Verify transaction finality for private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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-manta-atlantic-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_getHeader - Manta Atlantic RPC Method
# chain_getHeader
Returns the block header for a given hash on Manta Atlantic.
## Use Cases
- **Lightweight queries** - Get header without full block data
- **Chain synchronization** - Track block production for private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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-manta-atlantic-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_subscribeFinalizedHeads - Manta Atlantic RPC Method
# chain_subscribeFinalizedHeads
Subscribe to receive notifications when blocks are finalized on Manta Atlantic. 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 private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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 - Manta Atlantic RPC Method
# chain_subscribeNewHeads
Subscribe to receive notifications when new block headers are produced on Manta Atlantic. This WebSocket subscription provides real-time updates for each new block.
## Use Cases
- **Block monitoring** - Track new blocks in real-time for private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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
---
## grandpa_roundState - Manta Atlantic RPC Method
# grandpa_roundState
Returns the state of the current GRANDPA finality round on Manta Atlantic. GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) is the finality gadget used by Substrate chains.
## Use Cases
- **Finality monitoring** - Track consensus progress for private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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-manta-atlantic-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)
---
## Manta Atlantic - ZK Identity L1 Guide
# Manta Atlantic - ZK Identity L1 on Polkadot
## Why Build on Manta Atlantic?
- **Fastest zk Layer 1 on Polkadot** – Atlantic specializes in zero-knowledge identity proofs with high-throughput circuits powering zkSoulbound credentials for millions of users.
- **Programmable privacy-preserving identities** – zkSBTs, selective disclosure primitives, and proof tooling let teams ship compliant identity workflows without exposing raw user data.
- **On-chain compliance infrastructure** – The NPO (NFT Private Offering) stack supports private KYC/AML verification, credential revocation, and auditable reporting for regulated deployments.
- **Interoperability across Polkadot** – As parachain 2104, Atlantic inherits shared security, XCMP messaging, and bridges into ecosystems like Moonbeam, Bifrost, and Ethereum.
## Quick Start with Manta Atlantic
Connect to Atlantic's production archive endpoint (no public testnet) using your Dwellir API key:
Replace `YOUR_API_KEY` after you [create an account](https://dashboard.dwellir.com/register). The WebSocket endpoint is available at `wss://api-manta-atlantic-mainnet.n.dwellir.com/YOUR_API_KEY`.
### Connect with @polkadot/api
```typescript
const provider = new WsProvider('wss://api-manta-atlantic-mainnet.n.dwellir.com/YOUR_API_KEY');
const api = await ApiPromise.create({ provider });
// Confirm network metadata
const chain = await api.rpc.system.chain();
console.log(`Connected to ${chain.toString()}`);
// Fetch the latest finalized block
const latest = await api.rpc.chain.getBlock();
console.log('Finalized block number', latest.block.header.number.toNumber());
```
### Rust (subxt) bootstrap
```rust
use subxt::{config::polkadot::PlainConfig, OnlineClient};
#[subxt::subxt(runtime_metadata_url = "wss://api-manta-atlantic-mainnet.n.dwellir.com/YOUR_API_KEY")]
pub mod manta_atlantic {}
#[tokio::main]
async fn main() -> Result<(), Box> {
let api = OnlineClient::::from_url(
"wss://api-manta-atlantic-mainnet.n.dwellir.com/YOUR_API_KEY"
).await?;
let runtime = api.runtime_version().await?;
println!("Spec version: {}", runtime.spec_version);
Ok(())
}
```
## Network Information
Parachain ID
2104
Registered on Polkadot Relay Chain
Consensus
NPoS + zk circuits
Collators submit zk-validated state proofs
Average Block Time
≈ 13.3 seconds
Measured 7-day mean on Polkadot OpenGov metrics
Native Token
MANTA
Used for staking, fees, and collator bonds
- Atlantic currently operates with 54 active collators securing 101.8M staked MANTA, delivering finality via GRANDPA on top of zk-verified execution.
- Average observed block time over the last seven days is roughly 13.35 seconds, based on PublicNode telemetry for Atlantic RPC endpoints.
- Collators must post a 400,000 MANTA self-bond and earn rewards from a 2% annual inflation stream dedicated to parachain security.
- Stakers escalate nominations in 6-hour rounds with a 7-day unbonding period, aligning incentives for compliance workloads that need predictable uptime.
- Polkadot’s asynchronous backing upgrade enables 6-second parachain blocks, and Atlantic’s roadmap targets these throughput gains as host chain optimizations roll out.
## JSON-RPC API Reference
Atlantic exposes the full Substrate JSON-RPC surface, including `chain_*`, `state_*`, and `author_*` namespaces for block data, storage access, and extrinsic submission.
| Category | Key Methods | Use Cases |
| --- | --- | --- |
| Chain | `chain_getBlock`, `chain_getFinalizedHead` | Retrieve zk-anchored parachain blocks and finality proofs |
| State | `state_getStorage`, `state_getRuntimeVersion` | Inspect identity pallets, zk credential registries, and runtime metadata |
| Author | `author_submitExtrinsic`, `author_pendingExtrinsics` | Submit zkSBT transactions and monitor queue health |
### Sample cURL call
```bash
curl https://api-manta-atlantic-mainnet.n.dwellir.com/YOUR_API_KEY \
-H 'Content-Type: application/json' \
-d '{
"jsonrpc": "2.0",
"method": "chain_getBlock",
"params": [],
"id": 1
}'
```
Explore detailed method docs in the [RPC reference](/manta-atlantic/chain_getBlock).
## Privacy Features Overview
- **zkSBTs for regulated identity** – Issue, revoke, and expire credentials privately using Manta’s zkSBT runtime modules and Prove Keys for selective disclosure.
- **Programmable identity fabric** – Compose verifiable credentials, attestations, and session keys tied to zk addresses for multi-jurisdictional compliance.
- **Privacy-preserving credential analytics** – Aggregate issuance stats and revocation logs without exposing user PII, using off-chain indexers that consume hashed commitments.
Deep dives:
- [Zero-Knowledge Soulbound Tokens](/manta-atlantic/zksbt_overview)
- [Programmable Identities](/manta-atlantic/programmable_identities)
- [Compliance Infrastructure](/manta-atlantic/compliance_infrastructure)
- [zkAddress System](/manta-atlantic/zkaddress_system)
## zkAddress System
Atlantic assigns every participant a standard Substrate account **and** a shielded UTXO-style address, enabling private balance updates while maintaining compatibility with Polkadot tooling.
- Establishes confidentiality via one-time addresses and viewing keys while preserving interoperability with public XCMP channels.
- Selective disclosure relies on user-controlled Prove Keys so only authorized verifiers can inspect credential proofs.
## Compliance Tools
- **zkKYC verification** – Issuers attest to KYC completion without storing underlying documents on-chain, satisfying policy requirements for permissioned DeFi.
- **Audit-friendly reporting** – Regulators receive revocation or expiry events derived from zk commitments, rather than raw identity data.
- **Bridges to off-chain capital markets** – Bifrost and other parachains integrate Atlantic credentials to wrap staking positions (vMANTA) and unlock liquidity while preserving privacy.
## Development Guides
1. **Issue zkSBTs** – Follow the [minting guide](/manta-atlantic/zksbt_overview) to register issuers, define schemas, and broadcast credential extrinsics.
2. **Build programmable identity flows** – Combine zkAddress guardrails with session-based Prove Keys to create reusable identity vaults.
3. **Integrate compliance pipelines** – Map `identity_verifyCredential` RPC calls to your policy engine for real-time access control.
## Troubleshooting
- **Proof generation stalls** – Re-sync proving key material and confirm `zk_generateProof` inputs match runtime-cached schema hashes.
- **Credential verification failures** – Ensure the verifier holds the latest Prove Key rotation and that revocation registries are in sync via `state_getStorage`.
- **Cross-chain settlement delays** – Monitor collator liveness (6-hour nomination cycles) and confirm asynchronous backing slots are available before submitting high-value transfers.
## Resources & Tools
- **Manta Atlantic Docs** – Official zkSBT, zkAddress, and Prove Key specifications.
- **Manta Network State of the Network (Q1 2025)** – Collator metrics, staking economics, and deprecation roadmap through July 2026.
- **MANTA Staking Guide** – How-to for nominators, collators, and reward cycles.
- **Messari Protocol Overview** – Historical issuance data and compliance-focused adoption metrics.
- **Substrate JSON-RPC Spec** – Authoritative method definitions for `chain_*`, `state_*`, and `author_*`.
Ready to build? [Get your API key](https://dashboard.dwellir.com/register) and start integrating Manta Atlantic today.
---
## payment_queryFeeDetails - Manta Atlantic RPC Method
# payment_queryFeeDetails
Returns a detailed breakdown of fees for a given extrinsic on Manta Atlantic. 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 private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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-manta-atlantic-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 - Manta Atlantic RPC Method
# payment_queryInfo
Estimates the fee for an extrinsic on Manta Atlantic.
## Use Cases
- **Fee estimation** - Calculate transaction costs before sending
- **UI display** - Show fees to users for private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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
---
## Compliance Infrastructure
Manta Atlantic provides a full-stack compliance toolkit: zkSBT credentials, verifier keys, and reporting channels that satisfy regulatory needs without leaking personal data.
## Private KYC/AML
- **KYC attestations** – Issuers publish zk proofs confirming identity verification; verifiers only see proof validity, not raw documents.
- **AML screening** – Credential schemas incorporate sanctions or risk flags that can be checked via `identity_verifyCredential` during transaction authorization.
- **Revocation** – Nullifiers revoke credentials instantly, ensuring revoked users cannot pass future checks.
## Reporting & Auditing
| Requirement | Atlantic Capability | Notes |
| --- | --- | --- |
| Regulator visibility | Access aggregated issuance and revocation metrics without identity leakage. | Aligns with NPO reporting flows for enterprise partners. |
| Proof of compliance | Share verifier logs demonstrating successful zk checks, signed with issuer keys. | Works with Prove Key distribution model. |
| Lifecycle transparency | Track credential status via `state_getStorage` queries on registry pallets. | Integrate into SOC2 or ISO audit evidence bundles. |
## Operational Controls
1. **Issuer governance** – Participate in network governance to stay aligned with Atlantic’s deprecation plan and runtime upgrades.
2. **Staking economics** – Collator incentives (2% inflation, 6-hour payout cadence) prioritize availability required for compliance workloads.
3. **Disaster recovery** – Maintain off-chain backups of Prove Keys and witness generators; Atlantic’s zk circuits can regenerate proofs if keys rotate.
## Integration Playbook
- Map each compliance policy to a credential schema (e.g., KYC Tier 2, Accredited Investor) and automate issuance via CI pipelines.
- Use asynchronous backing-aware monitoring to ensure block production throughput before onboarding large partners.
- Coordinate with bridging partners such as Bifrost to wrap compliant positions (vMANTA) while preserving privacy guarantees.
Next up: understand the [zkAddress System](./zkaddress_system) for private settlement flows.
---
## Programmable Identities
# Programmable Identities on Manta Atlantic
Manta Atlantic combines zkAddresses, zkSBTs, and selective disclosure keys to let builders compose identity systems that bridge on-chain compliance with user-centric privacy.
## Core Building Blocks
- **zkAddress pairs** – Every participant controls a public Substrate account plus a shielded address for confidential asset and credential management.
- **Prove Keys** – Holders distribute verification keys to specific relying parties, enabling selective KYC disclosure without exposing global viewing access.
- **Programmable schemas** – Issuers encode logic for membership, accreditation, jurisdiction, or AML flags, then publish updates via runtime governance.
## Identity Vault Pattern
1. **Bootstrap** – Derive zkAddresses for each user and link them to public accounts through encrypted off-chain registries.
2. **Credential orchestration** – Automate zkSBT issuance on approval events (KYC pass, accreditation, residency confirmation).
3. **Session management** – Rotate Prove Keys per relying party and attach policy metadata (expiry, scope, revocation callbacks).
4. **Audit hooks** – Stream anonymized issuance metrics to monitoring stacks for compliance reporting.
## Cross-Chain Portability
- Atlantic credentials travel to other Polkadot parachains through XCMP, unlocking composability with DeFi venues such as Bifrost’s vMANTA staking derivatives.
- Identity payloads can also bridge to EVM ecosystems (e.g., Moonbeam, Ethereum) using Manta’s interoperability hubs, preserving privacy across domains.
## Policy-Driven Verification
| Requirement | Implementation Strategy |
| --- | --- |
| Geographic access | Encode jurisdiction attributes inside credential schema and check using `identity_verifyCredential`, which wraps the zk verification flow described in the NPO compliance docs. |
| Transaction caps | Track credential usage counts off-chain and rotate Prove Keys when session budgets are exhausted. |
| AML monitoring | Subscribe to revocation events and apply business rules before processing settlement. |
## Governance & Roadmap
- Manta Atlantic is scheduled for deprecation in July 2026; plan migrations to successor deployments while leveraging Atlantic for near-term compliance projects.
- Participation in staking/governance keeps credential issuers aligned with network updates that may alter identity pallet semantics.
Proceed to [Compliance Infrastructure](./compliance_infrastructure) for regulatory workflows.
---
## zkAddress System
Manta Atlantic augments traditional Substrate accounts with shielded zkAddresses so users can transact privately while retaining compatibility with Polkadot tooling.
## Dual-Address Model
- **Public account** – Handles staking, governance, and XCMP interactions using standard Polkadot keys.
- **Private zkAddress** – Holds UTXO-style notes that represent balances, credentials, or proofs, enabling confidential transfers and credential issuance.
## Key Concepts
| Component | Purpose |
| --- | --- |
| Viewing Key | Lets holders inspect their private note set locally without revealing it to the network. |
| Prove Key | Grants third parties the ability to verify specific proofs, supporting selective disclosure in compliance workflows. |
| Note Commitment | Binds balances or credentials to zkAddresses using commitments stored in Atlantic’s runtime. |
## Private Transaction Flow
1. **Note creation** – Sender generates a new commitment and encrypts the payload with the recipient’s viewing key.
2. **Proof generation** – Sender calls `zk_generateProof` to produce a zero-knowledge proof of validity without revealing note contents.
3. **Submission** – The proof and ciphertext are broadcast via extrinsic or RPC, updating the UTXO set while keeping balances hidden.
4. **Consumption** – Recipient scans encrypted updates, decrypts matching notes, and updates their local wallet state.
## Interoperability
- zkAddresses can export proofs to partner chains (e.g., Bifrost, Moonbeam) to unlock wrapped liquidity without disclosing identities.
- Polkadot asynchronous backing keeps private transfers within expected latency bounds even during high throughput periods.
## Operational Tips
- Rotate Prove Keys regularly and record distribution logs to maintain auditability.
- Cache circuit parameters locally to avoid latency spikes in proof generation services.
- Monitor `state_getStorage` for note commitment merkle roots to keep client state synchronized.
For RPC invocation details, refer to the Manta Atlantic documentation.
---
## zkSBT Overview
# Zero-Knowledge Soulbound Tokens (zkSBTs)
Manta Atlantic’s zkSBT framework lets issuers attest to real-world identity or compliance checks without ever exposing the underlying documents on-chain.
## Why zkSBTs Matter
- **Private attestations** – zkSBT proofs encode that requirements (KYC, accreditation, residency) have been met while leaking no raw attributes.
- **Programmable lifecycle** – Issuers can define expiry, revocation conditions, and delegation policies enforced by runtime modules.
- **Adoption at scale** – Over 1.16 million zkSBTs have been minted for 1.5+ million Web3 users, demonstrating production readiness.
## Architecture
1. **Schema registry** – Issuers register credential schemas that define statement circuits and commitment formats.
2. **Witness generation** – Sensitive data stays off-chain; issuers compute witnesses locally and generate Groth16 proofs compatible with Atlantic’s circuits.
3. **zkSBT pallet** – Proofs are submitted as extrinsics, minting non-transferable tokens bound to a user’s zkAddress commitment.
4. **Selective disclosure** – Holders derive viewing access with Prove Keys so verifiers can validate claims without deanonymizing accounts.
## Issuance Workflow
1. **Register issuer keys** – Broadcast an extrinsic to enrol your issuer DID and publishing key.
2. **Publish schema** – Commit schema metadata (description, constraint hash, revocation type).
3. **Generate proof** – Use the trusted setup artifacts to compute a zk proof tied to the recipient’s zkAddress commitment.
4. **Submit `sbt_mintPrivate`** – Call the RPC (or runtime extrinsic) with the proof, note, and expiry metadata.
5. **Distribute Prove Keys** – Share verification keys with relying parties via secure out-of-band channels.
## Revocation & Compliance
- **Revocation lists** – Issuers can revoke credentials by publishing nullifiers; verifiers check revocation registries during proof verification.
- **Expiry logic** – zkSBTs include timestamps so expired credentials fail verification automatically.
- **Audit trails** – Regulators can audit aggregate issuance and revocation counts without linking to individual identities.
## Integration Checklist
- Sync the latest proving and verification keys from the official repositories.
- Monitor revocation registries via `state_getStorage` to invalidate stale credentials quickly.
- Store credential metadata in encrypted vaults; only commitments and nullifiers hit the chain.
- Automate issuance with CI pipelines so every new compliance approval emits a zkSBT mint.
Next: implement the workflow end-to-end in [Programmable Identities](./programmable_identities).
---
## rpc_methods - Manta Atlantic RPC Method
# rpc_methods
Returns a list of all RPC methods available on Manta Atlantic.
## Use Cases
- **API discovery** - List all available methods
- **Compatibility checking** - Verify method availability for private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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 - Manta Atlantic RPC Method
# state_call
Calls a runtime API method on Manta Atlantic.
## Use Cases
- **Runtime computations** - Execute runtime logic without transactions
- **Account queries** - Use AccountNonceApi for private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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_getKeysPaged - Manta Atlantic RPC Method
# state_getKeysPaged
Returns storage keys with pagination on Manta Atlantic.
## Use Cases
- **Storage iteration** - Enumerate storage map entries
- **Data export** - Bulk export chain data for private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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_getMetadata - Manta Atlantic RPC Method
# state_getMetadata
Returns the runtime metadata on Manta Atlantic.
## Use Cases
- **Runtime introspection** - Discover available pallets and calls
- **Extrinsic building** - Get call and type information for private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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-manta-atlantic-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_getRuntimeVersion - Manta Atlantic RPC Method
# state_getRuntimeVersion
Returns the runtime version on Manta Atlantic.
## Use Cases
- **Version checking** - Verify runtime compatibility
- **Upgrade detection** - Monitor for runtime upgrades on private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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-manta-atlantic-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 - Manta Atlantic RPC Method
# state_getStorage
Returns a storage entry at a specific key on Manta Atlantic.
> **Why Manta Atlantic?** Build on the ZK Layer 1 on Polkadot enabling private transactions and on-chain compliance identities with zkSNARK-powered privacy, modular compliance identities, MANTA token staking hub, and end-to-end transaction privacy.
## Use Cases
- **State queries** - Read on-chain storage values
- **Account balances** - Query account data for private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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 = '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-manta-atlantic-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_queryStorageAt - Manta Atlantic RPC Method
# state_queryStorageAt
Query multiple storage keys at a specific block on Manta Atlantic.
## Use Cases
- **Batch queries** - Efficiently query multiple storage items
- **Snapshot state** - Get consistent multi-key state for private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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
---
## system_chain - Manta Atlantic RPC Method
# system_chain
Returns the chain name on Manta Atlantic.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_chain",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl https://api-manta-atlantic-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-manta-atlantic-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_health - Manta Atlantic RPC Method
# system_health
Returns the health status of the Manta Atlantic node.
## Use Cases
- **Health checks** - Monitor node availability
- **Load balancing** - Route traffic based on health for private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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-manta-atlantic-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_name - Manta Atlantic RPC Method
# system_name
Returns the node implementation name on Manta Atlantic.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_name",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl https://api-manta-atlantic-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-manta-atlantic-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_properties - Manta Atlantic RPC Method
# system_properties
Returns chain properties including token symbol and decimals on Manta Atlantic.
## Use Cases
- **Token formatting** - Get decimals and symbol for private asset transfers, zkNFTs, on-chain compliance identities, and private parachain asset swaps
- **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-manta-atlantic-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-manta-atlantic-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_version - Manta Atlantic RPC Method
# system_version
Returns the node implementation version on Manta Atlantic.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_version",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl https://api-manta-atlantic-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-manta-atlantic-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
---
## debug_traceBlock - Manta RPC Method
# debug_traceBlock
Traces all transactions in a block on Manta Pacific 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 ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
## 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-manta-pacific-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-manta-pacific-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 - Manta RPC Method
# debug_traceBlockByHash
Traces all transactions in a block on Manta Pacific 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": ["0xd40eb9063e1311e2c49869e91d4033d24e7d82620a2c305247ac4d0587757a3c", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceBlockByHash",
"params": ["0xd40eb9063e1311e2c49869e91d4033d24e7d82620a2c305247ac4d0587757a3c", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0xd40eb9063e1311e2c49869e91d4033d24e7d82620a2c305247ac4d0587757a3c';
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 - Manta RPC Method
# debug_traceBlockByNumber
Traces all transactions in a block on Manta Pacific 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-manta-pacific-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-manta-pacific-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 - Manta RPC Method
# debug_traceCall
Traces a call without creating a transaction on Manta Pacific.
:::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 ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
## 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": "0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"data": "0x70a082310000000000000000000000000Dc808adcE2099A9F62AA87D9670745AbA741746"
},
"latest",
{}
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceCall",
"params": [
{"to": "0x0Dc808adcE2099A9F62AA87D9670745AbA741746", "data": "0x70a082310000000000000000000000000Dc808adcE2099A9F62AA87D9670745AbA741746"},
"latest",
{"tracer": "callTracer"}
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY');
const trace = await provider.send('debug_traceCall', [
{ to: '0x0Dc808adcE2099A9F62AA87D9670745AbA741746', data: '0x70a082310000000000000000000000000Dc808adcE2099A9F62AA87D9670745AbA741746' },
'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 - Manta RPC Method
# debug_traceTransaction
Traces a transaction execution on Manta Pacific 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 ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
## 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": ["0xf3134f27d41373e62496990ad048f81f01f3c7a86a431c99fa05dc20835f9cbd", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceTransaction",
"params": ["0xf3134f27d41373e62496990ad048f81f01f3c7a86a431c99fa05dc20835f9cbd", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY');
const txHash = '0xf3134f27d41373e62496990ad048f81f01f3c7a86a431c99fa05dc20835f9cbd';
// 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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0xf3134f27d41373e62496990ad048f81f01f3c7a86a431c99fa05dc20835f9cbd'
# 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 - Manta RPC Method
# eth_accounts
Returns a list of addresses owned by the client on Manta Pacific.
> **Why Manta?** Build on the modular ZK L2 with Celestia DA delivering the lowest fees for 200+ dApps with first L2 on Celestia mainnet, ZK-as-a-Service via Universal Circuits, Polygon CDK integration, and modular OP Stack architecture.
## 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 ZK application developers, privacy-focused builders, and teams requiring modular 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-manta-pacific-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-manta-pacific-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-manta-pacific-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-manta-pacific-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-manta-pacific-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-manta-pacific-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 - Manta RPC Method
# eth_blockNumber
Returns the number of the most recent block on Manta Pacific.
> **Why Manta?** Build on the modular ZK L2 with Celestia DA delivering the lowest fees for 200+ dApps with first L2 on Celestia mainnet, ZK-as-a-Service via Universal Circuits, Polygon CDK integration, and modular OP Stack architecture.
## When to Use This Method
`eth_blockNumber` is fundamental for ZK application developers, privacy-focused builders, and teams requiring modular scalability:
- **Syncing Applications** — Keep your dApp in sync with the latest Manta blockchain state
- **Transaction Monitoring** — Verify confirmations by comparing block numbers
- **Event Filtering** — Set the correct block range for querying logs on ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
- **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-manta-pacific-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-manta-pacific-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('Manta block:', blockNumber);
// Using ethers.js
const provider = new JsonRpcProvider('https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY');
const blockNumber = await provider.getBlockNumber();
console.log('Manta block:', blockNumber);
```
```python
def get_block_number():
response = requests.post(
'https://api-manta-pacific-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'Manta block: {block_number}')
# Using web3.py
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY'))
print(f'Manta 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-manta-pacific-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("Manta block: %d\n", blockNumber)
}
```
## Common Use Cases
### 1. Block Confirmation Counter
Monitor transaction confirmations on Manta:
```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 Manta:
```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 Manta 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-manta-pacific-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 - Manta RPC Method
# eth_call
Executes a new message call immediately without creating a transaction on Manta Pacific. Used for reading smart contract state.
> **Why Manta?** Build on the modular ZK L2 with Celestia DA delivering the lowest fees for 200+ dApps with first L2 on Celestia mainnet, ZK-as-a-Service via Universal Circuits, Polygon CDK integration, and modular OP Stack architecture.
## 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 ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
- **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": "0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"data": "0x70a082310000000000000000000000000Dc808adcE2099A9F62AA87D9670745AbA741746"
},
"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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_call",
"params": [{
"to": "0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"data": "0x70a082310000000000000000000000000Dc808adcE2099A9F62AA87D9670745AbA741746"
}, "latest"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-manta-pacific-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-manta-pacific-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(
'0x0Dc808adcE2099A9F62AA87D9670745AbA741746',
'0x0Dc808adcE2099A9F62AA87D9670745AbA741746'
)
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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
contractAddress := common.HexToAddress("0x0Dc808adcE2099A9F62AA87D9670745AbA741746")
data := common.FromHex("0x70a082310000000000000000000000000Dc808adcE2099A9F62AA87D9670745AbA741746")
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 - Manta RPC Method
# eth_chainId
Returns the chain ID used for transaction signing on Manta Pacific.
> **Why Manta?** Build on the modular ZK L2 with Celestia DA delivering the lowest fees for 200+ dApps with first L2 on Celestia mainnet, ZK-as-a-Service via Universal Circuits, Polygon CDK integration, and modular OP Stack architecture.
## 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-manta-pacific-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-manta-pacific-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-manta-pacific-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-manta-pacific-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(Manta-pacific)
# eth_coinbase
Get coinbase address on the Manta Pacific 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-manta-pacific-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-manta-pacific-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 [Manta Pacific documentation](/docs/manta-pacific).*
---
## eth_estimateGas - Manta RPC Method
# eth_estimateGas
Estimates the gas necessary to execute a transaction on Manta Pacific.
> **Why Manta?** Build on the modular ZK L2 with Celestia DA delivering the lowest fees for 200+ dApps with first L2 on Celestia mainnet, ZK-as-a-Service via Universal Circuits, Polygon CDK integration, and modular OP Stack architecture.
## 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 ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
## 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": "0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"to": "0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_estimateGas",
"params": [{
"from": "0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"to": "0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"value": "0x1"
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-manta-pacific-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-manta-pacific-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('0x0Dc808adcE2099A9F62AA87D9670745AbA741746', 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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
toAddress := common.HexToAddress("0x0Dc808adcE2099A9F62AA87D9670745AbA741746")
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 - Manta RPC Method
# eth_feeHistory
Returns historical gas information on Manta Pacific 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 ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
## 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-manta-pacific-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-manta-pacific-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-manta-pacific-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 - Manta RPC Method
# eth_gasPrice
Returns the current gas price on Manta Pacific in wei.
> **Why Manta?** Build on the modular ZK L2 with Celestia DA delivering the lowest fees for 200+ dApps with first L2 on Celestia mainnet, ZK-as-a-Service via Universal Circuits, Polygon CDK integration, and modular OP Stack architecture.
## 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 ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
## 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-manta-pacific-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-manta-pacific-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-manta-pacific-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-manta-pacific-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 - Manta RPC Method
# eth_getBalance
Returns the balance of a given address on Manta Pacific.
> **Why Manta?** Build on the modular ZK L2 with Celestia DA delivering the lowest fees for 200+ dApps with first L2 on Celestia mainnet, ZK-as-a-Service via Universal Circuits, Polygon CDK integration, and modular OP Stack architecture.
## 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 ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
- **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": [
"0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY');
const address = '0x0Dc808adcE2099A9F62AA87D9670745AbA741746';
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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY'))
address = '0x0Dc808adcE2099A9F62AA87D9670745AbA741746'
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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
address := common.HexToAddress("0x0Dc808adcE2099A9F62AA87D9670745AbA741746")
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 - Manta RPC Method
# eth_getBlockByHash
Returns information about a block by hash on Manta Pacific.
> **Why Manta?** Build on the modular ZK L2 with Celestia DA delivering the lowest fees for 200+ dApps with first L2 on Celestia mainnet, ZK-as-a-Service via Universal Circuits, Polygon CDK integration, and modular OP Stack architecture.
## 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 ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
- **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": [
"0xd40eb9063e1311e2c49869e91d4033d24e7d82620a2c305247ac4d0587757a3c",
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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByHash",
"params": [
"0xd40eb9063e1311e2c49869e91d4033d24e7d82620a2c305247ac4d0587757a3c",
false
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0xd40eb9063e1311e2c49869e91d4033d24e7d82620a2c305247ac4d0587757a3c';
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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY'))
block_hash = '0xd40eb9063e1311e2c49869e91d4033d24e7d82620a2c305247ac4d0587757a3c'
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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
blockHash := common.HexToHash("0xd40eb9063e1311e2c49869e91d4033d24e7d82620a2c305247ac4d0587757a3c")
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 - Manta RPC Method
# eth_getBlockByNumber
Returns information about a block by block number on Manta Pacific.
> **Why Manta?** Build on the modular ZK L2 with Celestia DA delivering the lowest fees for 200+ dApps with first L2 on Celestia mainnet, ZK-as-a-Service via Universal Circuits, Polygon CDK integration, and modular OP Stack architecture.
## 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 ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
- **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": "0xd40eb9063e1311e2c49869e91d4033d24e7d82620a2c305247ac4d0587757a3c",
"parentHash": "0x...",
"timestamp": "0x64d8f6d0",
"gasUsed": "0x1234",
"gasLimit": "0x1c9c380",
"transactions": [],
"baseFeePerGas": "0x5f5e100"
}
}
```
## Code Examples
```bash
curl -X POST https://api-manta-pacific-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-manta-pacific-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-manta-pacific-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-manta-pacific-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 - Manta RPC Method
# eth_getCode
Returns the bytecode at a given address on Manta Pacific.
> **Why Manta?** Build on the modular ZK L2 with Celestia DA delivering the lowest fees for 200+ dApps with first L2 on Celestia mainnet, ZK-as-a-Service via Universal Circuits, Polygon CDK integration, and modular OP Stack architecture.
## 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 ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
## 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": [
"0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"latest"
],
"id": 1
}
```
## Returns
| Type | Description |
|------|-------------|
| `DATA` | Contract bytecode or `0x` if EOA |
## Code Examples
```bash
curl -X POST https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getCode",
"params": [
"0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY');
const address = '0x0Dc808adcE2099A9F62AA87D9670745AbA741746';
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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY'))
address = '0x0Dc808adcE2099A9F62AA87D9670745AbA741746'
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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
address := common.HexToAddress("0x0Dc808adcE2099A9F62AA87D9670745AbA741746")
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 - Manta RPC Method
# eth_getFilterChanges
Polling method for a filter on Manta Pacific, returns an array of logs since last poll.
## Use Cases
- **Event streaming** - Get new events incrementally
- **Real-time monitoring** - Track contract activity for ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
- **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-manta-pacific-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-manta-pacific-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 - Manta RPC Method
# eth_getFilterLogs
Returns an array of all logs matching filter with given ID on Manta Pacific.
## Use Cases
- **Historical queries** - Get all matching logs for a filter
- **Full event history** - Retrieve complete event data for ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
## 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-manta-pacific-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-manta-pacific-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 - Manta RPC Method
# eth_getLogs
Returns an array of all logs matching a given filter object on Manta Pacific.
> **Why Manta?** Build on the modular ZK L2 with Celestia DA delivering the lowest fees for 200+ dApps with first L2 on Celestia mainnet, ZK-as-a-Service via Universal Circuits, Polygon CDK integration, and modular OP Stack architecture.
## Use Cases
The `eth_getLogs` method is essential for:
- **Event indexing** - Track contract events for ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
- **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": "0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"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": "0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."],
"data": "0x...",
"blockNumber": "0x5BAD55",
"transactionHash": "0x...",
"logIndex": "0x0"
}]
}
```
## Code Examples
```bash
curl -X POST https://api-manta-pacific-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": "0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-manta-pacific-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(
'0x0Dc808adcE2099A9F62AA87D9670745AbA741746',
'latest',
'latest'
);
console.log('Transfer events:', events);
```
```python
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-manta-pacific-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(
'0x0Dc808adcE2099A9F62AA87D9670745AbA741746',
'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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
contractAddress := common.HexToAddress("0x0Dc808adcE2099A9F62AA87D9670745AbA741746")
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 - Manta RPC Method
# eth_getStorageAt
Returns the value from a storage position at a given address on Manta Pacific.
## Use Cases
- **Contract analysis** - Read raw storage values
- **State verification** - Verify contract state
- **Security auditing** - Analyze storage layout for ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
- **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": [
"0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"0x0",
"latest"
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getStorageAt",
"params": [
"0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"0x0",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY');
const address = '0x0Dc808adcE2099A9F62AA87D9670745AbA741746';
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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY'))
address = '0x0Dc808adcE2099A9F62AA87D9670745AbA741746'
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 - Manta RPC Method
# eth_getTransactionByHash
Returns the information about a transaction by transaction hash on Manta Pacific.
> **Why Manta?** Build on the modular ZK L2 with Celestia DA delivering the lowest fees for 200+ dApps with first L2 on Celestia mainnet, ZK-as-a-Service via Universal Circuits, Polygon CDK integration, and modular OP Stack architecture.
## 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 ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
- **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": ["0xf3134f27d41373e62496990ad048f81f01f3c7a86a431c99fa05dc20835f9cbd"],
"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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionByHash",
"params": ["0xf3134f27d41373e62496990ad048f81f01f3c7a86a431c99fa05dc20835f9cbd"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY');
const txHash = '0xf3134f27d41373e62496990ad048f81f01f3c7a86a431c99fa05dc20835f9cbd';
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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0xf3134f27d41373e62496990ad048f81f01f3c7a86a431c99fa05dc20835f9cbd'
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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0xf3134f27d41373e62496990ad048f81f01f3c7a86a431c99fa05dc20835f9cbd")
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 - Manta RPC Method
# eth_getTransactionCount
Returns the number of transactions sent from an address on Manta Pacific (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 ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
## 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": [
"0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"latest"
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [
"0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY');
const address = '0x0Dc808adcE2099A9F62AA87D9670745AbA741746';
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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY'))
address = '0x0Dc808adcE2099A9F62AA87D9670745AbA741746'
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 - Manta RPC Method
# eth_getTransactionReceipt
Returns the receipt of a transaction by transaction hash on Manta Pacific. Receipt is only available for mined transactions.
> **Why Manta?** Build on the modular ZK L2 with Celestia DA delivering the lowest fees for 200+ dApps with first L2 on Celestia mainnet, ZK-as-a-Service via Universal Circuits, Polygon CDK integration, and modular OP Stack architecture.
## 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 ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `transactionHash` | `DATA` | Yes | 32-byte transaction hash |
## Request
```json
{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0xf3134f27d41373e62496990ad048f81f01f3c7a86a431c99fa05dc20835f9cbd"],
"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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0xf3134f27d41373e62496990ad048f81f01f3c7a86a431c99fa05dc20835f9cbd"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY');
const txHash = '0xf3134f27d41373e62496990ad048f81f01f3c7a86a431c99fa05dc20835f9cbd';
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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0xf3134f27d41373e62496990ad048f81f01f3c7a86a431c99fa05dc20835f9cbd'
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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0xf3134f27d41373e62496990ad048f81f01f3c7a86a431c99fa05dc20835f9cbd")
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(Manta-pacific)
# eth_hashrate
Get node hashrate on the Manta Pacific 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-manta-pacific-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-manta-pacific-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 [Manta Pacific documentation](/docs/manta-pacific).*
---
## eth_maxPriorityFeePerGas - Manta RPC Method
# eth_maxPriorityFeePerGas
Returns the current recommended priority fee per gas on Manta Pacific 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 ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
## 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-manta-pacific-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-manta-pacific-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-manta-pacific-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(Manta-pacific)
# eth_mining
Check if node is mining on the Manta Pacific 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-manta-pacific-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-manta-pacific-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 [Manta Pacific documentation](/docs/manta-pacific).*
---
## eth_newBlockFilter - Manta RPC Method
# eth_newBlockFilter
Creates a filter on Manta Pacific 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-manta-pacific-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-manta-pacific-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 - Manta RPC Method
# eth_newFilter
Creates a filter object on Manta Pacific to notify when state changes (logs).
## Use Cases
- **Event monitoring** - Subscribe to contract events
- **Real-time updates** - Track events for ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
- **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": "0x0Dc808adcE2099A9F62AA87D9670745AbA741746",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
}],
"id": 1
}
```
## Returns
| Type | Description |
|------|-------------|
| `QUANTITY` | Filter ID |
## Code Examples
```bash
curl -X POST https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_newFilter",
"params": [{
"fromBlock": "latest",
"address": "0x0Dc808adcE2099A9F62AA87D9670745AbA741746"
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY');
// Create filter
const filterId = await provider.send('eth_newFilter', [{
fromBlock: 'latest',
address: '0x0Dc808adcE2099A9F62AA87D9670745AbA741746',
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 - Manta RPC Method
# eth_newPendingTransactionFilter
Creates a filter on Manta Pacific 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-manta-pacific-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-manta-pacific-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 ver...
# eth_protocolVersion
Get protocol version on the Manta Pacific 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-manta-pacific-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-manta-pacific-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 [Manta Pacific documentation](/docs/manta-pacific).*
---
## eth_sendRawTransaction - Manta RPC Method
# eth_sendRawTransaction
Submits a pre-signed transaction for broadcast to Manta Pacific.
> **Why Manta?** Build on the modular ZK L2 with Celestia DA delivering the lowest fees for 200+ dApps with first L2 on Celestia mainnet, ZK-as-a-Service via Universal Circuits, Polygon CDK integration, and modular OP Stack architecture.
## 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 ZK-enabled DeFi, private identity verification, and modular ZK applications via Universal Circuits
- **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-manta-pacific-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-manta-pacific-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-manta-pacific-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-manta-pacific-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("0x0Dc808adcE2099A9F62AA87D9670745AbA741746")
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...(Manta-pacific)
# eth_sendTransaction
> **Important**: Dwellir's shared Manta Pacific 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-manta-pacific-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...(Manta-pacific)
# 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-manta-pacific-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-manta-pacific-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 [Manta Pacific documentation](/docs/manta-pacific).*
---
## eth_syncing - Manta RPC Method
# eth_syncing
Returns syncing status of Manta Pacific 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-manta-pacific-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-manta-pacific-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 - Manta RPC Method
# eth_uninstallFilter
Uninstalls a filter on Manta Pacific. 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-manta-pacific-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-manta-pacific-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
---
## Manta Pacific - EVM Network Guide
# Manta Pacific - EVM Network
## Why Build on Manta Pacific?
Focus on what matters — building — while Dwellir delivers:
- High‑availability RPC with global anycast routing and low latency
- Full Ethereum JSON‑RPC coverage with tracing and debug APIs
- Consistent, high‑throughput mainnet endpoints
- Clear rate limits, observability, and an enterprise‑grade SLA
## Quick Start with Manta Pacific
Connect to Manta Pacific in seconds with Dwellir's optimized endpoints:
### Installation & Setup
```javascript
// Connect to Manta Pacific mainnet
const provider = new JsonRpcProvider(
'https://api-manta-pacific-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 Manta Pacific mainnet
const web3 = new Web3(
'https://api-manta-pacific-mainnet.n.dwellir.com/YOUR_API_KEY'
);
// Get chain ID to verify connection
const chainId = await web3.eth.getChainId();
console.log('Connected to Manta Pacific:', chainId === 169);
// Get gas price for optimal transaction pricing
const gasPrice = await web3.eth.getGasPrice();
console.log('Current gas price:', gasPrice);
```
```typescript
// Create client (without predefined chain)
const client = createPublicClient({
transport: http('https://api-manta-pacific-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
169
Mainnet
RPC Standard
Ethereum
JSON-RPC 2.0
## JSON-RPC API Reference
Manta Pacific supports the standard Ethereum JSON-RPC 2.0 API. Access common methods for blocks, transactions, logs, traces, and debugging.
## 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);
return receipt;
}
```
### 💰 Gas Optimization
Use EIP‑1559 dynamic fees for predictable pricing:
```javascript
const feeData = await provider.getFeeData();
const tx = {
to: '0x...',
value: 0n,
maxFeePerGas: feeData.maxFeePerGas,
maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
gasLimit: 21000n,
};
```
### 🔍 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; // Manta Pacific 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 Manta PacificProvider {
static instance = null;
static getInstance() {
if (!this.instance) {
this.instance = new JsonRpcProvider(
'https://api-manta-pacific-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"
Always check the account balance against the estimated gas cost:
```javascript
const balance = await provider.getBalance(address);
const gas = await provider.estimateGas(tx);
const maxCost = gas * (tx.maxFeePerGas ?? 0n) + (tx.value ?? 0n);
if (balance < maxCost) throw new Error('Insufficient funds');
```
### Error: "Transaction underpriced"
Manta Pacific 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 Manta Pacific L2 requires minimal changes:
```javascript
// Before (Ethereum)
const provider = new JsonRpcProvider('https://eth-rpc.example.com');
// After (Manta Pacific)
const provider = new JsonRpcProvider(
'https://api-manta-pacific-mainnet.n.dwellir.com/YOUR_API_KEY'
);
// ✅ Smart contracts work identically
// ✅ Same tooling and libraries
// ⚠️ Different chain ID (169)
// ⚠️ Separate block numbers
```
## Resources & Tools
### Official Resources
- Official docs, explorer, and tooling: please refer to the Manta Pacific official channels.
### Need Help?
- 📧 **Email**: support@dwellir.com
- 📚 **Docs**: You're here!
- 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com)
---
*Start building on Manta Pacific with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## net_listening - Manta RPC Method
# net_listening
Returns `true` if client is actively listening for network connections on Manta Pacific.
## 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-manta-pacific-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-manta-pacific-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 - Manta RPC Method
# net_peerCount
Returns number of peers currently connected to Manta Pacific 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-manta-pacific-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-manta-pacific-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 - Manta RPC Method
# net_version
Returns the current network ID on Manta Pacific.
## 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-manta-pacific-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-manta-pacific-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 - Manta RPC Method
# web3_clientVersion
Returns the current client version on Manta Pacific.
## 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-manta-pacific-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-manta-pacific-archive.n.dwellir.com/YOUR_API_KEY');
const version = await provider.send('web3_clientVersion', []);
console.log('Client version:', version);
```
---
## web3_sha3 - Manta RPC Method
# web3_sha3
Returns Keccak-256 (not standard SHA3-256) of the given data on Manta Pacific.
## 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-manta-pacific-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-manta-pacific-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 - Mantle RPC Method
# debug_traceBlock
Traces all transactions in a block on Mantle 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 liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
## 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-mantle-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-mantle-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 - Mantle RPC Method
# debug_traceBlockByHash
Traces all transactions in a block on Mantle 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": ["0x731df9ec5eb8000dc29641dfbebb0efef7660fff0b55f64e402eec934af2c538", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceBlockByHash",
"params": ["0x731df9ec5eb8000dc29641dfbebb0efef7660fff0b55f64e402eec934af2c538", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0x731df9ec5eb8000dc29641dfbebb0efef7660fff0b55f64e402eec934af2c538';
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 - Mantle RPC Method
# debug_traceBlockByNumber
Traces all transactions in a block on Mantle 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-mantle-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-mantle-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 - Mantle RPC Method
# debug_traceCall
Traces a call without creating a transaction on Mantle.
:::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 liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
## 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": "0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"data": "0x70a0823100000000000000000000000078c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8"
},
"latest",
{}
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceCall",
"params": [
{"to": "0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8", "data": "0x70a0823100000000000000000000000078c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8"},
"latest",
{"tracer": "callTracer"}
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY');
const trace = await provider.send('debug_traceCall', [
{ to: '0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8', data: '0x70a0823100000000000000000000000078c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8' },
'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 - Mantle RPC Method
# debug_traceTransaction
Traces a transaction execution on Mantle 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 liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
## 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": ["0x01fec3bc45d186d1bffc3ed7e7fd88bd8408f5b4c68a86a83c54c60846589b06", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceTransaction",
"params": ["0x01fec3bc45d186d1bffc3ed7e7fd88bd8408f5b4c68a86a83c54c60846589b06", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY');
const txHash = '0x01fec3bc45d186d1bffc3ed7e7fd88bd8408f5b4c68a86a83c54c60846589b06';
// 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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0x01fec3bc45d186d1bffc3ed7e7fd88bd8408f5b4c68a86a83c54c60846589b06'
# 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 - Mantle RPC Method
# eth_accounts
Returns a list of addresses owned by the client on Mantle.
> **Why Mantle?** Build on the world's largest ZK rollup by TVL with $2.5B+ secured and deep Bybit integration with near-instant ZK finality via OP Succinct, $6.2B treasury backing, mETH liquid staking, and 25% Bybit trading fee discounts.
## 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, liquid staking builders, and teams seeking institutional exchange integration 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-mantle-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-mantle-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-mantle-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-mantle-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-mantle-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-mantle-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 - Mantle RPC Method
# eth_blockNumber
Returns the number of the most recent block on Mantle.
> **Why Mantle?** Build on the world's largest ZK rollup by TVL with $2.5B+ secured and deep Bybit integration with near-instant ZK finality via OP Succinct, $6.2B treasury backing, mETH liquid staking, and 25% Bybit trading fee discounts.
## When to Use This Method
`eth_blockNumber` is fundamental for DeFi developers, liquid staking builders, and teams seeking institutional exchange integration:
- **Syncing Applications** — Keep your dApp in sync with the latest Mantle blockchain state
- **Transaction Monitoring** — Verify confirmations by comparing block numbers
- **Event Filtering** — Set the correct block range for querying logs on liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
- **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-mantle-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-mantle-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('Mantle block:', blockNumber);
// Using ethers.js
const provider = new JsonRpcProvider('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockNumber = await provider.getBlockNumber();
console.log('Mantle block:', blockNumber);
```
```python
def get_block_number():
response = requests.post(
'https://api-mantle-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'Mantle block: {block_number}')
# Using web3.py
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY'))
print(f'Mantle 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-mantle-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("Mantle block: %d\n", blockNumber)
}
```
## Common Use Cases
### 1. Block Confirmation Counter
Monitor transaction confirmations on Mantle:
```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 Mantle:
```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 Mantle 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-mantle-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 - Mantle RPC Method
# eth_call
Executes a new message call immediately without creating a transaction on Mantle. Used for reading smart contract state.
> **Why Mantle?** Build on the world's largest ZK rollup by TVL with $2.5B+ secured and deep Bybit integration with near-instant ZK finality via OP Succinct, $6.2B treasury backing, mETH liquid staking, and 25% Bybit trading fee discounts.
## 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 liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
- **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": "0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"data": "0x70a0823100000000000000000000000078c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8"
},
"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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_call",
"params": [{
"to": "0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"data": "0x70a0823100000000000000000000000078c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8"
}, "latest"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-mantle-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-mantle-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(
'0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8',
'0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8'
)
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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
contractAddress := common.HexToAddress("0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8")
data := common.FromHex("0x70a0823100000000000000000000000078c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8")
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 - Mantle RPC Method
# eth_chainId
Returns the chain ID used for transaction signing on Mantle.
> **Why Mantle?** Build on the world's largest ZK rollup by TVL with $2.5B+ secured and deep Bybit integration with near-instant ZK finality via OP Succinct, $6.2B treasury backing, mETH liquid staking, and 25% Bybit trading fee discounts.
## 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-mantle-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-mantle-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-mantle-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-mantle-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(Mantle)
# eth_coinbase
Get coinbase address on the Mantle 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-mantle-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-mantle-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 [Mantle documentation](/docs/mantle).*
---
## eth_estimateGas - Mantle RPC Method
# eth_estimateGas
Estimates the gas necessary to execute a transaction on Mantle.
> **Why Mantle?** Build on the world's largest ZK rollup by TVL with $2.5B+ secured and deep Bybit integration with near-instant ZK finality via OP Succinct, $6.2B treasury backing, mETH liquid staking, and 25% Bybit trading fee discounts.
## 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 liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
## 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": "0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"to": "0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_estimateGas",
"params": [{
"from": "0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"to": "0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"value": "0x1"
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-mantle-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-mantle-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('0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8', 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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
toAddress := common.HexToAddress("0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8")
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(Mantle)
# eth_estimateL1Fee
Estimate L1 data posting fee on the Mantle network. This method helps calculate the additional cost of posting transaction data to Ethereum L1 via EigenDA as part of Mantle's modular L2 architecture.
## Overview
Mantle's modular L2 is an optimistic rollup that periodically submits batched transaction data to Ethereum L1 through EigenDA for data availability. While most transaction execution happens on L2 with low gas costs paid in MNT, there's an additional fee component for the L1 data availability costs.
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `transaction` | Object | Yes | Transaction object to estimate L1 fee for |
### Transaction Object
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `from` | Address | No | Sender address |
| `to` | Address | No | Recipient address |
| `gas` | Quantity | No | Gas limit |
| `gasPrice` | Quantity | No | Gas price in wei |
| `value` | Quantity | No | Value to transfer in wei |
| `data` | Data | No | Transaction data |
## Returns
| Type | Description |
|------|-------------|
| `QUANTITY` | Estimated L1 fee in wei |
## Implementation Example
```bash
curl -X POST https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY \\
-H "Content-Type: application/json" \\
-d '{
"jsonrpc": "2.0",
"method": "eth_estimateL1Fee",
"params": [
{
"from": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5",
"to": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
"gas": "0x5208",
"gasPrice": "0x3b9aca00",
"value": "0x1bc16d674ec80000",
"data": "0x"
}
],
"id": 1
}'
```
```javascript
const response = await fetch('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_estimateL1Fee',
params: [
{
from: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5',
to: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
gas: '0x5208',
gasPrice: '0x3b9aca00',
value: '0x1bc16d674ec80000',
data: '0x'
}
],
id: 1
})
});
const data = await response.json();
console.log('L1 Fee:', data.result);
// Advanced L1 fee estimation with transaction cost breakdown
class MantleFeeEstimator {
constructor(rpcUrl) {
this.rpcUrl = rpcUrl;
}
async estimateL1Fee(transaction) {
const response = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_estimateL1Fee',
params: [transaction],
id: 1
})
});
const data = await response.json();
if (data.error) {
throw new Error(`RPC Error: ${data.error.message}`);
}
return parseInt(data.result, 16);
}
async getFullFeeBreakdown(transaction) {
try {
// Estimate L2 gas cost
const l2GasResponse = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_estimateGas',
params: [transaction],
id: 1
})
});
const l2GasData = await l2GasResponse.json();
const l2GasEstimate = parseInt(l2GasData.result, 16);
// Get current gas price
const gasPriceResponse = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_gasPrice',
params: [],
id: 1
})
});
const gasPriceData = await gasPriceResponse.json();
const gasPrice = parseInt(gasPriceData.result, 16);
// Estimate L1 fee
const l1Fee = await this.estimateL1Fee(transaction);
// Calculate L2 execution cost (paid in MNT)
const l2ExecutionCost = l2GasEstimate * gasPrice;
return {
l1Fee: l1Fee,
l2ExecutionCost: l2ExecutionCost,
totalEstimatedCost: l1Fee + l2ExecutionCost,
gasEstimate: l2GasEstimate,
gasPrice: gasPrice,
breakdown: {
l1FeePercentage: ((l1Fee / (l1Fee + l2ExecutionCost)) * 100).toFixed(2),
l2FeePercentage: ((l2ExecutionCost / (l1Fee + l2ExecutionCost)) * 100).toFixed(2)
}
};
} catch (error) {
throw new Error(`Failed to get fee breakdown: ${error.message}`);
}
}
async compareFeesByDataSize(baseTransaction, dataSizes) {
const results = [];
for (const size of dataSizes) {
// Generate test data of specified size
const testData = '0x' + '00'.repeat(size);
const testTransaction = {
...baseTransaction,
data: testData
};
try {
const breakdown = await this.getFullFeeBreakdown(testTransaction);
results.push({
dataSize: size,
dataSizeKB: (size / 1024).toFixed(2),
l1Fee: breakdown.l1Fee,
l2ExecutionCost: breakdown.l2ExecutionCost,
totalCost: breakdown.totalEstimatedCost,
l1FeePerByte: breakdown.l1Fee / size,
costIncrease: size === dataSizes[0] ? 0 :
((breakdown.totalEstimatedCost - results[0].totalCost) / results[0].totalCost * 100).toFixed(2)
});
} catch (error) {
results.push({
dataSize: size,
error: error.message
});
}
}
return results;
}
async optimizeTransactionCost(transaction) {
const recommendations = [];
// Get baseline cost
const baseline = await this.getFullFeeBreakdown(transaction);
// Check if transaction has unnecessary data
if (transaction.data && transaction.data.length > 2) {
// Estimate with minimal data
const minimalTx = { ...transaction, data: '0x' };
const minimal = await this.getFullFeeBreakdown(minimalTx);
const dataCostSavings = baseline.l1Fee - minimal.l1Fee;
if (dataCostSavings > 0) {
recommendations.push({
type: 'data_optimization',
description: 'Consider reducing transaction data size',
potentialSavings: dataCostSavings,
savingsPercentage: ((dataCostSavings / baseline.totalEstimatedCost) * 100).toFixed(2)
});
}
}
// Check gas optimization
if (baseline.gasEstimate > 100000) {
recommendations.push({
type: 'gas_optimization',
description: 'High gas usage detected - consider optimizing contract calls',
currentGas: baseline.gasEstimate,
suggestion: 'Review contract logic for gas efficiency'
});
}
// Check if L1 fees dominate
if (parseFloat(baseline.breakdown.l1FeePercentage) > 70) {
recommendations.push({
type: 'l1_fee_dominance',
description: 'L1 fees represent majority of transaction cost',
l1Percentage: baseline.breakdown.l1FeePercentage,
suggestion: 'Consider batching transactions or reducing data payload'
});
}
return {
baseline: baseline,
recommendations: recommendations,
optimizationPotential: recommendations.length > 0
};
}
}
// Usage examples
const feeEstimator = new MantleFeeEstimator('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY');
// Basic L1 fee estimation
const l1Fee = await feeEstimator.estimateL1Fee({
from: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5',
to: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
value: '0x1bc16d674ec80000',
data: '0x'
});
console.log(`L1 Fee: ${l1Fee} wei`);
// Full fee breakdown
const breakdown = await feeEstimator.getFullFeeBreakdown({
from: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5',
to: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
value: '0x1bc16d674ec80000',
data: '0xa9059cbb000000000000000000000000recipient000000000000000000000000'
});
console.log('Fee Breakdown:', breakdown);
// Compare fees by data size
const dataSizeComparison = await feeEstimator.compareFeesByDataSize(
{
from: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5',
to: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913'
},
[0, 100, 500, 1000, 5000] // bytes
);
console.log('Data Size Impact:', dataSizeComparison);
// Optimization suggestions
const optimization = await feeEstimator.optimizeTransactionCost({
from: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5',
to: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
data: '0xa9059cbb' + '0'.repeat(1000) // Large data payload
});
console.log('Optimization Analysis:', optimization);
```
```python
from typing import Dict, List, Any, Optional
class MantleFeeEstimator:
"""Estimate L1 fees and analyze transaction costs on Mantle modular L2"""
def __init__(self, rpc_url: str):
self.rpc_url = rpc_url
def estimate_l1_fee(self, transaction: Dict[str, Any]) -> int:
"""Estimate L1 data posting fee for a transaction"""
payload = {
"jsonrpc": "2.0",
"method": "eth_estimateL1Fee",
"params": [transaction],
"id": 1
}
response = requests.post(self.rpc_url, json=payload)
data = response.json()
if 'error' in data:
raise Exception(f"RPC Error: {data['error']['message']}")
return int(data['result'], 16)
def _make_rpc_call(self, method: str, params: List = None) -> Any:
"""Helper method for RPC calls"""
payload = {
"jsonrpc": "2.0",
"method": method,
"params": params or [],
"id": 1
}
response = requests.post(self.rpc_url, json=payload)
data = response.json()
if 'error' in data:
raise Exception(f"RPC Error: {data['error']['message']}")
return data['result']
def get_full_fee_breakdown(self, transaction: Dict[str, Any]) -> Dict[str, Any]:
"""Get complete fee breakdown including L1 and L2 costs"""
# Estimate L2 gas
l2_gas_estimate = int(self._make_rpc_call('eth_estimateGas', [transaction]), 16)
# Get current gas price
gas_price = int(self._make_rpc_call('eth_gasPrice'), 16)
# Estimate L1 fee
l1_fee = self.estimate_l1_fee(transaction)
# Calculate L2 execution cost (paid in MNT)
l2_execution_cost = l2_gas_estimate * gas_price
total_cost = l1_fee + l2_execution_cost
return {
'l1_fee': l1_fee,
'l2_execution_cost': l2_execution_cost,
'total_estimated_cost': total_cost,
'gas_estimate': l2_gas_estimate,
'gas_price': gas_price,
'breakdown': {
'l1_fee_percentage': round((l1_fee / total_cost) * 100, 2) if total_cost > 0 else 0,
'l2_fee_percentage': round((l2_execution_cost / total_cost) * 100, 2) if total_cost > 0 else 0
}
}
def analyze_data_cost_impact(
self,
base_transaction: Dict[str, Any],
data_payloads: List[str]
) -> List[Dict[str, Any]]:
"""Analyze how different data payloads affect L1 fees"""
results = []
for i, data in enumerate(data_payloads):
test_tx = {**base_transaction, 'data': data}
try:
breakdown = self.get_full_fee_breakdown(test_tx)
data_size = (len(data) - 2) // 2 if data.startswith('0x') else len(data) // 2
result = {
'data_payload': data[:20] + '...' if len(data) > 20 else data,
'data_size_bytes': data_size,
'l1_fee': breakdown['l1_fee'],
'l2_execution_cost': breakdown['l2_execution_cost'],
'total_cost': breakdown['total_estimated_cost'],
'l1_fee_per_byte': breakdown['l1_fee'] / data_size if data_size > 0 else 0
}
# Calculate cost increase relative to first payload
if i > 0 and results:
base_cost = results[0]['total_cost']
result['cost_increase_pct'] = round(
((result['total_cost'] - base_cost) / base_cost) * 100, 2
) if base_cost > 0 else 0
else:
result['cost_increase_pct'] = 0
results.append(result)
except Exception as e:
results.append({
'data_payload': data[:20] + '...' if len(data) > 20 else data,
'error': str(e)
})
return results
def suggest_optimizations(self, transaction: Dict[str, Any]) -> Dict[str, Any]:
"""Analyze transaction and suggest cost optimizations"""
baseline = self.get_full_fee_breakdown(transaction)
suggestions = []
# Check data optimization potential
if transaction.get('data') and len(transaction['data']) > 2:
minimal_tx = {**transaction, 'data': '0x'}
minimal_cost = self.get_full_fee_breakdown(minimal_tx)
data_cost_impact = baseline['l1_fee'] - minimal_cost['l1_fee']
if data_cost_impact > 0:
suggestions.append({
'type': 'data_optimization',
'description': 'Transaction data contributes significantly to L1 costs',
'potential_savings_wei': data_cost_impact,
'potential_savings_pct': round(
(data_cost_impact / baseline['total_estimated_cost']) * 100, 2
),
'recommendation': 'Consider compressing data or using events for large payloads'
})
# Check gas efficiency
if baseline['gas_estimate'] > 200000:
suggestions.append({
'type': 'gas_optimization',
'description': f'High gas usage detected: {baseline["gas_estimate"]:,} gas',
'recommendation': 'Review contract logic for gas efficiency improvements'
})
# Check fee composition
if baseline['breakdown']['l1_fee_percentage'] > 80:
suggestions.append({
'type': 'l1_fee_dominance',
'description': f'L1 fees dominate total cost ({baseline["breakdown"]["l1_fee_percentage"]}%)',
'recommendation': 'Consider batching multiple operations into single transaction'
})
return {
'baseline_cost': baseline,
'optimization_suggestions': suggestions,
'total_potential_savings': sum(
s.get('potential_savings_wei', 0) for s in suggestions
)
}
def compare_transaction_efficiency(
self,
transactions: List[Dict[str, Any]],
labels: List[str] = None
) -> Dict[str, Any]:
"""Compare efficiency of different transaction approaches"""
if labels is None:
labels = [f"Transaction {i+1}" for i in range(len(transactions))]
comparisons = []
for i, (tx, label) in enumerate(zip(transactions, labels)):
try:
breakdown = self.get_full_fee_breakdown(tx)
comparisons.append({
'label': label,
'total_cost': breakdown['total_estimated_cost'],
'l1_fee': breakdown['l1_fee'],
'l2_cost': breakdown['l2_execution_cost'],
'gas_estimate': breakdown['gas_estimate'],
'efficiency_score': breakdown['gas_estimate'] / breakdown['total_estimated_cost']
})
except Exception as e:
comparisons.append({
'label': label,
'error': str(e)
})
# Find most efficient
valid_comparisons = [c for c in comparisons if 'error' not in c]
if valid_comparisons:
most_efficient = min(valid_comparisons, key=lambda x: x['total_cost'])
least_efficient = max(valid_comparisons, key=lambda x: x['total_cost'])
return {
'comparisons': comparisons,
'most_efficient': most_efficient,
'least_efficient': least_efficient,
'cost_difference': least_efficient['total_cost'] - most_efficient['total_cost'],
'efficiency_improvement_pct': round(
((least_efficient['total_cost'] - most_efficient['total_cost']) /
least_efficient['total_cost']) * 100, 2
)
}
return {'comparisons': comparisons}
# Usage examples
fee_estimator = MantleFeeEstimator('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY')
# Basic L1 fee estimation
transaction = {
'from': '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5',
'to': '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
'value': '0x1bc16d674ec80000',
'data': '0xa9059cbb000000000000000000000000recipient000000000000000000000000'
}
l1_fee = fee_estimator.estimate_l1_fee(transaction)
print(f"L1 Fee: {l1_fee:,} wei")
# Full breakdown
breakdown = fee_estimator.get_full_fee_breakdown(transaction)
print(f"Total Cost: {breakdown['total_estimated_cost']:,} wei")
print(f"L1 Fee: {breakdown['l1_fee']:,} wei ({breakdown['breakdown']['l1_fee_percentage']}%)")
print(f"L2 Cost: {breakdown['l2_execution_cost']:,} wei ({breakdown['breakdown']['l2_fee_percentage']}%)")
# Data impact analysis
data_payloads = [
'0x', # Empty
'0xa9059cbb' + '00' * 32, # Basic ERC20 transfer
'0xa9059cbb' + '00' * 100, # Larger payload
'0xa9059cbb' + '00' * 500 # Very large payload
]
data_analysis = fee_estimator.analyze_data_cost_impact(
{'from': '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb5', 'to': '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913'},
data_payloads
)
print("\nData Size Impact Analysis:")
for result in data_analysis:
if 'error' not in result:
print(f" {result['data_size_bytes']} bytes: {result['total_cost']:,} wei "
f"(+{result['cost_increase_pct']}%)")
# Optimization suggestions
optimization = fee_estimator.suggest_optimizations(transaction)
print(f"\nOptimization Suggestions:")
for suggestion in optimization['optimization_suggestions']:
print(f" - {suggestion['description']}")
print(f" {suggestion['recommendation']}")
```
## Response Example
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x1c6bf526340"
}
```
## Understanding L1 Fees on Mantle
### Fee Components
1. **L2 Execution Fee**: Standard gas cost for transaction execution on Mantle (paid in MNT)
2. **L1 Data Fee**: Cost of posting transaction data to Ethereum L1 via EigenDA for data availability
### Data Size Impact
L1 fees scale with transaction data size:
- Simple transfers: Minimal L1 fee
- Contract interactions: Moderate L1 fee based on calldata
- Large data payloads: Significant L1 fee component
### Cost Optimization Strategies
1. **Minimize Data**: Reduce unnecessary data in transactions
2. **Batch Operations**: Combine multiple operations into single transaction
3. **Use Events**: Emit events instead of storing large data on-chain
4. **Optimize Encoding**: Use efficient data encoding methods
5. **Leverage EigenDA**: Benefit from efficient data availability
## Common Use Cases
### 1. Transaction Cost Planning
```javascript
// Plan transaction costs before execution
async function planTransactionCosts(transactions) {
const feeEstimator = new MantleFeeEstimator(rpcUrl);
const plans = [];
for (const tx of transactions) {
const breakdown = await feeEstimator.getFullFeeBreakdown(tx);
plans.push({
transaction: tx,
estimatedCost: breakdown.totalEstimatedCost,
l1FeeRatio: breakdown.breakdown.l1FeePercentage,
recommendation: breakdown.breakdown.l1FeePercentage > 70 ?
'Consider batching or data optimization' : 'Cost efficient'
});
}
return plans.sort((a, b) => a.estimatedCost - b.estimatedCost);
}
```
### 2. Data Optimization Analysis
```python
def optimize_contract_call_data(base_transaction, data_variations):
"""Find most cost-effective data encoding"""
fee_estimator = MantleFeeEstimator(rpc_url)
results = []
for name, data in data_variations.items():
tx = {**base_transaction, 'data': data}
breakdown = fee_estimator.get_full_fee_breakdown(tx)
results.append({
'encoding': name,
'data_size': len(data) // 2 - 1, # Hex bytes
'total_cost': breakdown['total_estimated_cost'],
'l1_fee': breakdown['l1_fee'],
'efficiency': breakdown['l1_fee'] / (len(data) // 2 - 1)
})
# Sort by total cost
return sorted(results, key=lambda x: x['total_cost'])
```
## Related Methods
- [`eth_estimateGas`](/mantle/eth_estimateGas) - Estimate L2 execution gas
- [`eth_gasPrice`](/mantle/eth_gasPrice) - Get current L2 gas price
- [`eth_feeHistory`](/mantle/eth_feeHistory) - Historical fee data
---
*Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Mantle documentation](/docs/mantle).*
---
## eth_feeHistory - Mantle RPC Method
# eth_feeHistory
Returns historical gas information on Mantle 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 liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
## 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-mantle-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-mantle-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-mantle-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 - Mantle RPC Method
# eth_gasPrice
Returns the current gas price on Mantle in wei.
> **Why Mantle?** Build on the world's largest ZK rollup by TVL with $2.5B+ secured and deep Bybit integration with near-instant ZK finality via OP Succinct, $6.2B treasury backing, mETH liquid staking, and 25% Bybit trading fee discounts.
## 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 liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
## 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-mantle-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-mantle-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-mantle-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-mantle-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 - Mantle RPC Method
# eth_getBalance
Returns the balance of a given address on Mantle.
> **Why Mantle?** Build on the world's largest ZK rollup by TVL with $2.5B+ secured and deep Bybit integration with near-instant ZK finality via OP Succinct, $6.2B treasury backing, mETH liquid staking, and 25% Bybit trading fee discounts.
## 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 liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
- **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": [
"0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY');
const address = '0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8';
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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY'))
address = '0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8'
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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
address := common.HexToAddress("0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8")
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 - Mantle RPC Method
# eth_getBlockByHash
Returns information about a block by hash on Mantle.
> **Why Mantle?** Build on the world's largest ZK rollup by TVL with $2.5B+ secured and deep Bybit integration with near-instant ZK finality via OP Succinct, $6.2B treasury backing, mETH liquid staking, and 25% Bybit trading fee discounts.
## 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 liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
- **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": [
"0x731df9ec5eb8000dc29641dfbebb0efef7660fff0b55f64e402eec934af2c538",
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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByHash",
"params": [
"0x731df9ec5eb8000dc29641dfbebb0efef7660fff0b55f64e402eec934af2c538",
false
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0x731df9ec5eb8000dc29641dfbebb0efef7660fff0b55f64e402eec934af2c538';
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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY'))
block_hash = '0x731df9ec5eb8000dc29641dfbebb0efef7660fff0b55f64e402eec934af2c538'
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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
blockHash := common.HexToHash("0x731df9ec5eb8000dc29641dfbebb0efef7660fff0b55f64e402eec934af2c538")
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 - Mantle RPC Method
# eth_getBlockByNumber
Returns information about a block by block number on Mantle.
> **Why Mantle?** Build on the world's largest ZK rollup by TVL with $2.5B+ secured and deep Bybit integration with near-instant ZK finality via OP Succinct, $6.2B treasury backing, mETH liquid staking, and 25% Bybit trading fee discounts.
## 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 liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
- **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": "0x731df9ec5eb8000dc29641dfbebb0efef7660fff0b55f64e402eec934af2c538",
"parentHash": "0x...",
"timestamp": "0x64d8f6d0",
"gasUsed": "0x1234",
"gasLimit": "0x1c9c380",
"transactions": [],
"baseFeePerGas": "0x5f5e100"
}
}
```
## Code Examples
```bash
curl -X POST https://api-mantle-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-mantle-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-mantle-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-mantle-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 - Mantle RPC Method
# eth_getCode
Returns the bytecode at a given address on Mantle.
> **Why Mantle?** Build on the world's largest ZK rollup by TVL with $2.5B+ secured and deep Bybit integration with near-instant ZK finality via OP Succinct, $6.2B treasury backing, mETH liquid staking, and 25% Bybit trading fee discounts.
## 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 liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
## 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": [
"0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"latest"
],
"id": 1
}
```
## Returns
| Type | Description |
|------|-------------|
| `DATA` | Contract bytecode or `0x` if EOA |
## Code Examples
```bash
curl -X POST https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getCode",
"params": [
"0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY');
const address = '0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8';
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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY'))
address = '0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8'
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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
address := common.HexToAddress("0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8")
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 - Mantle RPC Method
# eth_getFilterChanges
Polling method for a filter on Mantle, returns an array of logs since last poll.
## Use Cases
- **Event streaming** - Get new events incrementally
- **Real-time monitoring** - Track contract activity for liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
- **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-mantle-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-mantle-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 - Mantle RPC Method
# eth_getFilterLogs
Returns an array of all logs matching filter with given ID on Mantle.
## Use Cases
- **Historical queries** - Get all matching logs for a filter
- **Full event history** - Retrieve complete event data for liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
## 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-mantle-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-mantle-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 - Mantle RPC Method
# eth_getLogs
Returns an array of all logs matching a given filter object on Mantle.
> **Why Mantle?** Build on the world's largest ZK rollup by TVL with $2.5B+ secured and deep Bybit integration with near-instant ZK finality via OP Succinct, $6.2B treasury backing, mETH liquid staking, and 25% Bybit trading fee discounts.
## Use Cases
The `eth_getLogs` method is essential for:
- **Event indexing** - Track contract events for liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
- **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": "0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"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": "0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."],
"data": "0x...",
"blockNumber": "0x5BAD55",
"transactionHash": "0x...",
"logIndex": "0x0"
}]
}
```
## Code Examples
```bash
curl -X POST https://api-mantle-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": "0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-mantle-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(
'0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8',
'latest',
'latest'
);
console.log('Transfer events:', events);
```
```python
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-mantle-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(
'0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8',
'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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
contractAddress := common.HexToAddress("0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8")
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 - Mantle RPC Method
# eth_getStorageAt
Returns the value from a storage position at a given address on Mantle.
## Use Cases
- **Contract analysis** - Read raw storage values
- **State verification** - Verify contract state
- **Security auditing** - Analyze storage layout for liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
- **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": [
"0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"0x0",
"latest"
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getStorageAt",
"params": [
"0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"0x0",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY');
const address = '0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8';
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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY'))
address = '0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8'
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 - Mantle RPC Method
# eth_getTransactionByHash
Returns the information about a transaction by transaction hash on Mantle.
> **Why Mantle?** Build on the world's largest ZK rollup by TVL with $2.5B+ secured and deep Bybit integration with near-instant ZK finality via OP Succinct, $6.2B treasury backing, mETH liquid staking, and 25% Bybit trading fee discounts.
## 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 liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
- **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": ["0x01fec3bc45d186d1bffc3ed7e7fd88bd8408f5b4c68a86a83c54c60846589b06"],
"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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionByHash",
"params": ["0x01fec3bc45d186d1bffc3ed7e7fd88bd8408f5b4c68a86a83c54c60846589b06"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY');
const txHash = '0x01fec3bc45d186d1bffc3ed7e7fd88bd8408f5b4c68a86a83c54c60846589b06';
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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0x01fec3bc45d186d1bffc3ed7e7fd88bd8408f5b4c68a86a83c54c60846589b06'
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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0x01fec3bc45d186d1bffc3ed7e7fd88bd8408f5b4c68a86a83c54c60846589b06")
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 - Mantle RPC Method
# eth_getTransactionCount
Returns the number of transactions sent from an address on Mantle (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 liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
## 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": [
"0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"latest"
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [
"0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY');
const address = '0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8';
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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY'))
address = '0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8'
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 - Mantle RPC Method
# eth_getTransactionReceipt
Returns the receipt of a transaction by transaction hash on Mantle. Receipt is only available for mined transactions.
> **Why Mantle?** Build on the world's largest ZK rollup by TVL with $2.5B+ secured and deep Bybit integration with near-instant ZK finality via OP Succinct, $6.2B treasury backing, mETH liquid staking, and 25% Bybit trading fee discounts.
## 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 liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `transactionHash` | `DATA` | Yes | 32-byte transaction hash |
## Request
```json
{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0x01fec3bc45d186d1bffc3ed7e7fd88bd8408f5b4c68a86a83c54c60846589b06"],
"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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0x01fec3bc45d186d1bffc3ed7e7fd88bd8408f5b4c68a86a83c54c60846589b06"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY');
const txHash = '0x01fec3bc45d186d1bffc3ed7e7fd88bd8408f5b4c68a86a83c54c60846589b06';
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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0x01fec3bc45d186d1bffc3ed7e7fd88bd8408f5b4c68a86a83c54c60846589b06'
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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0x01fec3bc45d186d1bffc3ed7e7fd88bd8408f5b4c68a86a83c54c60846589b06")
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(Mantle)
# eth_hashrate
Get node hashrate on the Mantle Network. Always returns 0x0 since Mantle uses optimistic rollup consensus instead of proof-of-work mining.
## Parameters
None
## Returns
String - Always "0x0" as Mantle Network does not use proof-of-work mining.
## Implementation Example
```bash
curl -X POST https://api-mantle-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-mantle-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); // "0x0"
```
## Response Example
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": "0x0"
}
```
---
*Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Mantle documentation](/docs/mantle).*
---
## eth_maxPriorityFeePerGas - Mantle RPC Method
# eth_maxPriorityFeePerGas
Returns the current recommended priority fee per gas on Mantle 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 liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
## 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-mantle-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-mantle-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-mantle-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 mining status(Mantle)
# eth_mining
Check mining status on the Mantle Network. Always returns false since Mantle uses optimistic rollup consensus instead of proof-of-work mining.
## Parameters
None
## Returns
Boolean - Always false as Mantle Network does not use proof-of-work mining.
## Implementation Example
```bash
curl -X POST https://api-mantle-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-mantle-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); // false
```
## Response Example
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": false
}
```
---
*Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Mantle documentation](/docs/mantle).*
---
## eth_newBlockFilter - Mantle RPC Method
# eth_newBlockFilter
Creates a filter on Mantle 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-mantle-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-mantle-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 - Mantle RPC Method
# eth_newFilter
Creates a filter object on Mantle to notify when state changes (logs).
## Use Cases
- **Event monitoring** - Subscribe to contract events
- **Real-time updates** - Track events for liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
- **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": "0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
}],
"id": 1
}
```
## Returns
| Type | Description |
|------|-------------|
| `QUANTITY` | Filter ID |
## Code Examples
```bash
curl -X POST https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_newFilter",
"params": [{
"fromBlock": "latest",
"address": "0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8"
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY');
// Create filter
const filterId = await provider.send('eth_newFilter', [{
fromBlock: 'latest',
address: '0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8',
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 - Mantle RPC Method
# eth_newPendingTransactionFilter
Creates a filter on Mantle 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-mantle-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-mantle-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(Mantle)
# eth_protocolVersion
Get protocol version on the Mantle 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-mantle-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-mantle-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 [Mantle documentation](/docs/mantle).*
---
## eth_sendRawTransaction - Mantle RPC Method
# eth_sendRawTransaction
Submits a pre-signed transaction for broadcast to Mantle.
> **Why Mantle?** Build on the world's largest ZK rollup by TVL with $2.5B+ secured and deep Bybit integration with near-instant ZK finality via OP Succinct, $6.2B treasury backing, mETH liquid staking, and 25% Bybit trading fee discounts.
## 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 liquid staking (mETH $1.87B TVL), institutional DeFi via Bybit, and yield optimization strategies
- **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-mantle-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-mantle-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-mantle-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-mantle-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("0x78c1b0C915c4FAA5FffA6CAbf0219DA63d7f4cb8")
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(Mantle)
# eth_sendTransaction
> **Important**: Dwellir's shared Mantle 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`](/mantle/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`](/mantle/eth_sendRawTransaction).
## Example response from the shared endpoint
```bash
curl -s -X POST https://api-mantle-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`](/mantle/eth_sendRawTransaction) guide.
---
## eth_signTransaction - Sign transaction(Mantle)
# eth_signTransaction
Sign transaction on the Mantle Network.
## Parameters
Varies by method. Please refer to the official [Ethereum JSON-RPC: eth_signTransaction](https://ethereum.org/developers/docs/apis/json-rpc/#eth_signtransaction) documentation for detailed parameter information.
## Returns
The return value depends on the specific method being called.
## Implementation Example
```bash
curl -X POST https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_signTransaction",
"params": [],
"id": 1
}'
```
```javascript
const response = await fetch('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_signTransaction',
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 [Mantle documentation](/docs/mantle).*
---
## eth_syncing - Mantle RPC Method
# eth_syncing
Returns syncing status of Mantle 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-mantle-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-mantle-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 - Mantle RPC Method
# eth_uninstallFilter
Uninstalls a filter on Mantle. 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-mantle-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-mantle-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
---
## Mantle - Modular L2 Documentation
# Mantle Network - Build on the First Modular Layer 2
## Why Build on Mantle?
Mantle Network is the first modular Layer 2 solution, pioneering the use of EigenDA for data availability. Built on the OP Stack with innovative architectural designs, Mantle offers:
### ⚡ **Modular Performance**
- **Sub-second block times** - Fast finality with optimistic rollup
- **Up to 500x lower costs** than Ethereum mainnet
- **20,000+ TPS capacity** - High throughput for demanding applications
### 🔒 **Advanced Security**
- **EigenDA integration** - First L2 with decentralized data availability
- **Optimistic rollup security** - Fraud proof protection with 7-day challenge period
- **Ethereum inheritance** - Full L1 security guarantees
### 🛠️ **Developer Excellence**
- **Full EVM compatibility** - Deploy existing contracts without changes
- **MNT gas token** - Native token for gas and governance
- **OP Stack foundation** - Battle-tested infrastructure
## Quick Start with Mantle
Connect to Mantle in seconds with Dwellir's optimized endpoints:
### Installation & Setup
```javascript
// Connect to Mantle mainnet
const provider = new JsonRpcProvider(
'https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY'
);
// Get network info
const network = await provider.getNetwork();
console.log('Connected to Mantle:', network.chainId); // 5000
// Query blockchain data
const blockNumber = await provider.getBlockNumber();
const balance = await provider.getBalance('0x...');
const gas = await provider.getFeeData();
```
```javascript
// Connect to Mantle
const web3 = new Web3(
'https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY'
);
// Get chain ID
const chainId = await web3.eth.getChainId();
console.log('Chain ID:', chainId); // 5000n
// Query blockchain
const block = await web3.eth.getBlock('latest');
const balance = await web3.eth.getBalance('0x...');
const gasPrice = await web3.eth.getGasPrice();
```
```python
from web3 import Web3
# Connect to Mantle mainnet
w3 = Web3(Web3.HTTPProvider(
'https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY'
))
# Verify connection
if w3.is_connected():
print(f"Connected to Mantle")
print(f"Chain ID: {w3.eth.chain_id}") # 5000
print(f"Latest block: {w3.eth.block_number}")
# Get MNT balance
address = "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"
balance = w3.eth.get_balance(address)
print(f"Balance: {w3.from_wei(balance, 'ether')} MNT")
```
## Network Information
### Mainnet Configuration
- **Network Name**: Mantle Network
- **Chain ID**: `5000` (0x1388)
- **Currency**: MNT
- **Block Explorer**: [https://explorer.mantle.xyz](https://explorer.mantle.xyz)
- **Bridge**: [https://bridge.mantle.xyz](https://bridge.mantle.xyz)
### Testnet Configuration (Sepolia)
- **Network Name**: Mantle Sepolia
- **Chain ID**: `5003` (0x138B)
- **Currency**: MNT (Testnet)
- **Block Explorer**: [https://explorer.testnet.mantle.xyz](https://explorer.testnet.mantle.xyz)
- **Faucet**: [https://faucet.testnet.mantle.xyz](https://faucet.testnet.mantle.xyz)
## Available RPC Methods
Mantle supports all standard Ethereum JSON-RPC methods plus L2-specific extensions:
### Core Methods
- **Transaction Management** - Send, sign, and track transactions
- **State Queries** - Get balances, code, storage
- **Block Information** - Query blocks and receipts
- **Event Logs** - Filter and retrieve events
- **Gas Estimation** - Estimate fees including L1 costs
### L2-Specific Methods
- `eth_estimateL1Fee` - Calculate L1 data posting costs
- `rollup_gasPrices` - Get current L1/L2 gas prices
- `rollup_getInfo` - Query rollup configuration
### Debug & Trace Methods
- `debug_traceTransaction` - Detailed transaction execution traces
- `debug_traceBlock` - Trace all transactions in a block
- `debug_traceCall` - Simulate and trace calls
## Architecture Overview
### Modular Design
Mantle's modular architecture separates core blockchain functions for optimal performance:
1. **Execution Layer** - Processes transactions using the EVM
2. **Settlement Layer** - Posts state commitments to Ethereum
3. **Data Availability Layer** - Uses EigenDA for efficient data storage
4. **Consensus Layer** - Inherits security from Ethereum L1
### EigenDA Integration
As the first L2 to integrate EigenDA, Mantle benefits from:
- **Lower costs** - Reduced data storage expenses
- **Higher throughput** - More efficient data availability
- **Decentralization** - Distributed DA layer
- **ETH restaking** - Additional security through EigenLayer
### Transaction Lifecycle
1. **Submission** - Users submit transactions to Mantle sequencer
2. **Execution** - Transactions processed in batches
3. **Data Posting** - Transaction data posted to EigenDA
4. **Settlement** - State root submitted to Ethereum L1
5. **Finality** - After 7-day challenge period
## Development Resources
### Smart Contract Deployment
Deploy your contracts to Mantle without modifications:
```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MantleApp {
mapping(address => uint256) public balances;
function deposit() public payable {
balances[msg.sender] += msg.value;
}
function withdraw(uint256 amount) public {
require(balances[msg.sender] >= amount, "Insufficient balance");
balances[msg.sender] -= amount;
payable(msg.sender).transfer(amount);
}
}
```
### Using MNT Token
MNT is used for gas payments on Mantle:
```javascript
// Send MNT
const tx = await signer.sendTransaction({
to: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb',
value: ethers.parseEther('1.0') // 1 MNT
});
// Estimate gas in MNT
const gasEstimate = await provider.estimateGas(tx);
const gasPrice = await provider.getFeeData();
const gasCost = gasEstimate * gasPrice.gasPrice; // Cost in MNT
```
### Bridging Assets
Bridge assets between Ethereum and Mantle:
```javascript
// Bridge configuration
const BRIDGE_ADDRESS = '0x...'; // Mantle Bridge contract
const L1_TOKEN = '0x...'; // Token on Ethereum
const L2_TOKEN = '0x...'; // Token on Mantle
// Deposit from L1 to L2
async function depositToMantle(amount) {
const bridge = new Contract(BRIDGE_ADDRESS, BRIDGE_ABI, l1Signer);
const tx = await bridge.depositERC20(
L1_TOKEN,
L2_TOKEN,
amount,
{ value: bridgeFee }
);
await tx.wait();
}
```
## Gas Optimization
### Understanding Mantle Fees
Mantle fees consist of two components:
1. **L2 Execution Fee** - Cost to run transaction on Mantle
2. **L1 Data Fee** - Cost to post data to Ethereum (via EigenDA)
```javascript
// Calculate total fee
const l2GasPrice = await provider.getGasPrice();
const l2GasUsed = await provider.estimateGas(tx);
const l1Fee = await provider.send('eth_estimateL1Fee', [tx]);
const totalFee = (l2GasPrice * l2GasUsed) + BigInt(l1Fee);
console.log('Total fee:', ethers.formatEther(totalFee), 'MNT');
```
### Optimization Tips
1. **Batch Operations** - Combine multiple operations in one transaction
2. **Use Events** - Cheaper than storage for data that doesn't need to be on-chain
3. **Optimize Calldata** - Minimize transaction input data
4. **Storage Packing** - Pack multiple values into single storage slots
## Common Use Cases
### DeFi Protocols
- Lower fees enable more frequent rebalancing and smaller trades
- High throughput supports order book DEXs
- Fast finality improves user experience
### Gaming & NFTs
- Affordable minting and trading
- High-frequency game actions
- Complex on-chain game logic
### DAOs & Governance
- Cost-effective voting
- More frequent proposal submissions
- On-chain treasury management
## Best Practices
### Error Handling
```javascript
try {
const tx = await contract.someMethod();
const receipt = await tx.wait();
if (receipt.status === 0) {
throw new Error('Transaction reverted');
}
} catch (error) {
if (error.code === 'CALL_EXCEPTION') {
console.error('Contract reverted:', error.reason);
} else if (error.code === 'INSUFFICIENT_FUNDS') {
console.error('Not enough MNT for gas');
}
}
```
### Rate Limiting
```javascript
// Implement exponential backoff
async function retryWithBackoff(fn, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
if (i === maxRetries - 1) throw error;
const delay = Math.pow(2, i) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
```
## Support & Resources
### Official Resources
- **Documentation**: [docs.mantle.xyz](https://docs.mantle.xyz)
- **GitHub**: [github.com/mantlenetworkio](https://github.com/mantlenetworkio)
- **Discord**: [discord.gg/mantle](https://discord.gg/mantle)
- **Twitter**: [@0xMantle](https://twitter.com/0xMantle)
### Dwellir Support
- **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com)
- **Status Page**: [status.dwellir.com](https://status.dwellir.com)
- **Support**: [support@dwellir.com](mailto:support@dwellir.com)
## Start Building
Ready to build on Mantle? Get your free API key and start developing:
🚀 Launch Your Mantle dApp Today
Get instant access to Mantle's modular L2 with our high-performance RPC endpoints
Get Your Free API Key →
---
*Need help? Check our [API reference](/mantle/eth_blockNumber) or [contact support](mailto:support@dwellir.com).*
---
## net_listening - Mantle RPC Method
# net_listening
Returns `true` if client is actively listening for network connections on Mantle.
## 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-mantle-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-mantle-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 - Mantle RPC Method
# net_peerCount
Returns number of peers currently connected to Mantle 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-mantle-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-mantle-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 - Mantle RPC Method
# net_version
Returns the current network ID on Mantle.
## 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-mantle-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-mantle-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
---
## rollup_gasPrices - Get modular L2 gas price o...
# rollup_gasPrices
Get modular L2 gas price oracle data on the Mantle network. This method provides comprehensive gas pricing information for the optimistic rollup, including both L2 execution costs and L1 data availability fees.
## Overview
Mantle's modular L2 architecture uses a sophisticated gas pricing mechanism that accounts for:
- **L2 Execution Costs**: Gas costs for transaction execution on the optimistic rollup
- **L1 Data Availability**: Costs for posting transaction data to Ethereum L1 via EigenDA
- **Sequencer Operations**: Costs associated with transaction ordering and batch processing
## Parameters
This method typically takes no parameters, but implementation may vary. Please refer to the official [Mantle documentation](https://docs.mantle.xyz/) for the most current parameter specifications.
## Returns
Gas price oracle data object containing current pricing information for the modular L2 rollup.
## Implementation Example
```bash
curl -X POST https://api-mantle-mainnet.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-mantle-mainnet.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('Gas Prices:', data.result);
// Advanced gas price monitoring for Mantle modular L2
class MantleGasPriceMonitor {
constructor(rpcUrl) {
this.rpcUrl = rpcUrl;
this.priceHistory = [];
}
async getGasPrices() {
const response = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'rollup_gasPrices',
params: [],
id: 1
})
});
const data = await response.json();
if (data.error) {
throw new Error(`RPC Error: ${data.error.message}`);
}
return data.result;
}
async getCurrentPricing() {
try {
// Get rollup gas prices
const rollupPrices = await this.getGasPrices();
// Get standard gas price for comparison
const standardGasResponse = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_gasPrice',
params: [],
id: 1
})
});
const standardGasData = await standardGasResponse.json();
const standardGasPrice = parseInt(standardGasData.result, 16);
return {
timestamp: Date.now(),
rollupPrices: rollupPrices,
standardGasPrice: standardGasPrice,
formattedPrices: this.formatPrices(rollupPrices, standardGasPrice)
};
} catch (error) {
throw new Error(`Failed to get pricing: ${error.message}`);
}
}
formatPrices(rollupPrices, standardGasPrice) {
return {
standardGasPrice: {
wei: standardGasPrice,
gwei: (standardGasPrice / 1e9).toFixed(2),
mnt: (standardGasPrice / 1e18).toFixed(8)
},
rollupData: rollupPrices // This will depend on actual response format
};
}
async trackPriceHistory(duration = 3600000, interval = 60000) {
// Track gas prices for specified duration (default 1 hour) at intervals (default 1 minute)
const startTime = Date.now();
const endTime = startTime + duration;
console.log(`Starting price tracking for ${duration / 60000} minutes...`);
while (Date.now() < endTime) {
try {
const pricing = await this.getCurrentPricing();
this.priceHistory.push(pricing);
console.log(`Price update: ${pricing.formattedPrices.standardGasPrice.gwei} gwei`);
await new Promise(resolve => setTimeout(resolve, interval));
} catch (error) {
console.error('Price tracking error:', error.message);
await new Promise(resolve => setTimeout(resolve, interval));
}
}
return this.analyzePriceHistory();
}
analyzePriceHistory() {
if (this.priceHistory.length === 0) {
return { error: 'No price history available' };
}
const prices = this.priceHistory.map(p => p.standardGasPrice);
const sortedPrices = [...prices].sort((a, b) => a - b);
const analysis = {
duration: {
start: new Date(this.priceHistory[0].timestamp).toISOString(),
end: new Date(this.priceHistory[this.priceHistory.length - 1].timestamp).toISOString(),
dataPoints: this.priceHistory.length
},
statistics: {
min: Math.min(...prices),
max: Math.max(...prices),
average: prices.reduce((sum, p) => sum + p, 0) / prices.length,
median: sortedPrices[Math.floor(sortedPrices.length / 2)],
volatility: this.calculateVolatility(prices)
},
trends: {
direction: this.getTrend(prices),
priceChange: prices[prices.length - 1] - prices[0],
percentageChange: ((prices[prices.length - 1] - prices[0]) / prices[0] * 100).toFixed(2)
},
recommendations: this.generateRecommendations(prices)
};
return analysis;
}
calculateVolatility(prices) {
if (prices.length < 2) return 0;
const mean = prices.reduce((sum, p) => sum + p, 0) / prices.length;
const variance = prices.reduce((sum, p) => sum + Math.pow(p - mean, 2), 0) / prices.length;
return Math.sqrt(variance);
}
getTrend(prices) {
if (prices.length < 2) return 'insufficient_data';
const firstHalf = prices.slice(0, Math.floor(prices.length / 2));
const secondHalf = prices.slice(Math.floor(prices.length / 2));
const firstAvg = firstHalf.reduce((sum, p) => sum + p, 0) / firstHalf.length;
const secondAvg = secondHalf.reduce((sum, p) => sum + p, 0) / secondHalf.length;
const changePct = ((secondAvg - firstAvg) / firstAvg) * 100;
if (changePct > 5) return 'increasing';
if (changePct < -5) return 'decreasing';
return 'stable';
}
generateRecommendations(prices) {
const recommendations = [];
const currentPrice = prices[prices.length - 1];
const avgPrice = prices.reduce((sum, p) => sum + p, 0) / prices.length;
const minPrice = Math.min(...prices);
if (currentPrice > avgPrice * 1.2) {
recommendations.push({
type: 'high_gas_warning',
message: 'Current gas price is significantly above average',
suggestion: 'Consider waiting for lower gas prices or using lower priority'
});
}
if (currentPrice <= minPrice * 1.1) {
recommendations.push({
type: 'optimal_timing',
message: 'Current gas price is near historical low',
suggestion: 'Good time to execute transactions'
});
}
const volatility = this.calculateVolatility(prices);
if (volatility > avgPrice * 0.1) {
recommendations.push({
type: 'high_volatility',
message: 'Gas prices are highly volatile',
suggestion: 'Monitor prices closely and be prepared to adjust'
});
}
return recommendations;
}
async predictOptimalTiming(targetGasPrice) {
const pricing = await this.getCurrentPricing();
const currentPrice = pricing.standardGasPrice;
if (currentPrice <= targetGasPrice) {
return {
optimal: true,
currentPrice: currentPrice,
targetPrice: targetGasPrice,
recommendation: 'Execute transaction now'
};
}
// Simple prediction based on recent trend
const recentPrices = this.priceHistory.slice(-10).map(p => p.standardGasPrice);
const trend = this.getTrend(recentPrices);
let prediction = 'unknown';
let estimatedWait = 'unknown';
if (trend === 'decreasing') {
prediction = 'prices_likely_to_drop';
estimatedWait = 'monitor_for_15_30_minutes';
} else if (trend === 'increasing') {
prediction = 'prices_likely_to_rise';
estimatedWait = 'consider_executing_soon';
} else {
prediction = 'prices_stable';
estimatedWait = 'no_clear_trend';
}
return {
optimal: false,
currentPrice: currentPrice,
targetPrice: targetGasPrice,
prediction: prediction,
estimatedWait: estimatedWait,
recommendation: `Current: ${(currentPrice / 1e9).toFixed(2)} gwei, Target: ${(targetGasPrice / 1e9).toFixed(2)} gwei`
};
}
async compareWithL1Costs() {
try {
// Get Mantle gas prices
const mantlePricing = await this.getCurrentPricing();
// For comparison with Ethereum L1, you would need to call Ethereum mainnet
// This is just an example structure
const comparison = {
mantle: {
gasPrice: mantlePricing.standardGasPrice,
gasPriceGwei: mantlePricing.formattedPrices.standardGasPrice.gwei,
estimatedTransferCost: mantlePricing.standardGasPrice * 21000 // MNT transfer
},
savings: {
// This would be calculated with actual L1 data
estimatedSavings: 'Requires L1 comparison data',
savingsPercentage: 'Requires L1 comparison data'
}
};
return comparison;
} catch (error) {
throw new Error(`Failed to compare costs: ${error.message}`);
}
}
}
// Usage examples
const gasPriceMonitor = new MantleGasPriceMonitor('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY');
// Get current gas pricing
const currentPricing = await gasPriceMonitor.getCurrentPricing();
console.log('Current Gas Prices:', currentPricing.formattedPrices);
// Track prices for 10 minutes
const priceAnalysis = await gasPriceMonitor.trackPriceHistory(600000, 30000);
console.log('Price Analysis:', priceAnalysis);
// Check optimal timing for transaction
const optimalTiming = await gasPriceMonitor.predictOptimalTiming(20000000000); // 20 gwei target
console.log('Optimal Timing:', optimalTiming);
// Compare with L1 costs
const costComparison = await gasPriceMonitor.compareWithL1Costs();
console.log('Cost Comparison:', costComparison);
```
```python
from typing import Dict, List, Any, Optional
from datetime import datetime, timedelta
class MantleGasPriceAnalyzer:
"""Analyze and monitor gas prices on Mantle modular L2"""
def __init__(self, rpc_url: str):
self.rpc_url = rpc_url
self.price_history = []
def get_rollup_gas_prices(self) -> Dict[str, Any]:
"""Get current rollup gas prices"""
payload = {
"jsonrpc": "2.0",
"method": "rollup_gasPrices",
"params": [],
"id": 1
}
response = requests.post(self.rpc_url, json=payload)
data = response.json()
if 'error' in data:
raise Exception(f"RPC Error: {data['error']['message']}")
return data['result']
def get_standard_gas_price(self) -> int:
"""Get standard gas price for comparison"""
payload = {
"jsonrpc": "2.0",
"method": "eth_gasPrice",
"params": [],
"id": 1
}
response = requests.post(self.rpc_url, json=payload)
data = response.json()
if 'error' in data:
raise Exception(f"RPC Error: {data['error']['message']}")
return int(data['result'], 16)
def get_comprehensive_pricing(self) -> Dict[str, Any]:
"""Get comprehensive gas pricing information"""
rollup_prices = self.get_rollup_gas_prices()
standard_gas_price = self.get_standard_gas_price()
return {
'timestamp': datetime.now().isoformat(),
'rollup_data': rollup_prices,
'standard_gas_price': standard_gas_price,
'formatted': {
'gas_price_wei': standard_gas_price,
'gas_price_gwei': round(standard_gas_price / 1e9, 2),
'gas_price_mnt': round(standard_gas_price / 1e18, 8)
},
'transaction_costs': {
'mnt_transfer': standard_gas_price * 21000, # Standard MNT transfer
'erc20_transfer': standard_gas_price * 65000, # Typical ERC20 transfer
'swap': standard_gas_price * 150000 # Typical DEX swap
}
}
def monitor_prices(
self,
duration_minutes: int = 60,
interval_seconds: int = 60
) -> Dict[str, Any]:
"""Monitor gas prices over time"""
start_time = datetime.now()
end_time = start_time + timedelta(minutes=duration_minutes)
print(f"Monitoring gas prices for {duration_minutes} minutes...")
price_data = []
while datetime.now() < end_time:
try:
pricing = self.get_comprehensive_pricing()
price_data.append(pricing)
self.price_history.append(pricing)
print(f"Price update: {pricing['formatted']['gas_price_gwei']} gwei")
time.sleep(interval_seconds)
except Exception as e:
print(f"Error monitoring prices: {e}")
time.sleep(interval_seconds)
return self._analyze_price_data(price_data)
def _analyze_price_data(self, price_data: List[Dict]) -> Dict[str, Any]:
"""Analyze collected price data"""
if not price_data:
return {'error': 'No price data available'}
gas_prices = [p['standard_gas_price'] for p in price_data]
gwei_prices = [p['formatted']['gas_price_gwei'] for p in price_data]
analysis = {
'period': {
'start': price_data[0]['timestamp'],
'end': price_data[-1]['timestamp'],
'data_points': len(price_data)
},
'statistics': {
'min_wei': min(gas_prices),
'max_wei': max(gas_prices),
'average_wei': statistics.mean(gas_prices),
'median_wei': statistics.median(gas_prices),
'min_gwei': min(gwei_prices),
'max_gwei': max(gwei_prices),
'average_gwei': round(statistics.mean(gwei_prices), 2),
'median_gwei': round(statistics.median(gwei_prices), 2),
'std_dev_gwei': round(statistics.stdev(gwei_prices) if len(gwei_prices) > 1 else 0, 2)
},
'trends': self._calculate_trends(gas_prices),
'volatility': self._calculate_volatility(gas_prices),
'cost_analysis': self._analyze_transaction_costs(price_data)
}
return analysis
def _calculate_trends(self, prices: List[int]) -> Dict[str, Any]:
"""Calculate price trends"""
if len(prices) < 2:
return {'trend': 'insufficient_data'}
# Simple linear trend
x = list(range(len(prices)))
n = len(prices)
# Calculate slope using least squares
sum_x = sum(x)
sum_y = sum(prices)
sum_xy = sum(x[i] * prices[i] for i in range(n))
sum_x2 = sum(x[i] ** 2 for i in range(n))
slope = (n * sum_xy - sum_x * sum_y) / (n * sum_x2 - sum_x ** 2)
# Percentage change
price_change = prices[-1] - prices[0]
pct_change = (price_change / prices[0]) * 100
trend_direction = 'increasing' if slope > 0 else 'decreasing' if slope < 0 else 'stable'
return {
'trend': trend_direction,
'slope': slope,
'price_change_wei': price_change,
'percentage_change': round(pct_change, 2),
'is_volatile': abs(pct_change) > 10
}
def _calculate_volatility(self, prices: List[int]) -> Dict[str, Any]:
"""Calculate price volatility metrics"""
if len(prices) < 2:
return {'volatility': 0}
mean_price = statistics.mean(prices)
variance = statistics.variance(prices)
std_dev = statistics.stdev(prices)
# Coefficient of variation (relative volatility)
cv = (std_dev / mean_price) * 100 if mean_price > 0 else 0
return {
'standard_deviation': round(std_dev, 2),
'variance': round(variance, 2),
'coefficient_of_variation': round(cv, 2),
'volatility_level': (
'high' if cv > 15 else
'medium' if cv > 5 else
'low'
)
}
def _analyze_transaction_costs(self, price_data: List[Dict]) -> Dict[str, Any]:
"""Analyze transaction costs over time"""
cost_analysis = {
'mnt_transfer': [],
'erc20_transfer': [],
'swap': []
}
for data in price_data:
costs = data['transaction_costs']
cost_analysis['mnt_transfer'].append(costs['mnt_transfer'])
cost_analysis['erc20_transfer'].append(costs['erc20_transfer'])
cost_analysis['swap'].append(costs['swap'])
result = {}
for tx_type, costs in cost_analysis.items():
result[tx_type] = {
'min_cost_wei': min(costs),
'max_cost_wei': max(costs),
'avg_cost_wei': round(statistics.mean(costs)),
'cost_range_wei': max(costs) - min(costs),
'min_cost_usd': 'Requires MNT price data',
'max_cost_usd': 'Requires MNT price data'
}
return result
def recommend_optimal_timing(
self,
target_gas_price_gwei: float,
transaction_type: str = 'mnt_transfer'
) -> Dict[str, Any]:
"""Recommend optimal timing for transaction execution"""
current_pricing = self.get_comprehensive_pricing()
current_gwei = current_pricing['formatted']['gas_price_gwei']
recommendation = {
'current_price_gwei': current_gwei,
'target_price_gwei': target_gas_price_gwei,
'execute_now': current_gwei <= target_gas_price_gwei
}
if recommendation['execute_now']:
recommendation['message'] = 'Current gas price meets target - execute now'
recommendation['estimated_cost'] = current_pricing['transaction_costs'][transaction_type]
else:
price_diff = current_gwei - target_gas_price_gwei
recommendation['message'] = f'Wait for lower prices (current: {current_gwei}, target: {target_gas_price_gwei})'
recommendation['price_difference_gwei'] = round(price_diff, 2)
# Simple prediction based on recent trend if available
if len(self.price_history) > 5:
recent_prices = [p['standard_gas_price'] for p in self.price_history[-5:]]
trends = self._calculate_trends(recent_prices)
if trends['trend'] == 'decreasing':
recommendation['prediction'] = 'Prices trending down - may reach target soon'
elif trends['trend'] == 'increasing':
recommendation['prediction'] = 'Prices trending up - consider executing soon'
else:
recommendation['prediction'] = 'Prices stable - monitor for changes'
return recommendation
def compare_with_ethereum_l1(self, eth_l1_gas_price_gwei: float) -> Dict[str, Any]:
"""Compare Mantle costs with Ethereum L1"""
mantle_pricing = self.get_comprehensive_pricing()
mantle_gwei = mantle_pricing['formatted']['gas_price_gwei']
# Calculate savings for different transaction types
savings_analysis = {}
for tx_type, mantle_gas_units in [
('mnt_transfer', 21000),
('erc20_transfer', 65000),
('swap', 150000)
]:
l1_cost_wei = int(eth_l1_gas_price_gwei * 1e9 * mantle_gas_units)
mantle_cost_wei = mantle_pricing['transaction_costs'][tx_type]
savings_wei = l1_cost_wei - mantle_cost_wei
savings_pct = (savings_wei / l1_cost_wei) * 100 if l1_cost_wei > 0 else 0
savings_analysis[tx_type] = {
'l1_cost_wei': l1_cost_wei,
'mantle_cost_wei': mantle_cost_wei,
'savings_wei': savings_wei,
'savings_percentage': round(savings_pct, 2),
'cost_ratio': round(mantle_cost_wei / l1_cost_wei, 3) if l1_cost_wei > 0 else 0
}
return {
'comparison_timestamp': datetime.now().isoformat(),
'l1_gas_price_gwei': eth_l1_gas_price_gwei,
'mantle_gas_price_gwei': mantle_gwei,
'price_ratio': round(mantle_gwei / eth_l1_gas_price_gwei, 3) if eth_l1_gas_price_gwei > 0 else 0,
'transaction_savings': savings_analysis
}
# Usage examples
analyzer = MantleGasPriceAnalyzer('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY')
# Get current comprehensive pricing
pricing = analyzer.get_comprehensive_pricing()
print(f"Current gas price: {pricing['formatted']['gas_price_gwei']} gwei")
print(f"MNT transfer cost: {pricing['transaction_costs']['mnt_transfer']:,} wei")
# Monitor prices for 30 minutes
price_analysis = analyzer.monitor_prices(duration_minutes=30, interval_seconds=120)
print("\nPrice Analysis:")
print(f"Average: {price_analysis['statistics']['average_gwei']} gwei")
print(f"Volatility: {price_analysis['volatility']['volatility_level']}")
print(f"Trend: {price_analysis['trends']['trend']}")
# Get timing recommendation
timing = analyzer.recommend_optimal_timing(target_gas_price_gwei=15.0)
print(f"\nTiming recommendation: {timing['message']}")
# Compare with Ethereum L1 (example with 50 gwei L1 price)
comparison = analyzer.compare_with_ethereum_l1(eth_l1_gas_price_gwei=50.0)
print(f"\nL1 vs Mantle savings:")
for tx_type, data in comparison['transaction_savings'].items():
print(f" {tx_type}: {data['savings_percentage']}% savings")
```
## Response Example
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"l1GasPrice": "0x12a05f200",
"l2GasPrice": "0x3b9aca00",
"overhead": "0xbc0",
"scalar": "0x684000",
"decimals": "0x6"
}
}
```
## Understanding Gas Prices on Mantle
### Price Components
1. **L2 Gas Price**: Cost per gas unit for execution on Mantle's modular L2
2. **L1 Gas Price**: Current Ethereum L1 gas price for data posting via EigenDA
3. **Overhead**: Fixed overhead cost for L1 data posting
4. **Scalar**: Scaling factor for L1 cost calculation
5. **Decimals**: Decimal precision for calculations
### Cost Calculation
Total transaction cost = (L2 Gas × L2 Gas Price) + L1 Data Fee
Where L1 Data Fee considers:
- Transaction data size
- Current L1 gas price via EigenDA
- Overhead and scalar factors
## Common Use Cases
### 1. Gas Price Monitoring
```javascript
// Monitor gas prices for optimal transaction timing
async function monitorForOptimalGas(targetGwei, callback) {
const monitor = new MantleGasPriceMonitor(rpcUrl);
const checkPrice = async () => {
const pricing = await monitor.getCurrentPricing();
const currentGwei = pricing.formattedPrices.standardGasPrice.gwei;
if (currentGwei <= targetGwei) {
callback({
optimal: true,
currentPrice: currentGwei,
targetPrice: targetGwei,
message: 'Target price reached!'
});
return true;
}
return false;
};
// Check every 30 seconds
const interval = setInterval(async () => {
const optimal = await checkPrice();
if (optimal) {
clearInterval(interval);
}
}, 30000);
// Initial check
await checkPrice();
}
```
### 2. Cost Optimization
```python
def optimize_transaction_timing(analyzer, transactions, budget_gwei):
"""Find optimal timing for multiple transactions within budget"""
optimization_plan = []
for i, tx in enumerate(transactions):
# Estimate transaction cost at different gas prices
cost_estimates = []
for gas_price_gwei in [10, 15, 20, 25, 30]:
gas_price_wei = int(gas_price_gwei * 1e9)
estimated_cost = tx['gas_estimate'] * gas_price_wei
cost_estimates.append({
'gas_price_gwei': gas_price_gwei,
'estimated_cost_wei': estimated_cost,
'within_budget': gas_price_gwei <= budget_gwei
})
# Find optimal price point
optimal = next(
(est for est in cost_estimates if est['within_budget']),
cost_estimates[0]
)
optimization_plan.append({
'transaction_id': i,
'optimal_gas_price': optimal['gas_price_gwei'],
'estimated_cost': optimal['estimated_cost_wei'],
'cost_estimates': cost_estimates
})
return optimization_plan
```
### 3. Historical Analysis
```javascript
// Analyze historical gas price patterns
async function analyzeGasPricePatterns(monitor, days = 7) {
const patterns = {
hourlyAverages: {},
dailyTrends: [],
optimalTimes: []
};
// This would require storing historical data
// For demonstration, showing structure
// Simulate hourly analysis
for (let hour = 0; hour < 24; hour++) {
patterns.hourlyAverages[hour] = {
averageGwei: 0, // Would be calculated from historical data
transactionVolume: 0,
volatility: 0
};
}
// Identify optimal transaction times
const sortedHours = Object.entries(patterns.hourlyAverages)
.sort((a, b) => a[1].averageGwei - b[1].averageGwei);
patterns.optimalTimes = sortedHours.slice(0, 6).map(([hour, data]) => ({
hour: parseInt(hour),
averageGwei: data.averageGwei,
timeRange: `${hour}:00-${hour}:59 UTC`
}));
return patterns;
}
```
## Related Methods
- [`eth_gasPrice`](/mantle/eth_gasPrice) - Get current L2 gas price
- [`eth_feeHistory`](/mantle/eth_feeHistory) - Historical fee data
- [`eth_estimateGas`](/mantle/eth_estimateGas) - Estimate transaction gas
- [`rollup_getInfo`](/mantle/rollup_getInfo) - Get rollup configuration
---
*Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Mantle documentation](/docs/mantle).*
---
## rollup_getInfo - Get modular L2 rollup config...
# rollup_getInfo
Get modular L2 rollup configuration on the Mantle network. This method provides essential information about the optimistic rollup parameters, settings, and operational details.
## Overview
Mantle's modular L2 architecture is an optimistic rollup that leverages modular components for enhanced performance and scalability. The rollup configuration includes important parameters for:
- **Batch Processing**: How transactions are batched and processed
- **Data Availability**: EigenDA integration for efficient data posting
- **Bridge Operations**: L1 ↔ L2 asset bridging configuration
- **Network Parameters**: Chain ID, block times, and operational settings
## Parameters
This method typically takes no parameters, but implementation may vary. Please refer to the official [Mantle documentation](https://docs.mantle.xyz/) for the most current parameter specifications.
## Returns
Rollup configuration object containing comprehensive information about the modular L2 rollup setup.
## Implementation Example
```bash
curl -X POST https://api-mantle-mainnet.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-mantle-mainnet.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('Rollup Info:', data.result);
// Advanced Mantle modular L2 rollup information analyzer
class MantleRollupAnalyzer {
constructor(rpcUrl) {
this.rpcUrl = rpcUrl;
}
async getRollupInfo() {
const response = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'rollup_getInfo',
params: [],
id: 1
})
});
const data = await response.json();
if (data.error) {
throw new Error(`RPC Error: ${data.error.message}`);
}
return data.result;
}
async getComprehensiveRollupStatus() {
try {
// Get rollup info
const rollupInfo = await this.getRollupInfo();
// Get current chain info
const chainIdResponse = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_chainId',
params: [],
id: 1
})
});
const chainData = await chainIdResponse.json();
const chainId = parseInt(chainData.result, 16);
// Get latest block info
const blockResponse = await fetch(this.rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_getBlockByNumber',
params: ['latest', false],
id: 1
})
});
const blockData = await blockResponse.json();
const latestBlock = blockData.result;
return {
timestamp: new Date().toISOString(),
network: {
name: 'Mantle',
chainId: chainId,
type: 'Modular L2 Optimistic Rollup'
},
rollupConfig: rollupInfo,
currentState: {
latestBlock: parseInt(latestBlock.number, 16),
blockHash: latestBlock.hash,
timestamp: parseInt(latestBlock.timestamp, 16),
gasLimit: parseInt(latestBlock.gasLimit, 16),
gasUsed: parseInt(latestBlock.gasUsed, 16),
utilization: ((parseInt(latestBlock.gasUsed, 16) / parseInt(latestBlock.gasLimit, 16)) * 100).toFixed(2)
},
analysis: this.analyzeRollupConfig(rollupInfo, chainId)
};
} catch (error) {
throw new Error(`Failed to get comprehensive status: ${error.message}`);
}
}
analyzeRollupConfig(rollupInfo, chainId) {
const analysis = {
networkType: 'Modular L2 Optimistic Rollup',
securityModel: 'Optimistic with fraud proofs',
dataAvailability: 'EigenDA integration',
features: [],
optimizations: [],
considerations: []
};
// Analyze chain ID
if (chainId === 5000) {
analysis.features.push('Mantle Mainnet');
analysis.features.push('Production Network');
} else if (chainId === 5003) {
analysis.features.push('Mantle Sepolia Testnet');
analysis.features.push('Development Network');
}
// General modular L2 features
analysis.features.push('EVM Compatibility');
analysis.features.push('Optimistic Rollup Architecture');
analysis.features.push('EigenDA Data Availability');
analysis.features.push('MNT Gas Token');
analysis.features.push('OP Stack Foundation');
// Optimizations
analysis.optimizations.push('High Throughput via Modular Architecture');
analysis.optimizations.push('Low Transaction Costs');
analysis.optimizations.push('Fast L2 Finality');
analysis.optimizations.push('Ethereum Virtual Machine Compatibility');
analysis.optimizations.push('Efficient Data Availability via EigenDA');
// Considerations
analysis.considerations.push('7-day withdrawal period for L1 finality');
analysis.considerations.push('L1 data posting costs via EigenDA');
analysis.considerations.push('Optimistic fraud proof mechanism');
return analysis;
}
async compareWithOtherL2s() {
const mantleInfo = await this.getComprehensiveRollupStatus();
// This would be expanded with actual data from other L2s
const comparison = {
mantle: {
type: 'Modular L2 Optimistic Rollup',
proofSystem: 'Fraud Proofs',
evmCompatibility: 'Full',
dataAvailability: 'EigenDA',
finality: 'Optimistic → Proven',
withdrawalTime: '~7 days',
gasToken: 'MNT',
advantages: [
'Modular architecture for flexibility',
'EigenDA for efficient data availability',
'Fast transaction processing',
'MNT gas token benefits',
'OP Stack foundation'
]
},
zkRollups: {
type: 'Zero-Knowledge',
proofSystem: 'Zero-Knowledge Proofs',
evmCompatibility: 'Full (zkEVM)',
dataAvailability: 'On-chain (Ethereum L1)',
finality: 'Cryptographic',
withdrawalTime: '~7 days (pending finalization)',
tradeoffs: [
'Cryptographic security guarantees',
'Privacy-preserving proofs',
'Higher computational overhead',
'Proof generation complexity'
]
},
comparison: {
security: 'Both provide strong security with different mechanisms',
performance: 'Mantle optimized for high throughput',
costs: 'Mantle benefits from EigenDA cost efficiency',
devExperience: 'Both offer full EVM compatibility'
}
};
return comparison;
}
async monitorRollupHealth() {
const health = {
timestamp: new Date().toISOString(),
status: 'unknown',
metrics: {},
alerts: []
};
try {
const status = await this.getComprehensiveRollupStatus();
// Check basic connectivity and latest block
const blockAge = Date.now() / 1000 - status.currentState.timestamp;
health.metrics = {
latestBlock: status.currentState.latestBlock,
blockAge: blockAge,
gasUtilization: parseFloat(status.currentState.utilization),
chainId: status.network.chainId
};
// Health checks
if (blockAge > 300) { // 5 minutes
health.alerts.push({
severity: 'warning',
message: `Latest block is ${Math.floor(blockAge / 60)} minutes old`,
recommendation: 'Check network connectivity and block production'
});
}
if (health.metrics.gasUtilization > 90) {
health.alerts.push({
severity: 'info',
message: `High gas utilization: ${health.metrics.gasUtilization}%`,
recommendation: 'Network is experiencing high usage'
});
}
health.status = health.alerts.length === 0 ? 'healthy' :
health.alerts.some(a => a.severity === 'error') ? 'unhealthy' : 'warning';
} catch (error) {
health.status = 'error';
health.alerts.push({
severity: 'error',
message: `Failed to get rollup status: ${error.message}`,
recommendation: 'Check RPC endpoint connectivity'
});
}
return health;
}
async getNetworkCapacityInfo() {
try {
const status = await this.getComprehensiveRollupStatus();
const capacity = {
current: {
blockGasLimit: status.currentState.gasLimit,
blockGasUsed: status.currentState.gasUsed,
utilizationPercentage: parseFloat(status.currentState.utilization)
},
theoretical: {
maxTxPerSecond: 0, // Would be calculated based on average gas per tx
maxTxPerBlock: 0,
avgBlockTime: 0 // Would need historical data
},
estimates: {
simpleTransfers: Math.floor(status.currentState.gasLimit / 21000),
erc20Transfers: Math.floor(status.currentState.gasLimit / 65000),
complexContracts: Math.floor(status.currentState.gasLimit / 200000)
}
};
return capacity;
} catch (error) {
throw new Error(`Failed to get capacity info: ${error.message}`);
}
}
async analyzeUpgradeability() {
const rollupInfo = await this.getRollupInfo();
// This would analyze the actual rollup configuration
// For demonstration, providing general modular L2 upgrade analysis
return {
upgradeType: 'Governed Upgrades',
governanceModel: 'Multi-signature or DAO governance',
upgradeProcess: [
'Proposal submission',
'Community review',
'Governance voting',
'Implementation timeline',
'Upgrade execution'
],
considerations: [
'Modular architecture allows component upgrades',
'Smart contract upgrades follow standard patterns',
'L1 contract upgrades need careful coordination',
'Backward compatibility maintenance'
],
riskMitigation: [
'Extensive testing on testnets',
'Gradual rollout procedures',
'Emergency pause mechanisms',
'Rollback capabilities where possible'
]
};
}
async getBridgeInfo() {
// This would integrate with bridge contracts
// For demonstration, providing general bridge information
return {
bridgeType: 'Canonical Bridge',
supportedAssets: [
'ETH (bridged)',
'MNT (native gas token)',
'ERC-20 Tokens',
'ERC-721 NFTs',
'ERC-1155 Multi-tokens'
],
bridgeProcess: {
deposit: {
timeToL2: '~15 minutes',
steps: [
'Lock tokens on L1',
'Wait for L1 confirmation',
'Mint on L2',
'Tokens available on L2'
]
},
withdrawal: {
timeToL1: '~7 days',
steps: [
'Burn tokens on L2',
'Include in batch',
'Submit to L1',
'Challenge period (7 days)',
'Claim on L1'
]
}
},
security: {
model: 'Optimistic fraud proofs',
assumptions: 'Ethereum L1 security + honest validator assumption',
risks: [
'Smart contract bugs',
'Fraud proof mechanism vulnerabilities',
'Bridge implementation issues'
]
}
};
}
}
// Usage examples
const rollupAnalyzer = new MantleRollupAnalyzer('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY');
// Get basic rollup info
const rollupInfo = await rollupAnalyzer.getRollupInfo();
console.log('Rollup Configuration:', rollupInfo);
// Get comprehensive status
const comprehensiveStatus = await rollupAnalyzer.getComprehensiveRollupStatus();
console.log('Network Status:', comprehensiveStatus);
// Monitor rollup health
const healthStatus = await rollupAnalyzer.monitorRollupHealth();
console.log('Health Status:', healthStatus.status);
console.log('Alerts:', healthStatus.alerts);
// Get network capacity info
const capacityInfo = await rollupAnalyzer.getNetworkCapacityInfo();
console.log('Network Capacity:', capacityInfo);
// Compare with other L2s
const comparison = await rollupAnalyzer.compareWithOtherL2s();
console.log('L2 Comparison:', comparison);
// Analyze upgradeability
const upgradeAnalysis = await rollupAnalyzer.analyzeUpgradeability();
console.log('Upgrade Model:', upgradeAnalysis);
// Get bridge information
const bridgeInfo = await rollupAnalyzer.getBridgeInfo();
console.log('Bridge Details:', bridgeInfo);
```
```python
from typing import Dict, List, Any, Optional
from datetime import datetime
class MantleRollupInfoAnalyzer:
"""Comprehensive analyzer for Mantle modular L2 rollup information"""
def __init__(self, rpc_url: str):
self.rpc_url = rpc_url
def get_rollup_info(self) -> Dict[str, Any]:
"""Get basic rollup configuration information"""
payload = {
"jsonrpc": "2.0",
"method": "rollup_getInfo",
"params": [],
"id": 1
}
response = requests.post(self.rpc_url, json=payload)
data = response.json()
if 'error' in data:
raise Exception(f"RPC Error: {data['error']['message']}")
return data['result']
def _make_rpc_call(self, method: str, params: List = None) -> Any:
"""Helper method for making RPC calls"""
payload = {
"jsonrpc": "2.0",
"method": method,
"params": params or [],
"id": 1
}
response = requests.post(self.rpc_url, json=payload)
data = response.json()
if 'error' in data:
raise Exception(f"RPC Error: {data['error']['message']}")
return data['result']
def get_comprehensive_rollup_status(self) -> Dict[str, Any]:
"""Get comprehensive rollup status and configuration"""
rollup_info = self.get_rollup_info()
# Get additional network information
chain_id = int(self._make_rpc_call('eth_chainId'), 16)
latest_block = self._make_rpc_call('eth_getBlockByNumber', ['latest', False])
block_number = int(latest_block['number'], 16)
block_timestamp = int(latest_block['timestamp'], 16)
gas_limit = int(latest_block['gasLimit'], 16)
gas_used = int(latest_block['gasUsed'], 16)
return {
'timestamp': datetime.now().isoformat(),
'network_info': {
'name': 'Mantle',
'chain_id': chain_id,
'type': 'Modular L2 Optimistic Rollup',
'consensus': 'Optimistic with fraud proofs'
},
'rollup_config': rollup_info,
'current_state': {
'latest_block': block_number,
'block_hash': latest_block['hash'],
'block_timestamp': block_timestamp,
'gas_limit': gas_limit,
'gas_used': gas_used,
'gas_utilization': round((gas_used / gas_limit) * 100, 2),
'block_age_seconds': int(time.time()) - block_timestamp
},
'analysis': self._analyze_rollup_configuration(rollup_info, chain_id)
}
def _analyze_rollup_configuration(
self,
rollup_info: Dict[str, Any],
chain_id: int
) -> Dict[str, Any]:
"""Analyze rollup configuration and provide insights"""
analysis = {
'rollup_type': 'Modular L2 Optimistic Rollup',
'security_model': 'Optimistic fraud proofs with L1 data availability',
'key_features': [
'Full EVM compatibility',
'Optimistic fraud proof validation',
'EigenDA data availability',
'MNT gas token',
'OP Stack foundation',
'Modular architecture'
],
'network_classification': 'Mainnet' if chain_id == 5000 else 'Testnet',
'performance_characteristics': {
'finality': 'Optimistic with 7-day challenge period',
'withdrawal_time': '~7 days (challenge period)',
'throughput': 'High (optimized via modular architecture)',
'costs': 'Low L2 execution + efficient L1 data costs via EigenDA'
}
}
# Add specific insights based on chain
if chain_id == 5000: # Mantle Mainnet
analysis['environment'] = 'Production'
analysis['considerations'] = [
'Real value at risk',
'Production-grade security',
'Full audit coverage',
'Mainnet gas costs with MNT token'
]
elif chain_id == 5003: # Mantle Sepolia Testnet
analysis['environment'] = 'Testing'
analysis['considerations'] = [
'Testing and development use',
'No real value',
'Latest features may be experimental',
'Network resets possible'
]
return analysis
def monitor_rollup_performance(self, duration_minutes: int = 10) -> Dict[str, Any]:
"""Monitor rollup performance over time"""
monitoring_data = []
start_time = datetime.now()
print(f"Monitoring rollup for {duration_minutes} minutes...")
try:
while (datetime.now() - start_time).seconds < duration_minutes * 60:
status = self.get_comprehensive_rollup_status()
monitoring_data.append(status)
print(f"Block: {status['current_state']['latest_block']}, "
f"Utilization: {status['current_state']['gas_utilization']}%")
time.sleep(30) # Check every 30 seconds
except KeyboardInterrupt:
print("Monitoring stopped by user")
return self._analyze_performance_data(monitoring_data)
def _analyze_performance_data(self, monitoring_data: List[Dict]) -> Dict[str, Any]:
"""Analyze collected performance data"""
if not monitoring_data:
return {'error': 'No monitoring data collected'}
block_numbers = [d['current_state']['latest_block'] for d in monitoring_data]
gas_utilizations = [d['current_state']['gas_utilization'] for d in monitoring_data]
block_ages = [d['current_state']['block_age_seconds'] for d in monitoring_data]
# Calculate block production rate
if len(block_numbers) > 1:
blocks_produced = block_numbers[-1] - block_numbers[0]
time_elapsed = (
datetime.fromisoformat(monitoring_data[-1]['timestamp']) -
datetime.fromisoformat(monitoring_data[0]['timestamp'])
).seconds
avg_block_time = time_elapsed / blocks_produced if blocks_produced > 0 else 0
else:
avg_block_time = 0
blocks_produced = 0
return {
'monitoring_period': {
'start': monitoring_data[0]['timestamp'],
'end': monitoring_data[-1]['timestamp'],
'data_points': len(monitoring_data)
},
'block_production': {
'blocks_produced': blocks_produced,
'average_block_time': round(avg_block_time, 2),
'block_range': f"{block_numbers[0]} - {block_numbers[-1]}"
},
'gas_utilization': {
'average': round(sum(gas_utilizations) / len(gas_utilizations), 2),
'min': min(gas_utilizations),
'max': max(gas_utilizations),
'trend': self._calculate_trend(gas_utilizations)
},
'network_health': {
'consistent_block_production': blocks_produced > 0,
'average_block_age': round(sum(block_ages) / len(block_ages), 2),
'health_score': self._calculate_health_score(monitoring_data)
}
}
def _calculate_trend(self, values: List[float]) -> str:
"""Calculate trend direction for a series of values"""
if len(values) < 2:
return 'insufficient_data'
first_half = values[:len(values)//2]
second_half = values[len(values)//2:]
first_avg = sum(first_half) / len(first_half)
second_avg = sum(second_half) / len(second_half)
change_pct = ((second_avg - first_avg) / first_avg) * 100 if first_avg > 0 else 0
if change_pct > 5:
return 'increasing'
elif change_pct < -5:
return 'decreasing'
else:
return 'stable'
def _calculate_health_score(self, monitoring_data: List[Dict]) -> float:
"""Calculate a health score for the rollup"""
score = 100.0
# Check for stale blocks
avg_block_age = sum(d['current_state']['block_age_seconds'] for d in monitoring_data) / len(monitoring_data)
if avg_block_age > 300: # 5 minutes
score -= 20
elif avg_block_age > 120: # 2 minutes
score -= 10
# Check gas utilization patterns
gas_utils = [d['current_state']['gas_utilization'] for d in monitoring_data]
avg_util = sum(gas_utils) / len(gas_utils)
if avg_util > 95: # Very high utilization
score -= 15
elif avg_util < 5: # Very low utilization (might indicate issues)
score -= 10
return max(0, score)
def compare_with_ethereum_l1(self, eth_l1_rpc_url: str = None) -> Dict[str, Any]:
"""Compare Mantle with Ethereum L1 characteristics"""
mantle_status = self.get_comprehensive_rollup_status()
comparison = {
'mantle_modular_l2': {
'type': 'Modular L2 Optimistic Rollup',
'consensus': 'Optimistic fraud proofs',
'finality': 'Optimistic → Proven (7 days)',
'block_time': '~2 seconds',
'gas_limit': mantle_status['current_state']['gas_limit'],
'gas_token': 'MNT',
'transaction_throughput': 'High',
'transaction_costs': 'Low'
},
'ethereum_l1': {
'type': 'Layer 1 Blockchain',
'consensus': 'Proof of Stake',
'finality': 'Probabilistic',
'block_time': '~12 seconds',
'gas_limit': '~30M gas',
'gas_token': 'ETH',
'transaction_throughput': 'Limited',
'transaction_costs': 'High'
},
'advantages_mantle': [
'Lower transaction costs with MNT token',
'Higher throughput via modular architecture',
'EVM compatibility',
'Inherits Ethereum security',
'EigenDA data availability efficiency',
'OP Stack foundation'
],
'advantages_l1': [
'No additional trust assumptions',
'Direct composability',
'Immediate finality',
'No bridge requirements',
'Maximum decentralization'
]
}
return comparison
def analyze_upgradeability_governance(self) -> Dict[str, Any]:
"""Analyze upgradeability and governance mechanisms"""
return {
'upgrade_mechanism': 'Governed Smart Contracts',
'governance_model': {
'type': 'Multi-signature or DAO governance',
'participants': [
'Core development team',
'Community stakeholders',
'Security auditors',
'Ecosystem partners'
]
},
'upgrade_process': {
'steps': [
'1. Proposal creation and review',
'2. Community discussion period',
'3. Technical evaluation',
'4. Governance voting',
'5. Implementation timeline',
'6. Staged rollout',
'7. Post-upgrade monitoring'
],
'timeframes': {
'discussion_period': '1-2 weeks',
'voting_period': '1 week',
'implementation_delay': '1-2 weeks',
'total_process': '4-6 weeks minimum'
}
},
'risk_mitigation': [
'Extensive testnet validation',
'Audit requirements',
'Emergency pause mechanisms',
'Gradual feature activation',
'Rollback procedures where possible'
],
'recent_upgrades': 'Check governance forum for latest information'
}
def get_bridge_integration_info(self) -> Dict[str, Any]:
"""Get information about bridge integrations and interoperability"""
return {
'canonical_bridge': {
'purpose': 'Official L1 ↔ L2 asset transfer',
'supported_assets': [
'ETH (bridged from Ethereum)',
'MNT (native gas token)',
'ERC-20 tokens',
'ERC-721 NFTs',
'ERC-1155 multi-tokens'
],
'security_model': 'Optimistic fraud proof validation'
},
'bridge_process': {
'deposits_l1_to_l2': {
'time': '~15 minutes',
'process': [
'Lock assets on L1',
'Wait for L1 confirmation',
'Automatic minting on L2',
'Assets available on L2'
]
},
'withdrawals_l2_to_l1': {
'time': '~7 days',
'process': [
'Burn assets on L2',
'Include in batch',
'Submit to L1',
'Challenge period (7 days)',
'Claim assets on L1'
]
}
},
'third_party_bridges': {
'availability': 'Multiple third-party bridge providers',
'considerations': [
'Different security models',
'Varying withdrawal times',
'Different supported assets',
'Additional trust assumptions'
]
}
}
# Usage examples
analyzer = MantleRollupInfoAnalyzer('https://api-mantle-mainnet.n.dwellir.com/YOUR_API_KEY')
# Get basic rollup information
rollup_info = analyzer.get_rollup_info()
print("Basic Rollup Info:", json.dumps(rollup_info, indent=2))
# Get comprehensive status
comprehensive_status = analyzer.get_comprehensive_rollup_status()
print(f"\nNetwork: {comprehensive_status['network_info']['name']}")
print(f"Chain ID: {comprehensive_status['network_info']['chain_id']}")
print(f"Latest Block: {comprehensive_status['current_state']['latest_block']}")
print(f"Gas Utilization: {comprehensive_status['current_state']['gas_utilization']}%")
# Analyze network type
analysis = comprehensive_status['analysis']
print(f"\nRollup Type: {analysis['rollup_type']}")
print(f"Environment: {analysis['environment']}")
print("Key Features:")
for feature in analysis['key_features']:
print(f" - {feature}")
# Monitor performance (short demo)
print("\nStarting performance monitoring...")
performance_data = analyzer.monitor_rollup_performance(duration_minutes=2)
print("Performance Analysis:")
print(f" Average block time: {performance_data['block_production']['average_block_time']}s")
print(f" Health score: {performance_data['network_health']['health_score']}/100")
# Compare with L1
comparison = analyzer.compare_with_ethereum_l1()
print("\nMantle Advantages:")
for advantage in comparison['advantages_mantle']:
print(f" - {advantage}")
# Governance analysis
governance = analyzer.analyze_upgradeability_governance()
print(f"\nGovernance Model: {governance['governance_model']['type']}")
print(f"Upgrade Process Duration: {governance['upgrade_process']['timeframes']['total_process']}")
# Bridge information
bridge_info = analyzer.get_bridge_integration_info()
print(f"\nBridge Withdrawal Time: {bridge_info['bridge_process']['withdrawals_l2_to_l1']['time']}")
print("Supported Assets:")
for asset in bridge_info['canonical_bridge']['supported_assets']:
print(f" - {asset}")
```
## Response Example
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"mode": "optimistic",
"chainId": "0x1388",
"batchHash": "0x...",
"stateRoot": "0x...",
"withdrawalRoot": "0x...",
"sequencer": "0x...",
"version": "1.0.0"
}
}
```
## Understanding Mantle Modular L2 Configuration
### Key Components
1. **Mode**: Operating mode of the rollup (optimistic)
2. **Chain ID**: Network identifier (5000 for mainnet, 5003 for testnet)
3. **State Root**: Root hash of the current state tree
4. **Batch Hash**: Hash of the current batch of transactions
5. **Sequencer**: Address of the transaction sequencing system
6. **Version**: Current version of the rollup implementation
### Modular L2 Architecture
- **Sequencing**: Optimistic transaction ordering and execution
- **Data Availability**: EigenDA integration for efficient data posting
- **EVM Compatibility**: Full compatibility with Ethereum Virtual Machine
- **Finality**: Fast L2 finality with 7-day challenge period for L1 finality
## Common Use Cases
### 1. Network Health Monitoring
```javascript
// Monitor rollup health and performance
async function monitorRollupHealth(analyzer) {
const healthCheck = async () => {
const status = await analyzer.getComprehensiveRollupStatus();
const alerts = [];
// Check block production
if (status.current_state.block_age_seconds > 300) {
alerts.push({
type: 'stale_blocks',
severity: 'warning',
message: 'Blocks are older than expected'
});
}
// Check gas utilization
if (status.current_state.gas_utilization > 95) {
alerts.push({
type: 'high_utilization',
severity: 'info',
message: 'Network experiencing high usage'
});
}
return {
status: alerts.length === 0 ? 'healthy' : 'warning',
alerts: alerts,
metrics: status.current_state
};
};
return healthCheck;
}
```
### 2. Integration Compatibility Check
```python
def check_integration_compatibility(analyzer):
"""Check if current rollup config is compatible with integration"""
status = analyzer.get_comprehensive_rollup_status()
rollup_info = status['rollup_config']
compatibility = {
'evm_compatible': True, # Modular L2 is fully EVM compatible
'supported_features': [
'Standard Ethereum transactions',
'Smart contract deployment',
'ERC token standards',
'Event emission and filtering',
'eth_call and eth_estimateGas',
'Debug and trace methods'
],
'limitations': [
'7-day withdrawal period for L1 finality',
'L1 data posting affects costs',
'Optimistic fraud proof mechanism'
],
'recommended_practices': [
'Use standard Ethereum tooling',
'Account for withdrawal delays',
'Monitor gas price fluctuations with MNT token',
'Leverage EigenDA data availability benefits'
]
}
return compatibility
```
### 3. Performance Benchmarking
```javascript
// Benchmark rollup performance characteristics
async function benchmarkRollupPerformance(analyzer) {
const benchmark = {
testDuration: '10 minutes',
metrics: {},
recommendations: []
};
// Monitor for performance data
const performanceData = await analyzer.monitorRollupPerformance(10);
benchmark.metrics = {
avgBlockTime: performanceData.block_production.average_block_time,
gasUtilization: performanceData.gas_utilization.average,
healthScore: performanceData.network_health.health_score
};
// Generate recommendations
if (benchmark.metrics.avgBlockTime > 5) {
benchmark.recommendations.push(
'Block times are longer than expected - monitor network congestion'
);
}
if (benchmark.metrics.gasUtilization > 80) {
benchmark.recommendations.push(
'High gas utilization - consider transaction timing optimization'
);
}
return benchmark;
}
```
## Integration Considerations
### Development
- **Tooling**: Use standard Ethereum development tools (Hardhat, Truffle, Remix)
- **RPC Compatibility**: Full JSON-RPC compatibility with additional rollup-specific methods
- **Gas Estimation**: Account for MNT gas token and EigenDA data costs
### Production Deployment
- **Security**: Leverage optimistic rollup security with fraud proofs
- **Monitoring**: Monitor both L2 state and L1 batch submission
- **Bridge Integration**: Plan for canonical bridge usage and withdrawal delays
### User Experience
- **Transaction Speed**: Fast L2 confirmation with 7-day L1 finality
- **Cost Optimization**: Benefit from MNT gas token and EigenDA efficiency
- **Bridge UX**: Clear communication about withdrawal timeframes
## Related Methods
- [`rollup_gasPrices`](/mantle/rollup_gasPrices) - Get gas price oracle data
- [`eth_chainId`](/mantle/eth_chainId) - Get network chain ID
- [`eth_getBlockByNumber`](/mantle/eth_getBlockByNumber) - Get block information
---
*Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Mantle documentation](/docs/mantle).*
---
## web3_clientVersion - Mantle RPC Method
# web3_clientVersion
Returns the current client version on Mantle.
## 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-mantle-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-mantle-mainnet.n.dwellir.com/YOUR_API_KEY');
const version = await provider.send('web3_clientVersion', []);
console.log('Client version:', version);
```
---
## web3_sha3 - Mantle RPC Method
# web3_sha3
Returns Keccak-256 (not standard SHA3-256) of the given data on Mantle.
## 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-mantle-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-mantle-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);
```
---
## eth_accounts - MegaETH RPC Method
# eth_accounts
Returns a list of addresses owned by the client on MegaETH.
> **Why MegaETH?** Build on the first real-time blockchain with sub-millisecond latency and 100,000+ TPS with sub-millisecond transaction streaming with 100,000+ sustained TPS and full EVM compatibility.
## 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 high-frequency DeFi developers, gaming studios, and teams building real-time 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-megaeth-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-megaeth-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-megaeth-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-megaeth-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-megaeth-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-megaeth-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 - MegaETH RPC Method
# eth_blockNumber
Returns the number of the most recent block on MegaETH.
> **Why MegaETH?** Build on the first real-time blockchain with sub-millisecond latency and 100,000+ TPS with sub-millisecond transaction streaming with 100,000+ sustained TPS and full EVM compatibility.
## When to Use This Method
`eth_blockNumber` is fundamental for high-frequency DeFi developers, gaming studios, and teams building real-time applications:
- **Syncing Applications** — Keep your dApp in sync with the latest MegaETH blockchain state
- **Transaction Monitoring** — Verify confirmations by comparing block numbers
- **Event Filtering** — Set the correct block range for querying logs on high-frequency trading, real-time gaming, instant payments, and latency-sensitive 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-megaeth-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-megaeth-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('MegaETH block:', blockNumber);
// Using ethers.js
const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockNumber = await provider.getBlockNumber();
console.log('MegaETH block:', blockNumber);
```
```python
def get_block_number():
response = requests.post(
'https://api-megaeth-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'MegaETH block: {block_number}')
# Using web3.py
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'))
print(f'MegaETH 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-megaeth-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("MegaETH block: %d\n", blockNumber)
}
```
## Common Use Cases
### 1. Block Confirmation Counter
Monitor transaction confirmations on MegaETH:
```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 MegaETH:
```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 MegaETH 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-megaeth-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 - MegaETH RPC Method
# eth_call
Executes a new message call immediately without creating a transaction on MegaETH. Used for reading smart contract state.
> **Why MegaETH?** Build on the first real-time blockchain with sub-millisecond latency and 100,000+ TPS with sub-millisecond transaction streaming with 100,000+ sustained TPS and full EVM compatibility.
## 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 trading, real-time gaming, instant payments, and latency-sensitive applications
- **Complex queries** - Execute multi-step contract logic
## Gas Limit Restriction
:::info Gas Limit on MegaETH
On MegaETH, `eth_call` requests are subject to a **maximum gas limit of 10,000,000**. This limit ensures optimal real-time performance across the network.
If your contract call requires more gas, consider:
- Breaking the operation into smaller calls
- Optimizing your smart contract logic
- Using view functions that return aggregated data
:::
## 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": "0x1F006CCc9Ac133035D8B9bb17E5739E6a17E8C51",
"data": "0x06fdde03"
},
"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 name() function
curl -X POST https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_call",
"params": [{
"to": "0x1F006CCc9Ac133035D8B9bb17E5739E6a17E8C51",
"data": "0x06fdde03"
}, "latest"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
// ERC20 ABI for common read functions
const ERC20_ABI = [
"function name() view returns (string)",
"function symbol() view returns (string)",
"function decimals() view returns (uint8)",
"function totalSupply() view returns (uint256)",
"function balanceOf(address owner) view returns (uint256)"
];
// Read token information
const tokenAddress = '0x1F006CCc9Ac133035D8B9bb17E5739E6a17E8C51';
const contract = new Contract(tokenAddress, ERC20_ABI, provider);
// Get token name
const name = await contract.name();
console.log('Token name:', name);
// Get token symbol and decimals
const symbol = await contract.symbol();
const decimals = await contract.decimals();
console.log(`Token: ${symbol}, Decimals: ${decimals}`);
```
```python
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'))
# ERC20 token ABI for common functions
ERC20_ABI = [
{
"constant": True,
"inputs": [],
"name": "name",
"outputs": [{"name": "", "type": "string"}],
"type": "function"
},
{
"constant": True,
"inputs": [],
"name": "symbol",
"outputs": [{"name": "", "type": "string"}],
"type": "function"
},
{
"constant": True,
"inputs": [],
"name": "decimals",
"outputs": [{"name": "", "type": "uint8"}],
"type": "function"
}
]
# Create contract instance
token_address = '0x1F006CCc9Ac133035D8B9bb17E5739E6a17E8C51'
contract = w3.eth.contract(address=token_address, abi=ERC20_ABI)
# Call name() function
name = contract.functions.name().call()
print(f'Token name: {name}')
# Get additional token info
symbol = contract.functions.symbol().call()
decimals = contract.functions.decimals().call()
print(f'Token: {symbol}, Decimals: {decimals}')
```
## 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 - MegaETH RPC Method
# eth_chainId
Returns the chain ID used for transaction signing on MegaETH.
> **Why MegaETH?** Build on the first real-time blockchain with sub-millisecond latency and 100,000+ TPS with sub-millisecond transaction streaming with 100,000+ sustained TPS and full EVM compatibility.
## 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-megaeth-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-megaeth-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-megaeth-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-megaeth-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_estimateGas - MegaETH RPC Method
# eth_estimateGas
Estimates the gas necessary to execute a transaction on MegaETH.
> **Why MegaETH?** Build on the first real-time blockchain with sub-millisecond latency and 100,000+ TPS with sub-millisecond transaction streaming with 100,000+ sustained TPS and full EVM compatibility.
## 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 trading, real-time gaming, instant payments, and latency-sensitive applications
## Gas Limit Restriction
:::info Gas Limit on MegaETH
On MegaETH, `eth_estimateGas` requests are subject to a **maximum gas limit of 10,000,000**. Complex transactions exceeding this limit should be optimized or restructured.
:::
For transactions requiring more than 10M gas:
```javascript
// Split complex operations into multiple transactions
const operation1 = await contract.step1();
await operation1.wait();
const operation2 = await contract.step2();
await operation2.wait();
```
## 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": "0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f",
"to": "0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f",
"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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_estimateGas",
"params": [{
"from": "0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f",
"to": "0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f",
"value": "0x1"
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-megaeth-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-megaeth-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('0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f', 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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
toAddress := common.HexToAddress("0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f")
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 - MegaETH RPC Method
# eth_feeHistory
Returns historical gas information on MegaETH 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 trading, real-time gaming, instant payments, and latency-sensitive applications
## Block Range Limit
:::info Block Range Limit
On MegaETH, `eth_feeHistory` queries are subject to a **maximum block range of 10,000 blocks**. This means the `blockCount` parameter cannot exceed 10,000 blocks per request.
:::
For querying larger block ranges, split your requests into batches:
```javascript
// Example: Query in 10,000-block batches
const MAX_RANGE = 10000;
const totalBlocks = 50000;
const newestBlock = await provider.getBlockNumber();
const allFeeHistory = [];
for (let i = 0; i < totalBlocks; i += MAX_RANGE) {
const blockCount = Math.min(MAX_RANGE, totalBlocks - i);
const feeHistory = await provider.send('eth_feeHistory', [
blockCount,
newestBlock - i,
[]
]);
allFeeHistory.push(feeHistory);
}
```
## 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-megaeth-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-megaeth-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-megaeth-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 - MegaETH RPC Method
# eth_gasPrice
Returns the current gas price on MegaETH in wei.
> **Why MegaETH?** Build on the first real-time blockchain with sub-millisecond latency and 100,000+ TPS with sub-millisecond transaction streaming with 100,000+ sustained TPS and full EVM compatibility.
## 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 trading, real-time gaming, instant payments, and latency-sensitive 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-megaeth-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-megaeth-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-megaeth-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-megaeth-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 - MegaETH RPC Method
# eth_getBalance
Returns the balance of a given address on MegaETH.
> **Why MegaETH?** Build on the first real-time blockchain with sub-millisecond latency and 100,000+ TPS with sub-millisecond transaction streaming with 100,000+ sustained TPS and full EVM compatibility.
## 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 trading, real-time gaming, instant payments, and latency-sensitive 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": [
"0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f",
"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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const address = '0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f';
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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'))
address = '0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f'
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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
address := common.HexToAddress("0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f")
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 - MegaETH RPC Method
# eth_getBlockByHash
Returns information about a block by hash on MegaETH.
> **Why MegaETH?** Build on the first real-time blockchain with sub-millisecond latency and 100,000+ TPS with sub-millisecond transaction streaming with 100,000+ sustained TPS and full EVM compatibility.
## 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 trading, real-time gaming, instant payments, and latency-sensitive applications
- **Deterministic queries** - Get consistent block data regardless of chain state
## Full Block Restriction
:::warning Full Block Queries Disabled
On MegaETH, the `fullTransactionObjects` parameter is **disabled** for performance optimization. The method always returns transaction hashes instead of full transaction objects.
To get full transaction details, fetch them individually:
```javascript
// Get block with transaction hashes
const block = await provider.getBlock(blockHash, false);
// Fetch full transaction details as needed
for (const txHash of block.transactions) {
const tx = await provider.getTransaction(txHash);
console.log('Transaction:', tx);
}
```
:::
## 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": [
"0xe2ae73c07a531471127f7a4e814d7d1e8dbd3def6152c60e2e0284024798056e",
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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByHash",
"params": [
"0xe2ae73c07a531471127f7a4e814d7d1e8dbd3def6152c60e2e0284024798056e",
false
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0xe2ae73c07a531471127f7a4e814d7d1e8dbd3def6152c60e2e0284024798056e';
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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'))
block_hash = '0xe2ae73c07a531471127f7a4e814d7d1e8dbd3def6152c60e2e0284024798056e'
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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
blockHash := common.HexToHash("0xe2ae73c07a531471127f7a4e814d7d1e8dbd3def6152c60e2e0284024798056e")
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 - MegaETH RPC Method
# eth_getBlockByNumber
Returns information about a block by block number on MegaETH.
> **Why MegaETH?** Build on the first real-time blockchain with sub-millisecond latency and 100,000+ TPS with sub-millisecond transaction streaming with 100,000+ sustained TPS and full EVM compatibility.
## 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 trading, real-time gaming, instant payments, and latency-sensitive applications
- **Timestamp verification** - Get block timestamps for time-based logic
## Full Block Restriction
:::warning Full Block Queries Disabled
On MegaETH, the `fullTransactionObjects` parameter is **disabled** for performance optimization. The method always returns transaction hashes instead of full transaction objects.
To get full transaction details, fetch them individually:
```javascript
// Get block with transaction hashes
const block = await provider.getBlock('latest', false);
// Fetch full transaction details as needed
for (const txHash of block.transactions) {
const tx = await provider.getTransaction(txHash);
console.log('Transaction:', tx);
}
```
:::
## 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": "0xe2ae73c07a531471127f7a4e814d7d1e8dbd3def6152c60e2e0284024798056e",
"parentHash": "0x...",
"timestamp": "0x64d8f6d0",
"gasUsed": "0x1234",
"gasLimit": "0x1c9c380",
"transactions": [],
"baseFeePerGas": "0x5f5e100"
}
}
```
## Code Examples
```bash
curl -X POST https://api-megaeth-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-megaeth-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-megaeth-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-megaeth-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 - MegaETH RPC Method
# eth_getCode
Returns the bytecode at a given address on MegaETH.
> **Why MegaETH?** Build on the first real-time blockchain with sub-millisecond latency and 100,000+ TPS with sub-millisecond transaction streaming with 100,000+ sustained TPS and full EVM compatibility.
## 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 trading, real-time gaming, instant payments, and latency-sensitive 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": [
"0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f",
"latest"
],
"id": 1
}
```
## Returns
| Type | Description |
|------|-------------|
| `DATA` | Contract bytecode or `0x` if EOA |
## Code Examples
```bash
curl -X POST https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getCode",
"params": [
"0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const address = '0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f';
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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'))
address = '0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f'
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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
address := common.HexToAddress("0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f")
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 - MegaETH RPC Method
# eth_getFilterChanges
Polling method for a filter on MegaETH, 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 trading, real-time gaming, instant payments, and latency-sensitive 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-megaeth-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-megaeth-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 - MegaETH RPC Method
# eth_getFilterLogs
Returns an array of all logs matching filter with given ID on MegaETH.
## Use Cases
- **Historical queries** - Get all matching logs for a filter
- **Full event history** - Retrieve complete event data for high-frequency trading, real-time gaming, instant payments, and latency-sensitive 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-megaeth-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-megaeth-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 - MegaETH RPC Method
# eth_getLogs
Returns an array of all logs matching a given filter object on MegaETH.
> **Why MegaETH?** Build on the first real-time blockchain with sub-millisecond latency and 100,000+ TPS with sub-millisecond transaction streaming with 100,000+ sustained TPS and full EVM compatibility.
## Use Cases
The `eth_getLogs` method is essential for:
- **Event indexing** - Track contract events for high-frequency trading, real-time gaming, instant payments, and latency-sensitive 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": "0x70f337",
"toBlock": "0x70f341",
"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": "0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."],
"data": "0x...",
"blockNumber": "0x5BAD55",
"transactionHash": "0x...",
"logIndex": "0x0"
}]
}
```
## Code Examples
```bash
# Query ERC20 Transfer events
curl -X POST https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getLogs",
"params": [{
"fromBlock": "0x70f337",
"toBlock": "0x70f341",
"address": "0x4200000000000000000000000000000000000006",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
// ERC20 ABI for Transfer event
const ERC20_ABI = [
"event Transfer(address indexed from, address indexed to, uint256 value)"
];
const tokenAddress = '0x4200000000000000000000000000000000000006';
const contract = new Contract(tokenAddress, ERC20_ABI, provider);
// Query Transfer events in block range
const fromBlock = 7402295; // 0x70f337
const toBlock = 7402305; // 0x70f341
const filter = contract.filters.Transfer();
const logs = await contract.queryFilter(filter, fromBlock, toBlock);
console.log(`Found ${logs.length} Transfer events`);
logs.forEach(log => {
console.log(`From: ${log.args.from}`);
console.log(`To: ${log.args.to}`);
console.log(`Amount: ${log.args.value.toString()}`);
});
```
```python
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'))
# Query Transfer events
filter_params = {
'fromBlock': 0x70f337,
'toBlock': 0x70f341,
'address': '0x4200000000000000000000000000000000000006',
'topics': ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef']
}
logs = w3.eth.get_logs(filter_params)
print(f'Found {len(logs)} Transfer events')
for log in logs:
# Decode Transfer event (from, to, value)
from_address = '0x' + log['topics'][1].hex()[-40:]
to_address = '0x' + log['topics'][2].hex()[-40:]
value = int(log['data'].hex(), 16)
print(f'From: {from_address}')
print(f'To: {to_address}')
print(f'Value: {value}')
```
## 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 - MegaETH RPC Method
# eth_getStorageAt
Returns the value from a storage position at a given address on MegaETH.
## Use Cases
- **Contract analysis** - Read raw storage values
- **State verification** - Verify contract state
- **Security auditing** - Analyze storage layout for high-frequency trading, real-time gaming, instant payments, and latency-sensitive 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": [
"0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f",
"0x0",
"latest"
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getStorageAt",
"params": [
"0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f",
"0x0",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const address = '0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f';
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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'))
address = '0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f'
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 - MegaETH RPC Method
# eth_getTransactionByHash
Returns the information about a transaction by transaction hash on MegaETH.
> **Why MegaETH?** Build on the first real-time blockchain with sub-millisecond latency and 100,000+ TPS with sub-millisecond transaction streaming with 100,000+ sustained TPS and full EVM compatibility.
## 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 trading, real-time gaming, instant payments, and latency-sensitive 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": ["0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692"],
"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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionByHash",
"params": ["0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const txHash = '0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692';
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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692'
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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692")
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 - MegaETH RPC Method
# eth_getTransactionCount
Returns the number of transactions sent from an address on MegaETH (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 trading, real-time gaming, instant payments, and latency-sensitive 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": [
"0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f",
"latest"
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [
"0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const address = '0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f';
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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'))
address = '0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f'
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 - MegaETH RPC Method
# eth_getTransactionReceipt
Returns the receipt of a transaction by transaction hash on MegaETH. Receipt is only available for mined transactions.
> **Why MegaETH?** Build on the first real-time blockchain with sub-millisecond latency and 100,000+ TPS with sub-millisecond transaction streaming with 100,000+ sustained TPS and full EVM compatibility.
## 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 trading, real-time gaming, instant payments, and latency-sensitive applications
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `transactionHash` | `DATA` | Yes | 32-byte transaction hash |
## Request
```json
{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692"],
"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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const txHash = '0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692';
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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692'
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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692")
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 - MegaETH RPC Method
# eth_maxPriorityFeePerGas
Returns the current recommended priority fee per gas on MegaETH 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 trading, real-time gaming, instant payments, and latency-sensitive 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-megaeth-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-megaeth-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-megaeth-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_newBlockFilter - MegaETH RPC Method
# eth_newBlockFilter
Creates a filter on MegaETH 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-megaeth-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-megaeth-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 - MegaETH RPC Method
# eth_newFilter
Creates a filter object on MegaETH to notify when state changes (logs).
## Use Cases
- **Event monitoring** - Subscribe to contract events
- **Real-time updates** - Track events for high-frequency trading, real-time gaming, instant payments, and latency-sensitive 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": "0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
}],
"id": 1
}
```
## Returns
| Type | Description |
|------|-------------|
| `QUANTITY` | Filter ID |
## Code Examples
```bash
curl -X POST https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_newFilter",
"params": [{
"fromBlock": "latest",
"address": "0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f"
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
// Create filter
const filterId = await provider.send('eth_newFilter', [{
fromBlock: 'latest',
address: '0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f',
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 - MegaETH RPC Method
# eth_newPendingTransactionFilter
Creates a filter on MegaETH 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-megaeth-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-megaeth-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_sendRawTransaction - MegaETH RPC Method
# eth_sendRawTransaction
Submits a pre-signed transaction for broadcast to MegaETH.
> **Why MegaETH?** Build on the first real-time blockchain with sub-millisecond latency and 100,000+ TPS with sub-millisecond transaction streaming with 100,000+ sustained TPS and full EVM compatibility.
## 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 trading, real-time gaming, instant payments, and latency-sensitive 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-megaeth-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-megaeth-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-megaeth-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-megaeth-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("0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f")
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 - MegaETH RPC Method
# eth_syncing
Returns syncing status of MegaETH 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-megaeth-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-megaeth-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 - MegaETH RPC Method
# eth_uninstallFilter
Uninstalls a filter on MegaETH. 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-megaeth-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-megaeth-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
---
## MegaETH - The First Real-Time Blockchain
# MegaETH - Build on the First Real-Time Blockchain
## Why Build on MegaETH?
MegaETH is the world's first real-time blockchain, delivering unprecedented performance while maintaining full EVM compatibility:
### ⚡ **Real-Time Performance**
- **Sub-millisecond latency** - Transaction streaming in real-time, not batches
- **100,000+ TPS sustained** - Orders of magnitude faster than traditional L2s
- **0.01 second block time** - Near-instant transaction finality
### 🛡️ **Battle-Tested Security**
- **Ethereum-secured** - Inherits Ethereum's L1 security guarantees
- **Backed by Vitalik Buterin** - Co-founded by Ethereum's creator
- **Full EVM compatibility** - All existing Ethereum tools work seamlessly
### 🚀 **Ideal for High-Frequency Applications**
- **High-frequency DeFi** - Enable latency-sensitive trading strategies
- **Gaming & Real-Time Apps** - Build truly responsive onchain experiences
- **Instant UX** - Deliver web2-like responsiveness with web3 security
## Quick Start with MegaETH
Connect to MegaETH in seconds with Dwellir's optimized endpoints:
### Installation & Setup
```javascript
// Connect to MegaETH mainnet
const provider = new JsonRpcProvider(
'https://api-megaeth-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 MegaETH mainnet
const web3 = new Web3(
'https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'
);
// Get chain ID to verify connection
const chainId = await web3.eth.getChainId();
console.log('Connected to MegaETH:', chainId === 4326);
// Get gas price for optimal transaction pricing
const gasPrice = await web3.eth.getGasPrice();
console.log('Current gas price:', gasPrice);
```
```typescript
// Define MegaETH chain
const megaeth = defineChain({
id: 4326,
name: 'MegaETH',
nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
rpcUrls: {
default: { http: ['https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'] },
},
blockExplorers: {
default: { name: 'Blockscout', url: 'https://megaeth.blockscout.com' },
},
});
// Create MegaETH client
const client = createPublicClient({
chain: megaeth,
transport: http('https://api-megaeth-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
4326
Mainnet
Block Time
0.01 seconds
Real-time
Gas Token
ETH
Native token
RPC Standard
Ethereum
JSON-RPC 2.0
## JSON-RPC API Reference
MegaETH supports a subset of the [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/) optimized for real-time performance.
:::info Method Availability
MegaETH implements core Ethereum JSON-RPC methods with some modifications for performance:
- **Debug methods** are not available (debug_*, trace_*)
- **Full block queries** are disabled for `eth_getBlockByHash` and `eth_getBlockByNumber`
- **Gas limits** apply to certain methods (10,000,000 gas for `eth_call`, `eth_createAccessList`, `eth_estimateGas`)
- **Block range limits** apply to `eth_feeHistory` (maximum 10,000 blocks)
:::
## Common Integration Patterns
### ⚡ Real-Time Transaction Streaming
Leverage MegaETH's real-time capabilities for instant transaction updates:
```javascript
// Subscribe to pending transactions via WebSocket
const wsProvider = new ethers.WebSocketProvider(
'wss://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'
);
// Watch for new blocks in real-time (every 0.01s)
wsProvider.on('block', async (blockNumber) => {
console.log('New block:', blockNumber);
const block = await wsProvider.getBlock(blockNumber);
console.log('Block timestamp:', block.timestamp);
});
// Watch for specific transaction confirmations
async function streamTransaction(txHash) {
const receipt = await wsProvider.waitForTransaction(txHash, 1);
console.log('Transaction confirmed in:', receipt.blockNumber);
return receipt;
}
```
### 💰 Gas Optimization
Optimize gas costs on MegaETH:
```javascript
// Get current fee data
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 MegaETH's fast block times:
```javascript
// Query recent events (fast with 0.01s blocks)
async function getRecentEvents(contract, eventName, blocksBack = 1000) {
const latestBlock = await provider.getBlockNumber();
const fromBlock = latestBlock - blocksBack;
const filter = contract.filters[eventName]();
const events = await contract.queryFilter(filter, fromBlock, latestBlock);
return events;
}
```
## Performance Best Practices
### 1. **WebSocket for Real-Time Updates**
Use WebSockets to leverage MegaETH's real-time streaming capabilities:
```javascript
const wsProvider = new ethers.WebSocketProvider(
'wss://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'
);
// Subscribe to new blocks (every 0.01s)
wsProvider.on('block', (blockNumber) => {
console.log('New block:', blockNumber);
});
// Handle reconnection
wsProvider.on('error', () => {
console.log('WebSocket error, reconnecting...');
});
```
### 2. **Connection Pooling**
Reuse provider instances to minimize connection overhead:
```javascript
// Singleton pattern for provider
class MegaETHProvider {
static instance = null;
static getInstance() {
if (!this.instance) {
this.instance = new JsonRpcProvider(
'https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'
);
}
return this.instance;
}
}
```
### 3. **Respect Gas Limits**
MegaETH enforces a 10,000,000 gas limit for certain methods:
```javascript
// When calling contracts, stay within gas limits
const result = await provider.call({
to: contractAddress,
data: calldata,
// MegaETH enforces 10M gas limit
gasLimit: 10000000
});
```
## Troubleshooting Common Issues
### Error: "Gas limit exceeded"
MegaETH limits certain methods to 10,000,000 gas:
```javascript
// Split large queries into smaller batches
async function batchCall(contract, method, args, batchSize = 100) {
const results = [];
for (let i = 0; i < args.length; i += batchSize) {
const batch = args.slice(i, i + batchSize);
const result = await contract[method](batch);
results.push(...result);
}
return results;
}
```
### Error: "Full block queries disabled"
Use the standard block query format without transaction details:
```javascript
// Don't request full transaction objects
const block = await provider.getBlock(blockNumber, false);
// If you need transaction details, fetch them separately
for (const txHash of block.transactions) {
const tx = await provider.getTransaction(txHash);
console.log('Transaction:', tx);
}
```
### Error: "Block range too large"
For `eth_feeHistory`, limit your range to 10,000 blocks:
```javascript
// Query fee history in 10k block batches
async function getFeeHistory(blockCount, newestBlock) {
const maxRange = 10000;
if (blockCount > maxRange) {
// Split into multiple requests
const batches = Math.ceil(blockCount / maxRange);
const results = [];
for (let i = 0; i < batches; i++) {
const batchSize = Math.min(maxRange, blockCount - (i * maxRange));
const batchResult = await provider.send('eth_feeHistory', [
batchSize,
newestBlock - (i * maxRange),
[]
]);
results.push(batchResult);
}
return results;
}
return provider.send('eth_feeHistory', [blockCount, newestBlock, []]);
}
```
## Smoke Tests
### Test Connection with cURL
```bash
# Test MegaETH mainnet
curl -X POST https://api-megaeth-mainnet.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-megaeth-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 4326n
```
### Test with Web3.py
```python
from web3 import Web3
# Test connection
web3 = Web3(Web3.HTTPProvider(
'https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'
))
print('Connected:', web3.is_connected())
print('Chain ID:', web3.eth.chain_id) # Should be 4326
print('Block number:', web3.eth.block_number)
```
## Migration Guide
### From Other EVM Chains
MegaETH is fully EVM-compatible, making migration straightforward:
```javascript
// Before (Ethereum/other L2)
const provider = new JsonRpcProvider('https://eth-rpc.example.com');
// After (MegaETH)
const provider = new JsonRpcProvider(
'https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'
);
// ✅ Smart contracts work identically
// ✅ Same tooling and libraries
// ⚠️ Different chain ID (4326)
// ⚠️ Some debug methods unavailable
// ⚠️ Gas limits apply (10M for call/estimateGas)
// ⚠️ Full block queries disabled
```
## Resources & Tools
### Official Resources
- [MegaETH Documentation](https://docs.megaeth.com/)
- [MegaETH Website](https://www.megaeth.com)
- [MegaETH Block Explorer](https://megaeth.blockscout.com/)
### Developer Tools
- [Hardhat](https://hardhat.org/) - Full EVM compatibility
- [Foundry](https://getfoundry.sh/) - Fast Solidity testing
- [Truffle](https://trufflesuite.com/) - Development framework
### Need Help?
- 📧 **Email**: support@dwellir.com
- 📚 **Docs**: You're here!
- 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com)
---
*Start building on MegaETH with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## net_listening - MegaETH RPC Method
# net_listening
Returns `true` if client is actively listening for network connections on MegaETH.
## 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-megaeth-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-megaeth-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 - MegaETH RPC Method
# net_peerCount
Returns number of peers currently connected to MegaETH 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-megaeth-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-megaeth-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 - MegaETH RPC Method
# net_version
Returns the current network ID on MegaETH.
## 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-megaeth-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-megaeth-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 - MegaETH RPC Method
# trace_block
Returns traces for all transactions in a block on MegaETH.
:::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 high-frequency trading, real-time gaming, instant payments, and latency-sensitive applications
## 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-megaeth-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-megaeth-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-megaeth-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 - MegaETH RPC Method
# trace_call
Traces a call without creating a transaction on MegaETH, 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 high-frequency trading, real-time gaming, instant payments, and latency-sensitive applications
## 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": "0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f",
"data": "0x70a082310000000000000000000000000E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f"
},
["trace"],
"latest"
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "trace_call",
"params": [
{"to": "0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f", "data": "0x70a082310000000000000000000000000E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f"},
["trace"],
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const result = await provider.send('trace_call', [
{
to: '0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f',
data: '0x70a082310000000000000000000000000E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f'
},
['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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'))
result = w3.provider.make_request('trace_call', [
{
'to': '0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f',
'data': '0x70a082310000000000000000000000000E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f'
},
['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 - MegaETH RPC Method
# trace_callMany
Traces multiple calls in sequence on MegaETH, 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 high-frequency trading, real-time gaming, instant payments, and latency-sensitive applications
## 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": "0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f", "data": "0x70a082310000000000000000000000000E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f"}, ["trace"]],
[{"to": "0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f", "data": "0x18160ddd"}, ["trace"]]
],
"latest"
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "trace_callMany",
"params": [
[
[{"to": "0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f", "data": "0x70a082310000000000000000000000000E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f"}, ["trace"]],
[{"to": "0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f", "data": "0x18160ddd"}, ["trace"]]
],
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const results = await provider.send('trace_callMany', [
[
[{ to: '0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f', data: '0x70a082310000000000000000000000000E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f' }, ['trace']],
[{ to: '0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f', 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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'))
results = w3.provider.make_request('trace_callMany', [
[
[{'to': '0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f', 'data': '0x70a082310000000000000000000000000E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f'}, ['trace']],
[{'to': '0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f', '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 - MegaETH RPC Method
# trace_filter
Returns traces matching a filter on MegaETH.
:::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 high-frequency trading, real-time gaming, instant payments, and latency-sensitive applications
## 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": ["0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f"],
"count": 10
}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-megaeth-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": ["0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f"],
"count": 10
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const traces = await provider.send('trace_filter', [{
fromBlock: 'latest',
toBlock: 'latest',
toAddress: ['0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f'],
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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'))
traces = w3.provider.make_request('trace_filter', [{
'fromBlock': 'latest',
'toBlock': 'latest',
'toAddress': ['0x0E0f4Dd25ae8AB20E1583D9E8EDFf319A88e1d3f'],
'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 - MegaETH RPC Method
# trace_get
Returns a trace at a specific position within a transaction on MegaETH.
:::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 high-frequency trading, real-time gaming, instant payments, and latency-sensitive applications
## 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": ["0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692", ["0x0"]],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "trace_get",
"params": ["0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692", ["0x0"]],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const trace = await provider.send('trace_get', [
'0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692',
['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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'))
trace = w3.provider.make_request('trace_get', [
'0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692',
['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 - MegaETH RPC Method
# trace_replayBlockTransactions
Replays all transactions in a block on MegaETH 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 high-frequency trading, real-time gaming, instant payments, and latency-sensitive applications
## 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-megaeth-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-megaeth-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-megaeth-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 - MegaETH RPC Method
# trace_replayTransaction
Replays a transaction on MegaETH 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 high-frequency trading, real-time gaming, instant payments, and latency-sensitive applications
## 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": ["0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692", ["trace"]],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "trace_replayTransaction",
"params": ["0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692", ["trace"]],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const result = await provider.send('trace_replayTransaction', [
'0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692',
['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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'))
result = w3.provider.make_request('trace_replayTransaction', [
'0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692',
['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 - MegaETH RPC Method
# trace_transaction
Returns all traces for a specific transaction on MegaETH.
:::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 high-frequency trading, real-time gaming, instant payments, and latency-sensitive applications
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `txHash` | `DATA` | Yes | 32-byte transaction hash |
## Request
```json
{
"jsonrpc": "2.0",
"method": "trace_transaction",
"params": ["0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692"],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "trace_transaction",
"params": ["0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const traces = await provider.send('trace_transaction', [
'0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692'
]);
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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY'))
traces = w3.provider.make_request('trace_transaction', [
'0xed92c2e964d7916f91fbc203f983bb89e15db600c1278d860812fe5c83b06692'
])
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 - MegaETH RPC Method
# web3_clientVersion
Returns the current client version on MegaETH.
## 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-megaeth-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-megaeth-mainnet.n.dwellir.com/YOUR_API_KEY');
const version = await provider.send('web3_clientVersion', []);
console.log('Client version:', version);
```
---
## web3_sha3 - MegaETH RPC Method
# web3_sha3
Returns Keccak-256 (not standard SHA3-256) of the given data on MegaETH.
## 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-megaeth-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-megaeth-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);
```
---
## Migrate from Blast API to Dwellir - Better Than Alchemy
# Migrate from Blast API to Dwellir
## 🚨 Blast API Acquired by Alchemy - Service Ending October 31st
Blast API has been **acquired by Alchemy** and is discontinuing service on **October 31st**. While Alchemy wants you to migrate to their platform, **there's a better choice**.
### ⚡ Why Dwellir Beats Alchemy
Before you follow the crowd to Alchemy, consider what you're really getting:
## Dwellir vs Alchemy: The Clear Winner
| Feature | Alchemy | Dwellir |
|---------|---------|---------|
| **Pricing Model** | Confusing compute units 🤯 | **Simple requests-based** ✅ |
| **Actual Cost** | $199-499/mo + overages | **50-70% cheaper** ✅ |
| **Network Coverage** | ~30 networks | **150+ networks** ✅ |
| **No Compute Units** | ❌ Complex CU calculations | **✅ Simple, transparent pricing** |
| **Rate Limits** | CU-based throttling | **Generous & predictable** ✅ |
| **Setup Complexity** | Multiple configs needed | **One API key, done** ✅ |
### 🎯 The Compute Units Problem
**Alchemy's confusing compute unit (CU) system** means:
- Different methods cost different CUs (eth_call = 26 CUs, eth_blockNumber = 10 CUs)
- You can't predict your actual costs
- Complex calculations just to estimate usage
- Surprise overages when CUs run out
**With Dwellir**: 1 request = 1 request. Simple. Transparent. Predictable.
## 🤔 Why Blast Users Are Choosing Dwellir Over Alchemy
### Real Developer Feedback
> "Good pricing, high uptime, and most importantly, you have a great response and resolution time." - *Hypernative*
> "We are very impressed with you. You are fast at deploying new nodes and we haven't experienced any downtime yet with you" - *Token Terminal*
> "Dwellir has significantly simplified our complex multi-chain coverage, enabling us to focus on our product instead of infrastructure management. Their team is always responsive and ready to help, making the experience even better." - *SQD*
### The Numbers Don't Lie
- **3x faster** average response times than Alchemy
- **80% cheaper** for high-volume applications
- **150+ networks** vs Alchemy's limited selection
- **No compute units** = No surprise bills
### Simple Example: The True Cost
**Alchemy's Hidden Math:**
- 1 eth_getLogs call = 75 CUs
- 1 eth_call = 26 CUs
- 1 eth_getBalance = 19 CUs
- Running out of CUs? Service stops or pay 10x more
**Dwellir's Transparency:**
- Every call = 1 response
- No complex calculations
- No service interruptions
## Quick Migration Guide
### Step 1: Create Your Dwellir Account
Get started in under 60 seconds:
1. **Sign up** at [dashboard.dwellir.com/register](https://dashboard.dwellir.com/register)
2. **Verify your email**
3. **Get your API key** instantly
### Step 2: Update Your RPC Endpoints
Migration is as simple as changing your RPC URL. Here's how:
```javascript
// Blast API (OLD)
const OLD_RPC = "https://eth-mainnet.blastapi.io/YOUR_PROJECT_ID";
// Dwellir (NEW) - Direct replacement
const NEW_RPC = "https://api-eth-mainnet-archive.n.dwellir.com/YOUR_API_KEY";
// That's it! Your existing code continues to work
const provider = new ethers.JsonRpcProvider(NEW_RPC);
```
```javascript
// Blast API (OLD)
const OLD_RPC = "https://base-mainnet.blastapi.io/YOUR_PROJECT_ID";
// Dwellir (NEW)
const NEW_RPC = "https://api-base-mainnet-archive.n.dwellir.com/YOUR_API_KEY";
```
```javascript
// Blast API (OLD)
const OLD_RPC = "https://arbitrum-one.blastapi.io/YOUR_PROJECT_ID";
// Dwellir (NEW)
const NEW_RPC = "https://api-arbitrum-mainnet-archive.n.dwellir.com/YOUR_API_KEY";
```
```javascript
// Blast API (OLD)
const OLD_RPC = "https://polygon-mainnet.blastapi.io/YOUR_PROJECT_ID";
// Dwellir (NEW)
const NEW_RPC = "https://api-polygon-mainnet-archive.n.dwellir.com/YOUR_API_KEY";
```
### Step 3: Test Your Integration
Before fully migrating, test Dwellir's endpoints:
```bash
# Test Ethereum endpoint
curl -X POST https://api-eth-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}'
# Response
{"jsonrpc":"2.0","id":1,"result":"0x1234567"}
```
### Step 4: Implement Zero-Downtime Migration
Use our recommended dual-provider pattern for seamless migration:
```javascript
// Gradual migration with fallback
class RPCProvider {
constructor() {
this.primary = "https://api-eth-mainnet-archive.n.dwellir.com/YOUR_API_KEY";
this.fallback = "https://eth-mainnet.blastapi.io/YOUR_PROJECT_ID"; // Keep until Oct 31
}
async request(method, params) {
try {
// Try Dwellir first
return await fetch(this.primary, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', method, params, id: 1 })
});
} catch (error) {
// Fallback to Blast (remove after migration)
console.warn('Falling back to Blast API');
return await fetch(this.fallback, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ jsonrpc: '2.0', method, params, id: 1 })
});
}
}
}
```
## Network Endpoint Mapping
Here's a complete mapping of Blast endpoints to Dwellir:
| Network | Blast Endpoint | Dwellir Endpoint |
|---------|---------------|------------------|
| Ethereum | `eth-mainnet.blastapi.io` | `api-eth-mainnet-archive.n.dwellir.com` |
| Base | `base-mainnet.blastapi.io` | `api-base-mainnet-archive.n.dwellir.com` |
| Arbitrum | `arbitrum-one.blastapi.io` | `api-arbitrum-mainnet-archive.n.dwellir.com` |
| Optimism | `optimism-mainnet.blastapi.io` | `api-optimism-mainnet-archive.n.dwellir.com` |
| Polygon | `polygon-mainnet.blastapi.io` | `api-polygon-mainnet-archive.n.dwellir.com` |
| BSC | `bsc-mainnet.blastapi.io` | `api-bsc-mainnet-archive.n.dwellir.com` |
| Avalanche | `ava-mainnet.blastapi.io` | `api-avalanche-mainnet-archive.n.dwellir.com` |
| Fantom | `fantom-mainnet.blastapi.io` | `api-fantom-mainnet-archive.n.dwellir.com` |
**Plus 140+ additional networks** not available on Blast, including:
- Sui
- Aptos
- Bittensor
- IoTeX
- Celo
- Tron
- And many more!
## Enhanced Features with Dwellir
### 1. Superior Performance
```javascript
const startTime = Date.now();
const response = await provider.getBlockNumber();
console.log(`Response time: ${Date.now() - startTime}ms`); // Typically <100ms
```
### 2. Advanced Debug APIs
Access powerful debugging capabilities not available on Blast:
```javascript
// Debug transaction execution
const trace = await provider.send('debug_traceTransaction', [
'0xhash',
{ tracer: 'callTracer' }
]);
// Trace block execution
const blockTrace = await provider.send('debug_traceBlockByNumber', [
'latest',
{ tracer: 'prestateTracer' }
]);
```
### 3. WebSocket Support
Real-time event streaming for all networks:
```javascript
// WebSocket connection for real-time data
const ws = new WebSocket('wss://api-eth-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
// Subscribe to new blocks
ws.send(JSON.stringify({
jsonrpc: '2.0',
method: 'eth_subscribe',
params: ['newHeads'],
id: 1
}));
```
### 4. Batch Request Optimization
Send multiple requests efficiently:
```javascript
// Batch multiple RPC calls
const batch = [
{ jsonrpc: '2.0', method: 'eth_blockNumber', params: [], id: 1 },
{ jsonrpc: '2.0', method: 'eth_gasPrice', params: [], id: 2 },
{ jsonrpc: '2.0', method: 'net_version', params: [], id: 3 }
];
const response = await fetch('https://api-eth-mainnet-archive.n.dwellir.com/YOUR_API_KEY', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(batch)
});
```
## Migration Checklist
Ensure a smooth transition with this checklist:
- [ ] **Create Dwellir account** at [dashboard.dwellir.com](https://dashboard.dwellir.com/register)
- [ ] **Get API keys** for all required networks
- [ ] **Update RPC endpoints** in your application configuration
- [ ] **Test endpoints** with your existing code
- [ ] **Monitor performance** using Dwellir dashboard
- [ ] **Update environment variables** in production
- [ ] **Implement fallback logic** (optional but recommended until Oct 31)
- [ ] **Remove Blast dependencies** after successful migration
- [ ] **Update documentation** for your team
## Exclusive Migration Benefits
### 🎁 Special Offers for Blast Users
As a Blast API user migrating to Dwellir, you'll receive:
1. **50% discount** on your first 3 months (use code: BLA1TOFF50)
2. **Priority migration support** from our engineering team
3. **Free architecture review** to optimize your setup
4. **Dedicated account manager** for enterprise accounts
### 🚀 High-Volume Special: $1 per Million
**For customers doing 1+ billion requests/month**: Get our special rate of just **$1 per million requests**. That's up to 90% cheaper than Alchemy!
## Common Migration Questions
### Q: Is Dwellir compatible with my existing code?
**A:** Yes! Dwellir is 100% compatible with standard JSON-RPC. Simply replace your Blast endpoint URL with Dwellir's, and your code continues to work without modifications.
### Q: How long does migration take?
**A:** Most users complete migration in **under 10 minutes**. Large enterprises with complex setups typically migrate within 1-2 hours.
### Q: Can I migrate gradually?
**A:** Absolutely! Use both providers simultaneously and gradually shift traffic to Dwellir. Our dual-provider pattern (shown above) makes this seamless.
### Q: What about rate limits?
**A:** Dwellir offers **significantly higher rate limits** than Blast:
- Paid tiers: 500+ requests/second
- Enterprise: Unlimited with dedicated infrastructure
### Q: Do you support all Blast networks?
**A:** Yes, plus 140+ additional networks! We support every network Blast offers and many more.
## Get Migration Support
Our team is standing by to ensure your migration is smooth and successful:
### 📧 Direct Support
- Email: **ben@dwellir.com**
- Response time: < 1 hour during business hours
### 📞 Enterprise Hotline
- For urgent migrations: Contact ben@dwellir.com
- Dedicated migration engineers available
### 📚 Resources
- [API Documentation](/docs)
- [Network Endpoints](/getting-started/supported-chains)
## Don't Follow the Crowd to Alchemy
While Alchemy wants to lock you into their confusing compute unit system, Dwellir offers a better path forward.
### ⚡ Skip Alchemy. Choose Dwellir.
✅ **No compute units** - Simple, predictable pricing
✅ **3x faster** than Alchemy
✅ **80% cheaper** for most applications
✅ **150+ networks** vs Alchemy's 30
✅ **Real human support** in <1 hour
✅ **$1 per million** intro offer for 1B+ requests/month
Skip Alchemy → Choose Dwellir
**Promo Code: BLAST50** - Save 50% for 3 months
**High Volume?** Email enterprise@dwellir.com for $1/M pricing
### 🎯 The Smart Choice is Clear
**Alchemy** = Complex compute units, surprise bills, slow support, limited networks
**Dwellir** = Simple pricing, predictable costs, fast support, 150+ networks
---
*Ready to make the smart choice? Contact our migration team at [migration@dwellir.com](mailto:migration@dwellir.com) or start a [live chat](https://dashboard.dwellir.com). We'll help you avoid Alchemy's complexity and get you running on better infrastructure.*
---
## admin_ethCallStatistics
Monad-specific method for admin_ethCallStatistics.
## Request
```json
{
"jsonrpc": "2.0",
"method": "admin_ethCallStatistics",
"params": [],
"id": 1
}
```
## Response
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": null
}
```
## Documentation
For more details, see the [Monad JSON-RPC documentation](https://docs.monad.xyz/reference/json-rpc).
---
## debug_getRawBlock
Monad-specific method for debug_getRawBlock.
## Request
```json
{
"id": 0,
"jsonrpc": "2.0",
"method": "debug_getRawBlock",
"params": [
"0x24bc67d"
]
}
```
## Response
```json
{
"jsonrpc": "2.0",
"results": "0xf92e32f90287a04cf264b15191aa568.....",
"id": 0
}
```
## Documentation
For more details, see the [Monad JSON-RPC documentation](https://docs.monad.xyz/reference/json-rpc).
---
## debug_getRawHeader
Monad-specific method for debug_getRawHeader.
## Request
```json
{
"id": 0,
"jsonrpc": "2.0",
"method": "debug_getRawHeader",
"params": [
"0x24bc67d"
]
}
```
## Response
```json
{
"jsonrpc": "2.0",
"results": "0xf90287a04cf264b15191aa568f00f9.....",
"id": 0
}
```
## Documentation
For more details, see the [Monad JSON-RPC documentation](https://docs.monad.xyz/reference/json-rpc).
---
## debug_getRawReceipts
Monad-specific method for debug_getRawReceipts.
## Request
```json
{
"id": 0,
"jsonrpc": "2.0",
"method": "debug_getRawReceipts",
"params": [
"0x24bc67d"
]
}
```
## Response
```json
{
"jsonrpc": "2.0",
"results": [
"0xf901c50180b9010000000000000000.....",
"0x02f90109018316e360b90100000000.....",
...
]
"id": 0
}
```
## Documentation
For more details, see the [Monad JSON-RPC documentation](https://docs.monad.xyz/reference/json-rpc).
---
## debug_getRawTransaction
Monad-specific method for debug_getRawTransaction.
## Request
```json
{
"id": 0,
"jsonrpc": "2.0",
"method": "debug_getRawTransaction",
"params": [
"0xdcc83cd5ab3c01e1d9f50da5c0150823def4bf13f5f01a03026c0a2c68f12882"
]
}
```
## Response
```json
{
"jsonrpc": "2.0",
"results": "0x02f90556818f830597c984665d1b74851815311ee8832dc6c.....",
"id": 0
}
```
## Documentation
For more details, see the [Monad JSON-RPC documentation](https://docs.monad.xyz/reference/json-rpc).
---
## debug_traceBlock - Monad RPC Method
# debug_traceBlock
Traces all transactions in a block on Monad 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-throughput DeFi, latency-sensitive trading, and scalable 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-monad-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-monad-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 - Monad RPC Method
# debug_traceBlockByHash
Traces all transactions in a block on Monad 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": ["0xc627c6245574cee468cfccfd9cbfcb93c6d230d46a1b88f3363e0396cb8da145", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceBlockByHash",
"params": ["0xc627c6245574cee468cfccfd9cbfcb93c6d230d46a1b88f3363e0396cb8da145", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0xc627c6245574cee468cfccfd9cbfcb93c6d230d46a1b88f3363e0396cb8da145';
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 - Monad RPC Method
# debug_traceBlockByNumber
Traces all transactions in a block on Monad 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-monad-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-monad-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 - Monad RPC Method
# debug_traceCall
Traces a call without creating a transaction on Monad.
:::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-throughput DeFi, latency-sensitive trading, and scalable 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": "0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"data": "0x70a082310000000000000000000000003bd359C1119dA7Da1D913D1C4D2B7c461115433A"
},
"latest",
{}
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceCall",
"params": [
{"to": "0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A", "data": "0x70a082310000000000000000000000003bd359C1119dA7Da1D913D1C4D2B7c461115433A"},
"latest",
{"tracer": "callTracer"}
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY');
const trace = await provider.send('debug_traceCall', [
{ to: '0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A', data: '0x70a082310000000000000000000000003bd359C1119dA7Da1D913D1C4D2B7c461115433A' },
'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 - Monad RPC Method
# debug_traceTransaction
Traces a transaction execution on Monad 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-throughput DeFi, latency-sensitive trading, and scalable 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": ["0xc2d1de53ff3ce014bbe5d43a740e60a6cdb487a0ab4fda52deb11d0a0c5aa5c9", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceTransaction",
"params": ["0xc2d1de53ff3ce014bbe5d43a740e60a6cdb487a0ab4fda52deb11d0a0c5aa5c9", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY');
const txHash = '0xc2d1de53ff3ce014bbe5d43a740e60a6cdb487a0ab4fda52deb11d0a0c5aa5c9';
// 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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0xc2d1de53ff3ce014bbe5d43a740e60a6cdb487a0ab4fda52deb11d0a0c5aa5c9'
# 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 - Monad RPC Method
# eth_accounts
Returns a list of addresses owned by the client on Monad.
> **Why Monad?** Build on the parallel EVM L1 delivering 10,000 TPS with 400ms blocks and sub-cent gas fees with optimistic parallel execution, MonadBFT consensus, $244M Paradigm-led funding, and consumer-grade validator hardware requirements.
## 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 high-performance dApp developers, DeFi builders, and teams requiring Ethereum compatibility at scale 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-monad-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-monad-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-monad-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-monad-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-monad-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-monad-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 - Monad RPC Method
# eth_blockNumber
Returns the number of the most recent block on Monad.
> **Why Monad?** Build on the parallel EVM L1 delivering 10,000 TPS with 400ms blocks and sub-cent gas fees with optimistic parallel execution, MonadBFT consensus, $244M Paradigm-led funding, and consumer-grade validator hardware requirements.
## When to Use This Method
`eth_blockNumber` is fundamental for high-performance dApp developers, DeFi builders, and teams requiring Ethereum compatibility at scale:
- **Syncing Applications** — Keep your dApp in sync with the latest Monad blockchain state
- **Transaction Monitoring** — Verify confirmations by comparing block numbers
- **Event Filtering** — Set the correct block range for querying logs on high-throughput DeFi, latency-sensitive trading, and scalable 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-monad-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-monad-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('Monad block:', blockNumber);
// Using ethers.js
const provider = new JsonRpcProvider('https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY');
const blockNumber = await provider.getBlockNumber();
console.log('Monad block:', blockNumber);
```
```python
def get_block_number():
response = requests.post(
'https://api-monad-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'Monad block: {block_number}')
# Using web3.py
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY'))
print(f'Monad 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-monad-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("Monad block: %d\n", blockNumber)
}
```
## Common Use Cases
### 1. Block Confirmation Counter
Monitor transaction confirmations on Monad:
```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 Monad:
```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 Monad 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-monad-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 - Monad RPC Method
# eth_call
Executes a new message call immediately without creating a transaction on Monad. Used for reading smart contract state.
> **Why Monad?** Build on the parallel EVM L1 delivering 10,000 TPS with 400ms blocks and sub-cent gas fees with optimistic parallel execution, MonadBFT consensus, $244M Paradigm-led funding, and consumer-grade validator hardware requirements.
## 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-throughput DeFi, latency-sensitive trading, and scalable 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": "0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"data": "0x70a082310000000000000000000000003bd359C1119dA7Da1D913D1C4D2B7c461115433A"
},
"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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_call",
"params": [{
"to": "0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"data": "0x70a082310000000000000000000000003bd359C1119dA7Da1D913D1C4D2B7c461115433A"
}, "latest"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-monad-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-monad-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(
'0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A',
'0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A'
)
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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
contractAddress := common.HexToAddress("0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A")
data := common.FromHex("0x70a082310000000000000000000000003bd359C1119dA7Da1D913D1C4D2B7c461115433A")
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 - Monad RPC Method
# eth_chainId
Returns the chain ID used for transaction signing on Monad.
> **Why Monad?** Build on the parallel EVM L1 delivering 10,000 TPS with 400ms blocks and sub-cent gas fees with optimistic parallel execution, MonadBFT consensus, $244M Paradigm-led funding, and consumer-grade validator hardware requirements.
## 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-monad-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-monad-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-monad-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-monad-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_createAccessList
Creates an EIP-2930 access list that you can include in a transaction. This method can help optimize gas costs for complex transactions.
## Request
```json
{
"jsonrpc": "2.0",
"method": "eth_createAccessList",
"params": [
{
"from": "0x...",
"to": "0x...",
"data": "0x..."
},
"latest"
],
"id": 1
}
```
### Parameters
1. `Object` - Transaction call object:
- `from` (optional): Address the transaction is sent from
- `to`: Address the transaction is directed to
- `gas` (optional): Integer of gas provided for the transaction execution
- `gasPrice` (optional): Integer of gasPrice used for each paid gas
- `value` (optional): Integer of value sent with this transaction
- `data` (optional): Hash of the method signature and encoded parameters
2. `String|Number` - Block number, or the string "latest", "earliest" or "pending"
## Response
```json
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"accessList": [
{
"address": "0x...",
"storageKeys": [
"0x..."
]
}
],
"gasUsed": "0x..."
}
}
```
### Response Fields
- `accessList`: Array of address and storage key objects
- `gasUsed`: Estimated gas used with the access list
## Documentation
For more details, see the [Monad JSON-RPC documentation](https://docs.monad.xyz/reference/json-rpc).
---
## eth_estimateGas - Monad RPC Method
# eth_estimateGas
Estimates the gas necessary to execute a transaction on Monad.
> **Why Monad?** Build on the parallel EVM L1 delivering 10,000 TPS with 400ms blocks and sub-cent gas fees with optimistic parallel execution, MonadBFT consensus, $244M Paradigm-led funding, and consumer-grade validator hardware requirements.
## 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-throughput DeFi, latency-sensitive trading, and scalable 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": "0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"to": "0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_estimateGas",
"params": [{
"from": "0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"to": "0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"value": "0x1"
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-monad-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-monad-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('0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A', 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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
toAddress := common.HexToAddress("0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A")
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 - Monad RPC Method
# eth_feeHistory
Returns historical gas information on Monad 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-throughput DeFi, latency-sensitive trading, and scalable 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-monad-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-monad-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-monad-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 - Monad RPC Method
# eth_gasPrice
Returns the current gas price on Monad in wei.
> **Why Monad?** Build on the parallel EVM L1 delivering 10,000 TPS with 400ms blocks and sub-cent gas fees with optimistic parallel execution, MonadBFT consensus, $244M Paradigm-led funding, and consumer-grade validator hardware requirements.
## 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-throughput DeFi, latency-sensitive trading, and scalable 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-monad-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-monad-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-monad-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-monad-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 - Monad RPC Method
# eth_getBalance
Returns the balance of a given address on Monad.
> **Why Monad?** Build on the parallel EVM L1 delivering 10,000 TPS with 400ms blocks and sub-cent gas fees with optimistic parallel execution, MonadBFT consensus, $244M Paradigm-led funding, and consumer-grade validator hardware requirements.
## 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-throughput DeFi, latency-sensitive trading, and scalable 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": [
"0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY');
const address = '0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A';
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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY'))
address = '0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A'
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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
address := common.HexToAddress("0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A")
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 - Monad RPC Method
# eth_getBlockByHash
Returns information about a block by hash on Monad.
> **Why Monad?** Build on the parallel EVM L1 delivering 10,000 TPS with 400ms blocks and sub-cent gas fees with optimistic parallel execution, MonadBFT consensus, $244M Paradigm-led funding, and consumer-grade validator hardware requirements.
## 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-throughput DeFi, latency-sensitive trading, and scalable 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": [
"0xc627c6245574cee468cfccfd9cbfcb93c6d230d46a1b88f3363e0396cb8da145",
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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByHash",
"params": [
"0xc627c6245574cee468cfccfd9cbfcb93c6d230d46a1b88f3363e0396cb8da145",
false
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0xc627c6245574cee468cfccfd9cbfcb93c6d230d46a1b88f3363e0396cb8da145';
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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY'))
block_hash = '0xc627c6245574cee468cfccfd9cbfcb93c6d230d46a1b88f3363e0396cb8da145'
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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
blockHash := common.HexToHash("0xc627c6245574cee468cfccfd9cbfcb93c6d230d46a1b88f3363e0396cb8da145")
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 - Monad RPC Method
# eth_getBlockByNumber
Returns information about a block by block number on Monad.
> **Why Monad?** Build on the parallel EVM L1 delivering 10,000 TPS with 400ms blocks and sub-cent gas fees with optimistic parallel execution, MonadBFT consensus, $244M Paradigm-led funding, and consumer-grade validator hardware requirements.
## 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-throughput DeFi, latency-sensitive trading, and scalable 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": "0xc627c6245574cee468cfccfd9cbfcb93c6d230d46a1b88f3363e0396cb8da145",
"parentHash": "0x...",
"timestamp": "0x64d8f6d0",
"gasUsed": "0x1234",
"gasLimit": "0x1c9c380",
"transactions": [],
"baseFeePerGas": "0x5f5e100"
}
}
```
## Code Examples
```bash
curl -X POST https://api-monad-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-monad-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-monad-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-monad-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 - Monad RPC Method
# eth_getCode
Returns the bytecode at a given address on Monad.
> **Why Monad?** Build on the parallel EVM L1 delivering 10,000 TPS with 400ms blocks and sub-cent gas fees with optimistic parallel execution, MonadBFT consensus, $244M Paradigm-led funding, and consumer-grade validator hardware requirements.
## 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-throughput DeFi, latency-sensitive trading, and scalable 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": [
"0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"latest"
],
"id": 1
}
```
## Returns
| Type | Description |
|------|-------------|
| `DATA` | Contract bytecode or `0x` if EOA |
## Code Examples
```bash
curl -X POST https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getCode",
"params": [
"0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY');
const address = '0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A';
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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY'))
address = '0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A'
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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
address := common.HexToAddress("0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A")
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 - Monad RPC Method
# eth_getFilterChanges
Polling method for a filter on Monad, returns an array of logs since last poll.
## Use Cases
- **Event streaming** - Get new events incrementally
- **Real-time monitoring** - Track contract activity for high-throughput DeFi, latency-sensitive trading, and scalable 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-monad-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-monad-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 - Monad RPC Method
# eth_getFilterLogs
Returns an array of all logs matching filter with given ID on Monad.
## Use Cases
- **Historical queries** - Get all matching logs for a filter
- **Full event history** - Retrieve complete event data for high-throughput DeFi, latency-sensitive trading, and scalable 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-monad-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-monad-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 - Monad RPC Method
# eth_getLogs
Returns an array of all logs matching a given filter object on Monad.
> **Why Monad?** Build on the parallel EVM L1 delivering 10,000 TPS with 400ms blocks and sub-cent gas fees with optimistic parallel execution, MonadBFT consensus, $244M Paradigm-led funding, and consumer-grade validator hardware requirements.
## Use Cases
The `eth_getLogs` method is essential for:
- **Event indexing** - Track contract events for high-throughput DeFi, latency-sensitive trading, and scalable 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": "0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"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": "0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "0x...", "0x..."],
"data": "0x...",
"blockNumber": "0x5BAD55",
"transactionHash": "0x...",
"logIndex": "0x0"
}]
}
```
## Code Examples
```bash
curl -X POST https://api-monad-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": "0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-monad-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(
'0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A',
'latest',
'latest'
);
console.log('Transfer events:', events);
```
```python
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-monad-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(
'0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A',
'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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
contractAddress := common.HexToAddress("0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A")
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 - Monad RPC Method
# eth_getStorageAt
Returns the value from a storage position at a given address on Monad.
## Use Cases
- **Contract analysis** - Read raw storage values
- **State verification** - Verify contract state
- **Security auditing** - Analyze storage layout for high-throughput DeFi, latency-sensitive trading, and scalable 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": [
"0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"0x0",
"latest"
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getStorageAt",
"params": [
"0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"0x0",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY');
const address = '0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A';
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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY'))
address = '0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A'
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 - Monad RPC Method
# eth_getTransactionByHash
Returns the information about a transaction by transaction hash on Monad.
> **Why Monad?** Build on the parallel EVM L1 delivering 10,000 TPS with 400ms blocks and sub-cent gas fees with optimistic parallel execution, MonadBFT consensus, $244M Paradigm-led funding, and consumer-grade validator hardware requirements.
## 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-throughput DeFi, latency-sensitive trading, and scalable 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": ["0xc2d1de53ff3ce014bbe5d43a740e60a6cdb487a0ab4fda52deb11d0a0c5aa5c9"],
"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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionByHash",
"params": ["0xc2d1de53ff3ce014bbe5d43a740e60a6cdb487a0ab4fda52deb11d0a0c5aa5c9"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY');
const txHash = '0xc2d1de53ff3ce014bbe5d43a740e60a6cdb487a0ab4fda52deb11d0a0c5aa5c9';
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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0xc2d1de53ff3ce014bbe5d43a740e60a6cdb487a0ab4fda52deb11d0a0c5aa5c9'
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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0xc2d1de53ff3ce014bbe5d43a740e60a6cdb487a0ab4fda52deb11d0a0c5aa5c9")
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 - Monad RPC Method
# eth_getTransactionCount
Returns the number of transactions sent from an address on Monad (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-throughput DeFi, latency-sensitive trading, and scalable 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": [
"0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"latest"
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [
"0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY');
const address = '0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A';
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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY'))
address = '0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A'
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 - Monad RPC Method
# eth_getTransactionReceipt
Returns the receipt of a transaction by transaction hash on Monad. Receipt is only available for mined transactions.
> **Why Monad?** Build on the parallel EVM L1 delivering 10,000 TPS with 400ms blocks and sub-cent gas fees with optimistic parallel execution, MonadBFT consensus, $244M Paradigm-led funding, and consumer-grade validator hardware requirements.
## 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-throughput DeFi, latency-sensitive trading, and scalable EVM applications
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `transactionHash` | `DATA` | Yes | 32-byte transaction hash |
## Request
```json
{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0xc2d1de53ff3ce014bbe5d43a740e60a6cdb487a0ab4fda52deb11d0a0c5aa5c9"],
"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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0xc2d1de53ff3ce014bbe5d43a740e60a6cdb487a0ab4fda52deb11d0a0c5aa5c9"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY');
const txHash = '0xc2d1de53ff3ce014bbe5d43a740e60a6cdb487a0ab4fda52deb11d0a0c5aa5c9';
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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0xc2d1de53ff3ce014bbe5d43a740e60a6cdb487a0ab4fda52deb11d0a0c5aa5c9'
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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0xc2d1de53ff3ce014bbe5d43a740e60a6cdb487a0ab4fda52deb11d0a0c5aa5c9")
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 - Monad RPC Method
# eth_maxPriorityFeePerGas
Returns the current recommended priority fee per gas on Monad 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-throughput DeFi, latency-sensitive trading, and scalable 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-monad-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-monad-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-monad-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_newBlockFilter - Monad RPC Method
# eth_newBlockFilter
Creates a filter on Monad 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-monad-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-monad-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 - Monad RPC Method
# eth_newFilter
Creates a filter object on Monad to notify when state changes (logs).
## Use Cases
- **Event monitoring** - Subscribe to contract events
- **Real-time updates** - Track events for high-throughput DeFi, latency-sensitive trading, and scalable 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": "0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
}],
"id": 1
}
```
## Returns
| Type | Description |
|------|-------------|
| `QUANTITY` | Filter ID |
## Code Examples
```bash
curl -X POST https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_newFilter",
"params": [{
"fromBlock": "latest",
"address": "0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A"
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY');
// Create filter
const filterId = await provider.send('eth_newFilter', [{
fromBlock: 'latest',
address: '0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A',
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 - Monad RPC Method
# eth_newPendingTransactionFilter
Creates a filter on Monad 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-monad-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-monad-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_sendRawTransaction - Monad RPC Method
# eth_sendRawTransaction
Submits a pre-signed transaction for broadcast to Monad.
> **Why Monad?** Build on the parallel EVM L1 delivering 10,000 TPS with 400ms blocks and sub-cent gas fees with optimistic parallel execution, MonadBFT consensus, $244M Paradigm-led funding, and consumer-grade validator hardware requirements.
## 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-throughput DeFi, latency-sensitive trading, and scalable 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-monad-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-monad-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-monad-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-monad-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("0x3bd359C1119dA7Da1D913D1C4D2B7c461115433A")
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 - Monad RPC Method
# eth_syncing
Returns syncing status of Monad 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-monad-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-monad-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 - Monad RPC Method
# eth_uninstallFilter
Uninstalls a filter on Monad. 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-monad-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-monad-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
---
## Monad - High-Performance EVM Layer 1 Documentation
# Monad - Build Without Limits on High-Performance EVM
## Why Build on Monad?
Monad is a high-performance EVM Layer 1 blockchain designed to deliver exceptional throughput without sacrificing decentralization. Built from the ground up for speed and scalability:
### 🚀 **Extreme Performance**
- **10,000+ TPS** - Handle massive transaction volumes with ease
- **1-second block times** - Near-instant finality for your users
- **Parallel execution** - Advanced transaction processing architecture
### 🛡️ **EVM Compatible**
- **Full Ethereum compatibility** - Deploy existing contracts without changes
- **Proven tooling** - Works with MetaMask, Hardhat, Foundry, and more
- **Familiar development** - Same APIs and libraries you already know
### 🌍 **Growing Ecosystem**
- **Active community** - Rapidly expanding developer base
- **Testnet live** - Build and test today on the Monad testnet
- **Mainnet launched** - Production-ready network live since November 2025
## Quick Start with Monad
Connect to Monad in seconds with Dwellir's optimized endpoints:
### Installation & Setup
```javascript
// Connect to Monad mainnet
const provider = new JsonRpcProvider(
'https://api-monad-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 Monad mainnet
const web3 = new Web3(
'https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY'
);
// Get chain ID to verify connection
const chainId = await web3.eth.getChainId();
console.log('Connected to Monad:', chainId === 143);
// Get gas price for optimal transaction pricing
const gasPrice = await web3.eth.getGasPrice();
console.log('Current gas price:', gasPrice);
```
```typescript
// Define Monad chain
const monad = defineChain({
id: 143,
name: 'Monad',
network: 'monad',
nativeCurrency: {
decimals: 18,
name: 'MON',
symbol: 'MON',
},
rpcUrls: {
default: {
http: ['https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY'],
},
public: {
http: ['https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY'],
},
},
});
// Create Monad client
const client = createPublicClient({
chain: monad,
transport: http(),
});
// Read contract data
const data = await client.readContract({
address: '0x...',
abi: contractAbi,
functionName: 'balanceOf',
args: ['0x...'],
});
```
## Network Information
Chain ID
143
Mainnet
Block Time
1 second
Average
Gas Token
MON
Native token
RPC Standard
Ethereum
JSON-RPC 2.0
## JSON-RPC API Reference
Monad supports the full [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/), plus additional methods for debugging, tracing, and transaction pool management.
## 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);
console.log('Transaction confirmed in block:', receipt.blockNumber);
console.log('Gas used:', receipt.gasUsed.toString());
return receipt;
}
// Monitor transaction status
const tx = await wallet.sendTransaction({
to: recipient,
value: amount,
});
console.log('Transaction sent:', tx.hash);
const receipt = await waitForTransaction(tx.hash);
```
### 💰 Gas Optimization
Optimize gas costs on Monad:
```javascript
// Estimate gas for a transaction
const gasEstimate = await provider.estimateGas({
to: recipient,
value: amount,
data: '0x...',
});
console.log('Estimated gas:', gasEstimate.toString());
// Get current gas price
const gasPrice = await provider.getGasPrice();
console.log('Current gas price:', gasPrice.toString());
// Use EIP-1559 pricing
const feeData = await provider.getFeeData();
const tx = {
to: recipient,
value: amount,
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 currentBlock = await provider.getBlockNumber();
const events = [];
const batchSize = 5000; // Monad's high throughput supports larger batches
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'] }
];
// Send batch request
const results = await Promise.all(
batch.map(req => provider.send(req.method, req.params))
);
```
### 2. **Connection Pooling**
Reuse provider instances to minimize connection overhead:
```javascript
// Singleton pattern for provider
class MonadProvider {
static instance = null;
static getInstance() {
if (!this.instance) {
this.instance = new JsonRpcProvider(
'https://api-monad-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);
}
```
## Monad-Specific Features
### Local Mempool Design
Monad does not have a global mempool. Each RPC node maintains its own local mempool, which affects transaction visibility:
```javascript
// Query transaction pool status by address
const statusByAddress = await provider.send('txpool_statusByAddress', [address]);
console.log('Pending transactions:', statusByAddress);
// Query transaction pool status by hash
const statusByHash = await provider.send('txpool_statusByHash', [txHash]);
console.log('Transaction status:', statusByHash);
```
### Transaction Pool Management
Use these Monad-specific methods for mempool operations:
```javascript
// Get pending transaction count for an address
const pendingCount = await provider.getTransactionCount(address, 'pending');
// Check transaction pool statistics (admin endpoint)
const txPoolStats = await provider.send('admin_ethCallStatistics', []);
console.log('TxPool stats:', txPoolStats);
```
## Troubleshooting Common Issues
### Error: "Insufficient funds"
Ensure your account has enough MON for gas:
```javascript
// Check balance before sending transaction
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) {
throw new Error(`Need ${totalRequired - balance} more MON`);
}
```
### Error: "Transaction underpriced"
Monad 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 Monad requires minimal changes:
```javascript
// Before (Ethereum)
const provider = new JsonRpcProvider('https://eth-rpc.example.com');
// After (Monad)
const provider = new JsonRpcProvider(
'https://api-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY'
);
// ✅ Smart contracts work identically
// ✅ Same tooling and libraries
// ✅ Higher throughput and faster finality
// ⚠️ Different chain ID (143)
// ⚠️ Different native token (MON instead of ETH)
// ⚠️ Local mempool design (no global mempool)
```
## Resources & Tools
### Official Resources
- [Monad Documentation](https://docs.monad.xyz)
- [Monad Explorer](https://monadexplorer.com)
- [Monad Testnet Explorer](https://testnet.monadexplorer.com)
### Developer Tools
- [Hardhat Setup](https://docs.monad.xyz/guides/hardhat)
- [Foundry Integration](https://docs.monad.xyz/guides/foundry)
- [Add Monad to MetaMask](https://docs.monad.xyz/guides/add-monad-to-wallet/mainnet)
### Need Help?
- 📧 **Email**: support@dwellir.com
- 📚 **Docs**: You're here!
- 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com)
---
*Start building on Monad with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## net_listening - Monad RPC Method
# net_listening
Returns `true` if client is actively listening for network connections on Monad.
## 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-monad-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-monad-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 - Monad RPC Method
# net_peerCount
Returns number of peers currently connected to Monad 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-monad-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-monad-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 - Monad RPC Method
# net_version
Returns the current network ID on Monad.
## 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-monad-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-monad-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 - Monad RPC Method
# web3_clientVersion
Returns the current client version on Monad.
## 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-monad-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-monad-mainnet-full.n.dwellir.com/YOUR_API_KEY');
const version = await provider.send('web3_clientVersion', []);
console.log('Client version:', version);
```
---
## web3_sha3 - Monad RPC Method
# web3_sha3
Returns Keccak-256 (not standard SHA3-256) of the given data on Monad.
## 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-monad-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-monad-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);
```
---
## author_pendingExtrinsics - Moonbase RPC Method
# author_pendingExtrinsics
Returns all pending extrinsics in the transaction pool on Moonbase Alpha.
## Use Cases
- **Mempool monitoring** - Track pending transactions
- **Transaction status** - Check if your transaction is pending for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# author_rotateKeys
Generate a new set of session keys on Moonbase Alpha. 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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase 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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# author_submitExtrinsic
Submit a signed extrinsic to Moonbase Alpha for inclusion in a block.
## Use Cases
- **Transaction submission** - Broadcast signed transactions
- **dApp interactions** - Execute on-chain operations for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# beefy_getFinalizedHead
Returns the block hash of the latest BEEFY-finalized block on Moonbase Alpha. 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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# chain_getBlock
Retrieves complete block information from Moonbase Alpha, including the block header, extrinsics, and justifications.
> **Why Moonbase?** Build on the Moonbeam testnet for risk-free EVM dApp development and deployment testing with free testnet tokens, full EVM compatibility, XCM testing capabilities, and identical feature set to Moonbeam mainnet.
## 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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# chain_getBlockHash
Returns the block hash for a given block number on Moonbase Alpha.
## Use Cases
- **Historical queries** - Convert block numbers to hashes
- **Block navigation** - Navigate blockchain history for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# chain_getFinalizedHead
Returns the hash of the last finalized block on Moonbase Alpha.
## Use Cases
- **Confirmed state** - Query state that cannot be reverted
- **Transaction confirmation** - Verify transaction finality for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# chain_getHeader
Returns the block header for a given hash on Moonbase Alpha.
## Use Cases
- **Lightweight queries** - Get header without full block data
- **Chain synchronization** - Track block production for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# chain_subscribeFinalizedHeads
Subscribe to receive notifications when blocks are finalized on Moonbase Alpha. 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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# chain_subscribeNewHeads
Subscribe to receive notifications when new block headers are produced on Moonbase Alpha. This WebSocket subscription provides real-time updates for each new block.
## Use Cases
- **Block monitoring** - Track new blocks in real-time for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_accounts
Returns a list of addresses owned by the client on Moonbase Alpha.
> **Why Moonbase?** Build on the Moonbeam testnet for risk-free EVM dApp development and deployment testing with free testnet tokens, full EVM compatibility, XCM testing capabilities, and identical feature set to Moonbeam mainnet.
## 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 Moonbeam developers, dApp testers, and teams validating cross-chain integrations 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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.n.dwellir.com/YOUR_API_KEY');
const accounts = await provider.listAccounts();
console.log('Accounts:', accounts);
```
```python
def get_accounts():
response = requests.post(
'https://api-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_blockNumber
Returns the number of the most recent block on Moonbase Alpha.
> **Why Moonbase?** Build on the Moonbeam testnet for risk-free EVM dApp development and deployment testing with free testnet tokens, full EVM compatibility, XCM testing capabilities, and identical feature set to Moonbeam mainnet.
## When to Use This Method
`eth_blockNumber` is fundamental for Moonbeam developers, dApp testers, and teams validating cross-chain integrations:
- **Syncing Applications** — Keep your dApp in sync with the latest Moonbase blockchain state
- **Transaction Monitoring** — Verify confirmations by comparing block numbers
- **Event Filtering** — Set the correct block range for querying logs on EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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('Moonbase block:', blockNumber);
// Using ethers.js
const provider = new JsonRpcProvider('https://api-moonbase-alpha.n.dwellir.com/YOUR_API_KEY');
const blockNumber = await provider.getBlockNumber();
console.log('Moonbase block:', blockNumber);
```
```python
def get_block_number():
response = requests.post(
'https://api-moonbase-alpha.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'Moonbase block: {block_number}')
# Using web3.py
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-moonbase-alpha.n.dwellir.com/YOUR_API_KEY'))
print(f'Moonbase 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-moonbase-alpha.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("Moonbase block: %d\n", blockNumber)
}
```
## Common Use Cases
### 1. Block Confirmation Counter
Monitor transaction confirmations on Moonbase:
```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 Moonbase:
```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 Moonbase 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-moonbase-alpha.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 - Moonbase RPC Method
# eth_call
Executes a new message call immediately without creating a transaction on Moonbase Alpha. Used for reading smart contract state.
> **Why Moonbase?** Build on the Moonbeam testnet for risk-free EVM dApp development and deployment testing with free testnet tokens, full EVM compatibility, XCM testing capabilities, and identical feature set to Moonbeam mainnet.
## 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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_chainId
Returns the chain ID used for transaction signing on Moonbase Alpha.
> **Why Moonbase?** Build on the Moonbeam testnet for risk-free EVM dApp development and deployment testing with free testnet tokens, full EVM compatibility, XCM testing capabilities, and identical feature set to Moonbeam mainnet.
## 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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_estimateGas
Estimates the gas necessary to execute a transaction on Moonbase Alpha.
> **Why Moonbase?** Build on the Moonbeam testnet for risk-free EVM dApp development and deployment testing with free testnet tokens, full EVM compatibility, XCM testing capabilities, and identical feature set to Moonbeam mainnet.
## 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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
## 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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_feeHistory
Returns historical gas information on Moonbase Alpha 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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
## 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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_gasPrice
Returns the current gas price on Moonbase Alpha in wei.
> **Why Moonbase?** Build on the Moonbeam testnet for risk-free EVM dApp development and deployment testing with free testnet tokens, full EVM compatibility, XCM testing capabilities, and identical feature set to Moonbeam mainnet.
## 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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
## 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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_getBalance
Returns the balance of a given address on Moonbase Alpha.
> **Why Moonbase?** Build on the Moonbeam testnet for risk-free EVM dApp development and deployment testing with free testnet tokens, full EVM compatibility, XCM testing capabilities, and identical feature set to Moonbeam mainnet.
## 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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_getBlockByHash
Returns information about a block by hash on Moonbase Alpha.
> **Why Moonbase?** Build on the Moonbeam testnet for risk-free EVM dApp development and deployment testing with free testnet tokens, full EVM compatibility, XCM testing capabilities, and identical feature set to Moonbeam mainnet.
## 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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_getBlockByNumber
Returns information about a block by block number on Moonbase Alpha.
> **Why Moonbase?** Build on the Moonbeam testnet for risk-free EVM dApp development and deployment testing with free testnet tokens, full EVM compatibility, XCM testing capabilities, and identical feature set to Moonbeam mainnet.
## 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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_getCode
Returns the bytecode at a given address on Moonbase Alpha.
> **Why Moonbase?** Build on the Moonbeam testnet for risk-free EVM dApp development and deployment testing with free testnet tokens, full EVM compatibility, XCM testing capabilities, and identical feature set to Moonbeam mainnet.
## 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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
## 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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_getFilterChanges
Polling method for a filter on Moonbase Alpha, returns an array of logs since last poll.
## Use Cases
- **Event streaming** - Get new events incrementally
- **Real-time monitoring** - Track contract activity for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_getFilterLogs
Returns an array of all logs matching filter with given ID on Moonbase Alpha.
## Use Cases
- **Historical queries** - Get all matching logs for a filter
- **Full event history** - Retrieve complete event data for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
## 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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_getLogs
Returns an array of all logs matching a given filter object on Moonbase Alpha.
> **Why Moonbase?** Build on the Moonbeam testnet for risk-free EVM dApp development and deployment testing with free testnet tokens, full EVM compatibility, XCM testing capabilities, and identical feature set to Moonbeam mainnet.
## Use Cases
The `eth_getLogs` method is essential for:
- **Event indexing** - Track contract events for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_getStorageAt
Returns the value from a storage position at a given address on Moonbase Alpha.
## Use Cases
- **Contract analysis** - Read raw storage values
- **State verification** - Verify contract state
- **Security auditing** - Analyze storage layout for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_getTransactionByHash
Returns the information about a transaction by transaction hash on Moonbase Alpha.
> **Why Moonbase?** Build on the Moonbeam testnet for risk-free EVM dApp development and deployment testing with free testnet tokens, full EVM compatibility, XCM testing capabilities, and identical feature set to Moonbeam mainnet.
## 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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_getTransactionCount
Returns the number of transactions sent from an address on Moonbase Alpha (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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
## 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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_getTransactionReceipt
Returns the receipt of a transaction by transaction hash on Moonbase Alpha. Receipt is only available for mined transactions.
> **Why Moonbase?** Build on the Moonbeam testnet for risk-free EVM dApp development and deployment testing with free testnet tokens, full EVM compatibility, XCM testing capabilities, and identical feature set to Moonbeam mainnet.
## 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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
## 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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_maxPriorityFeePerGas
Returns the current recommended priority fee per gas on Moonbase Alpha 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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
## 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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_newBlockFilter
Creates a filter on Moonbase Alpha 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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_newFilter
Creates a filter object on Moonbase Alpha to notify when state changes (logs).
## Use Cases
- **Event monitoring** - Subscribe to contract events
- **Real-time updates** - Track events for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_newPendingTransactionFilter
Creates a filter on Moonbase Alpha 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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_sendRawTransaction
Submits a pre-signed transaction for broadcast to Moonbase Alpha.
> **Why Moonbase?** Build on the Moonbeam testnet for risk-free EVM dApp development and deployment testing with free testnet tokens, full EVM compatibility, XCM testing capabilities, and identical feature set to Moonbeam mainnet.
## 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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_syncing
Returns syncing status of Moonbase Alpha 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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# eth_uninstallFilter
Uninstalls a filter on Moonbase Alpha. 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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# grandpa_roundState
Returns the state of the current GRANDPA finality round on Moonbase Alpha. GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) is the finality gadget used by Substrate chains.
## Use Cases
- **Finality monitoring** - Track consensus progress for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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)
---
## Moonbase Alpha RPC Guide
# Moonbase Alpha – Moonbeam Test Network
## Why Build on Moonbase Alpha?
Moonbase Alpha is Moonbeam’s public test network. It mirrors Moonbeam’s Ethereum-compatible Substrate runtime so you can validate end‑to‑end integrations safely before deploying to mainnet:
- EVM + Substrate: Test both Ethereum JSON‑RPC and Substrate RPC flows on one chain
- Fast iteration: Frequent upgrades track Moonbeam, enabling realistic pre‑prod rehearsals
- Tooling parity: Works with polkadot.js, subxt, py‑substrate‑interface, and EVM SDKs
## Quick Start
Connect in seconds using Dwellir’s optimized endpoints.
:::info Get your API key
Sign up at the Dwellir Dashboard to replace `YOUR_API_KEY` before sending requests.
:::
### Installation & Setup
```bash
curl https://api-moonbase-alpha.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "chain_getHeader",
"params": []
}'
```
```
# Sample (2025-10-09)
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"number": "0xd52457",
"parentHash": "0x56f87850ee68308211e6044273bc47bf8948e7e03a17d55e65ed70908eb921ca",
"stateRoot": "0x013f4c9d16f934155515a7328528a7309151c8b1a693a4f6a44224a0ea2e1099",
"extrinsicsRoot": "0x2d88bb9bc669fc3ab81a306e849b5f09248689abe1c05f81f63a88ee17891f4d"
}
}
```
```typescript
async function main() {
const provider = new WsProvider('wss://api-moonbase-alpha.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.toString()} via ${nodeName} ${version}`);
console.log(`specVersion=${runtime.specVersion.toString()}, txVersion=${runtime.transactionVersion.toString()}`);
// Subscribe to new block headers
const unsub = await api.rpc.chain.subscribeNewHeads((header) => {
console.log(`#${header.number.toString()} ${header.hash.toHex()}`);
});
// Unsubscribe later
setTimeout(async () => { await unsub(); await api.disconnect(); }, 10000);
}
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-moonbase-alpha.n.dwellir.com/YOUR_API_KEY"
).await?;
let head = api.rpc().finalized_head().await?;
let header = api.rpc().header(Some(head)).await?.expect("header");
println!("Finalized block #{:?} (hash {:?})", header.number, head);
Ok(())
}
```
```python
from substrateinterface import SubstrateInterface
api = SubstrateInterface(
url="wss://api-moonbase-alpha.n.dwellir.com/YOUR_API_KEY",
ss58_format=1287,
type_registry_preset="substrate-node-template"
)
runtime = api.get_runtime_version()
print("specVersion", runtime['specVersion'], "transactionVersion", runtime['transactionVersion'])
# Example account query (replace with a valid Moonbase Alpha SS58 address)
# account = api.query('System', 'Account', params=[''])
# print(account.value['data'])
```
## Network Information
Relay Chain
Alphanet Relay Chain
Unit / Decimals
DEV / 18
SS58 Prefix
1287
Genesis Hash
0x91bc6e169807aaa54802737e1c504b2577d4fafedd5a02c10293b1cd60e39527
Runtime (2025-10-09)
specVersion 3900 · transactionVersion 3
Explorer
moonbase.moonscan.io
## Substrate JSON‑RPC API Reference
Supported core method groups include `system_*`, `chain_*`, `state_*`, `author_*`, `payment_*`, and `rpc_methods`. Frontier EVM (`eth_*`) and debug namespaces are available on Moonbase Alpha but are out of scope for this Substrate reference.
## Common Integration Patterns
- Prefer WebSocket for subscriptions (e.g., `chain_subscribeNewHeads`).
- Cache metadata and types between runs to avoid repeated `state_getMetadata`/`state_getRuntimeVersion` calls.
- For large storage scans, paginate keys with `state_getKeysPaged`.
- Use `payment_queryInfo` to estimate fees before `author_submitExtrinsic`.
## Performance Best Practices
- Reconnect with exponential backoff on WS disconnects.
- Batch independent calls where possible.
- Scope `state_getStorage` queries to explicit keys; avoid full‑state traversals.
## Troubleshooting
- Connection errors: verify API key, TLS, and use WS for subscriptions.
- Type errors: ensure metadata is fresh; update polkadot.js/subxt type bundles.
- SS58 issues: confirm prefix `1287` and address checksum.
- Extrinsics failing: decode dispatch errors using runtime metadata.
## Smoke Tests
- `system_health` → expect `isSyncing: false` and non‑zero `peers`.
- `chain_getHeader` (latest) → block number increases over time.
- `state_getRuntimeVersion` → returns `specVersion: 3900`, `transactionVersion: 3` (as of 2025‑10‑09).
## Migration Guide
From Polkadot/Westend to Moonbase Alpha:
- Update endpoints to `api-moonbase-alpha.n.dwellir.com`.
- Switch SS58 to `1287`; unit symbol becomes `DEV` with 18 decimals.
- Re‑check fee modeling via `payment_queryInfo`.
- Confirm method availability with `rpc_methods` (GRANDPA/BEEFY are not exposed here).
## Resources & Tools
- Explorer: https://moonbase.moonscan.io
- Moonbeam Docs: https://docs.moonbeam.network/
- Substrate Developer Hub: https://docs.substrate.io/
- Polkadot.js Apps: https://polkadot.js.org/apps/
---
## net_listening - Moonbase RPC Method
# net_listening
Returns `true` if client is actively listening for network connections on Moonbase Alpha.
## 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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# net_peerCount
Returns number of peers currently connected to Moonbase Alpha 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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# net_version
Returns the current network ID on Moonbase Alpha.
## 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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# payment_queryFeeDetails
Returns a detailed breakdown of fees for a given extrinsic on Moonbase Alpha. 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 EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# payment_queryInfo
Estimates the fee for an extrinsic on Moonbase Alpha.
## Use Cases
- **Fee estimation** - Calculate transaction costs before sending
- **UI display** - Show fees to users for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# rpc_methods
Returns a list of all RPC methods available on Moonbase Alpha.
## Use Cases
- **API discovery** - List all available methods
- **Compatibility checking** - Verify method availability for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# state_call
Calls a runtime API method on Moonbase Alpha.
## Use Cases
- **Runtime computations** - Execute runtime logic without transactions
- **Account queries** - Use AccountNonceApi for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# state_getKeysPaged
Returns storage keys with pagination on Moonbase Alpha.
## Use Cases
- **Storage iteration** - Enumerate storage map entries
- **Data export** - Bulk export chain data for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# state_getMetadata
Returns the runtime metadata on Moonbase Alpha.
## Use Cases
- **Runtime introspection** - Discover available pallets and calls
- **Extrinsic building** - Get call and type information for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# state_getRuntimeVersion
Returns the runtime version on Moonbase Alpha.
## Use Cases
- **Version checking** - Verify runtime compatibility
- **Upgrade detection** - Monitor for runtime upgrades on EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# state_getStorage
Returns a storage entry at a specific key on Moonbase Alpha.
> **Why Moonbase?** Build on the Moonbeam testnet for risk-free EVM dApp development and deployment testing with free testnet tokens, full EVM compatibility, XCM testing capabilities, and identical feature set to Moonbeam mainnet.
## Use Cases
- **State queries** - Read on-chain storage values
- **Account balances** - Query account data for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# state_queryStorageAt
Query multiple storage keys at a specific block on Moonbase Alpha.
## Use Cases
- **Batch queries** - Efficiently query multiple storage items
- **Snapshot state** - Get consistent multi-key state for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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_accountNextIndex - JSON-RPC Me...
export const S = substrateSamples['moonbase-alpha'];
# system_accountNextIndex
Returns the next valid transaction index (nonce) for an account.
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `accountId` | string | Yes | SS58 address or hex AccountId. Moonbase Alpha uses 20-byte AccountId; hex like `${S.accountId}` works. |
## cURL
{`
curl -X POST ${S.rpcBase} \\
-H "Content-Type: application/json" \\
-d '{"jsonrpc":"2.0","id":1,"method":"system_accountNextIndex","params":["${S.accountId}"]}'
`}
## JavaScript (polkadot.js)
```typescript
async function main() {
const api = await ApiPromise.create({ provider: new WsProvider('${S.wsBase}') });
const nonce = await api.rpc.system.accountNextIndex('${S.accountId}');
console.log('Next nonce:', nonce.toString());
await api.disconnect();
}
```
## Notes
- For Substrate signing, pass the same nonce when constructing a signed extrinsic.
- Combine with `payment_queryInfo` to estimate fees before submission.
---
## system_chain - Moonbase RPC Method
# system_chain
Returns the chain name on Moonbase Alpha.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_chain",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl https://api-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# system_health
Returns the health status of the Moonbase Alpha node.
## Use Cases
- **Health checks** - Monitor node availability
- **Load balancing** - Route traffic based on health for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# system_name
Returns the node implementation name on Moonbase Alpha.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_name",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl https://api-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# system_properties
Returns chain properties including token symbol and decimals on Moonbase Alpha.
## Use Cases
- **Token formatting** - Get decimals and symbol for EVM dApp testing, XCM integration validation, and pre-mainnet deployment verification
- **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-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# system_version
Returns the node implementation version on Moonbase Alpha.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_version",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl https://api-moonbase-alpha.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-moonbase-alpha.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 - Moonbase RPC Method
# web3_clientVersion
Returns the current client version on Moonbase Alpha.
## 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-moonbase-alpha.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-moonbase-alpha.n.dwellir.com/YOUR_API_KEY');
const version = await provider.send('web3_clientVersion', []);
console.log('Client version:', version);
```
---
## web3_sha3 - Moonbase RPC Method
# web3_sha3
Returns Keccak-256 (not standard SHA3-256) of the given data on Moonbase Alpha.
## 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-moonbase-alpha.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-moonbase-alpha.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 - Moonbeam RPC Method
# author_pendingExtrinsics
Returns all pending extrinsics in the transaction pool on Moonbeam.
## Use Cases
- **Mempool monitoring** - Track pending transactions
- **Transaction status** - Check if your transaction is pending for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# author_rotateKeys
Generate a new set of session keys on Moonbeam. 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# author_submitExtrinsic
Submit a signed extrinsic to Moonbeam for inclusion in a block.
## Use Cases
- **Transaction submission** - Broadcast signed transactions
- **dApp interactions** - Execute on-chain operations for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# beefy_getFinalizedHead
Returns the block hash of the latest BEEFY-finalized block on Moonbeam. 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# chain_getBlock
Retrieves complete block information from Moonbeam, including the block header, extrinsics, and justifications.
> **Why Moonbeam?** Build on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects with full EVM compatibility on Polkadot, native XCM cross-chain messaging, 10K+ TPS, 24% staking APR, and $0.015 transaction costs.
## 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# chain_getBlockHash
Returns the block hash for a given block number on Moonbeam.
## Use Cases
- **Historical queries** - Convert block numbers to hashes
- **Block navigation** - Navigate blockchain history for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# chain_getFinalizedHead
Returns the hash of the last finalized block on Moonbeam.
## Use Cases
- **Confirmed state** - Query state that cannot be reverted
- **Transaction confirmation** - Verify transaction finality for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# chain_getHeader
Returns the block header for a given hash on Moonbeam.
## Use Cases
- **Lightweight queries** - Get header without full block data
- **Chain synchronization** - Track block production for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# chain_subscribeFinalizedHeads
Subscribe to receive notifications when blocks are finalized on Moonbeam. 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# chain_subscribeNewHeads
Subscribe to receive notifications when new block headers are produced on Moonbeam. 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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
---
## debug_traceBlock - Moonbeam RPC Method
# debug_traceBlock
Traces all transactions in a block on Moonbeam 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 cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
## 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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# debug_traceBlockByHash
Traces all transactions in a block on Moonbeam 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": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-moonbeam.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceBlockByHash",
"params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-moonbeam.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3';
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 - Moonbeam RPC Method
# debug_traceBlockByNumber
Traces all transactions in a block on Moonbeam 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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# debug_traceCall
Traces a call without creating a transaction on Moonbeam.
:::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 cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
## 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": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
"data": "0x70a08231000000000000000000000000"
},
"latest",
{}
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-moonbeam.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceCall",
"params": [
{"to": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY", "data": "0x70a08231000000000000000000000000"},
"latest",
{"tracer": "callTracer"}
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-moonbeam.n.dwellir.com/YOUR_API_KEY');
const trace = await provider.send('debug_traceCall', [
{ to: '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY', data: '0x70a08231000000000000000000000000' },
'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 - Moonbeam RPC Method
# debug_traceTransaction
Traces a transaction execution on Moonbeam 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 cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
## 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": ["", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-moonbeam.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceTransaction",
"params": ["", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-moonbeam.n.dwellir.com/YOUR_API_KEY');
const txHash = '';
// 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-moonbeam.n.dwellir.com/YOUR_API_KEY'))
tx_hash = ''
# 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 - Moonbeam RPC Method
# eth_accounts
Returns a list of addresses owned by the client on Moonbeam.
> **Why Moonbeam?** Build on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects with full EVM compatibility on Polkadot, native XCM cross-chain messaging, 10K+ TPS, 24% staking APR, and $0.015 transaction costs.
## 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 cross-chain dApp developers, Polkadot builders, and teams requiring multi-chain 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-moonbeam.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-moonbeam.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-moonbeam.n.dwellir.com/YOUR_API_KEY');
const accounts = await provider.listAccounts();
console.log('Accounts:', accounts);
```
```python
def get_accounts():
response = requests.post(
'https://api-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# eth_blockNumber
Returns the number of the most recent block on Moonbeam.
> **Why Moonbeam?** Build on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects with full EVM compatibility on Polkadot, native XCM cross-chain messaging, 10K+ TPS, 24% staking APR, and $0.015 transaction costs.
## When to Use This Method
`eth_blockNumber` is fundamental for cross-chain dApp developers, Polkadot builders, and teams requiring multi-chain interoperability:
- **Syncing Applications** — Keep your dApp in sync with the latest Moonbeam 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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('Moonbeam block:', blockNumber);
// Using ethers.js
const provider = new JsonRpcProvider('https://api-moonbeam.n.dwellir.com/YOUR_API_KEY');
const blockNumber = await provider.getBlockNumber();
console.log('Moonbeam block:', blockNumber);
```
```python
def get_block_number():
response = requests.post(
'https://api-moonbeam.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'Moonbeam block: {block_number}')
# Using web3.py
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-moonbeam.n.dwellir.com/YOUR_API_KEY'))
print(f'Moonbeam 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-moonbeam.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("Moonbeam block: %d\n", blockNumber)
}
```
## Common Use Cases
### 1. Block Confirmation Counter
Monitor transaction confirmations on Moonbeam:
```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 Moonbeam:
```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 Moonbeam 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-moonbeam.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 - Moonbeam RPC Method
# eth_call
Executes a new message call immediately without creating a transaction on Moonbeam. Used for reading smart contract state.
> **Why Moonbeam?** Build on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects with full EVM compatibility on Polkadot, native XCM cross-chain messaging, 10K+ TPS, 24% staking APR, and $0.015 transaction costs.
## 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# eth_chainId
Returns the chain ID used for transaction signing on Moonbeam.
> **Why Moonbeam?** Build on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects with full EVM compatibility on Polkadot, native XCM cross-chain messaging, 10K+ TPS, 24% staking APR, and $0.015 transaction costs.
## 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-moonbeam.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-moonbeam.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-moonbeam.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-moonbeam.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(Moonbeam)
# eth_coinbase
Get coinbase address on the Moonbeam network.
## Parameters
Varies by method. Please refer to the official [Moonbeam 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-moonbeam.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-moonbeam.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 [Moonbeam documentation](/docs/moonbeam).*
---
## eth_estimateGas - Moonbeam RPC Method
# eth_estimateGas
Estimates the gas necessary to execute a transaction on Moonbeam.
> **Why Moonbeam?** Build on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects with full EVM compatibility on Polkadot, native XCM cross-chain messaging, 10K+ TPS, 24% staking APR, and $0.015 transaction costs.
## 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
## 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-moonbeam.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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# eth_feeHistory
Returns historical gas information on Moonbeam 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
## 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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# eth_gasPrice
Returns the current gas price on Moonbeam in wei.
> **Why Moonbeam?** Build on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects with full EVM compatibility on Polkadot, native XCM cross-chain messaging, 10K+ TPS, 24% staking APR, and $0.015 transaction costs.
## 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
## 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-moonbeam.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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# eth_getBalance
Returns the balance of a given address on Moonbeam.
> **Why Moonbeam?** Build on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects with full EVM compatibility on Polkadot, native XCM cross-chain messaging, 10K+ TPS, 24% staking APR, and $0.015 transaction costs.
## 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# eth_getBlockByHash
Returns information about a block by hash on Moonbeam.
> **Why Moonbeam?** Build on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects with full EVM compatibility on Polkadot, native XCM cross-chain messaging, 10K+ TPS, 24% staking APR, and $0.015 transaction costs.
## 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# eth_getBlockByNumber
Returns information about a block by block number on Moonbeam.
> **Why Moonbeam?** Build on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects with full EVM compatibility on Polkadot, native XCM cross-chain messaging, 10K+ TPS, 24% staking APR, and $0.015 transaction costs.
## 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# eth_getCode
Returns the bytecode at a given address on Moonbeam.
> **Why Moonbeam?** Build on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects with full EVM compatibility on Polkadot, native XCM cross-chain messaging, 10K+ TPS, 24% staking APR, and $0.015 transaction costs.
## 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
## 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-moonbeam.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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# eth_getFilterChanges
Polling method for a filter on Moonbeam, 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# eth_getFilterLogs
Returns an array of all logs matching filter with given ID on Moonbeam.
## Use Cases
- **Historical queries** - Get all matching logs for a filter
- **Full event history** - Retrieve complete event data for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
## 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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# eth_getLogs
Returns an array of all logs matching a given filter object on Moonbeam.
> **Why Moonbeam?** Build on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects with full EVM compatibility on Polkadot, native XCM cross-chain messaging, 10K+ TPS, 24% staking APR, and $0.015 transaction costs.
## Use Cases
The `eth_getLogs` method is essential for:
- **Event indexing** - Track contract events for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# eth_getStorageAt
Returns the value from a storage position at a given address on Moonbeam.
## Use Cases
- **Contract analysis** - Read raw storage values
- **State verification** - Verify contract state
- **Security auditing** - Analyze storage layout for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# eth_getTransactionByHash
Returns the information about a transaction by transaction hash on Moonbeam.
> **Why Moonbeam?** Build on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects with full EVM compatibility on Polkadot, native XCM cross-chain messaging, 10K+ TPS, 24% staking APR, and $0.015 transaction costs.
## 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# eth_getTransactionCount
Returns the number of transactions sent from an address on Moonbeam (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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
## 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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# eth_getTransactionReceipt
Returns the receipt of a transaction by transaction hash on Moonbeam. Receipt is only available for mined transactions.
> **Why Moonbeam?** Build on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects with full EVM compatibility on Polkadot, native XCM cross-chain messaging, 10K+ TPS, 24% staking APR, and $0.015 transaction costs.
## 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
## 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-moonbeam.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-moonbeam.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-moonbeam.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-moonbeam.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(Moonbeam)
# eth_hashrate
Get node hashrate on the Moonbeam network.
## Parameters
Varies by method. Please refer to the official [Moonbeam 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-moonbeam.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-moonbeam.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 [Moonbeam documentation](/docs/moonbeam).*
---
## eth_maxPriorityFeePerGas - Moonbeam RPC Method
# eth_maxPriorityFeePerGas
Returns the current recommended priority fee per gas on Moonbeam 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
## 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-moonbeam.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-moonbeam.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-moonbeam.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(Moonbeam)
# eth_mining
Check if node is mining on the Moonbeam network.
## Parameters
Varies by method. Please refer to the official [Moonbeam 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-moonbeam.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-moonbeam.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 [Moonbeam documentation](/docs/moonbeam).*
---
## eth_newBlockFilter - Moonbeam RPC Method
# eth_newBlockFilter
Creates a filter on Moonbeam 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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# eth_newFilter
Creates a filter object on Moonbeam to notify when state changes (logs).
## Use Cases
- **Event monitoring** - Subscribe to contract events
- **Real-time updates** - Track events for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# eth_newPendingTransactionFilter
Creates a filter on Moonbeam 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-moonbeam.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-moonbeam.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(Moonbeam)
# eth_protocolVersion
Get protocol version on the Moonbeam network.
## Parameters
Varies by method. Please refer to the official [Moonbeam 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-moonbeam.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-moonbeam.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 [Moonbeam documentation](/docs/moonbeam).*
---
## eth_sendRawTransaction - Moonbeam RPC Method
# eth_sendRawTransaction
Submits a pre-signed transaction for broadcast to Moonbeam.
> **Why Moonbeam?** Build on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects with full EVM compatibility on Polkadot, native XCM cross-chain messaging, 10K+ TPS, 24% staking APR, and $0.015 transaction costs.
## 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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-moonbeam.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 (wal...(Moonbeam)
# eth_sendTransaction
> **Important**: Dwellir's shared Moonbeam 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-moonbeam.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...(Moonbeam)
# 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-moonbeam.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-moonbeam.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 [Moonbeam documentation](/docs/moonbeam).*
---
## eth_syncing - Moonbeam RPC Method
# eth_syncing
Returns syncing status of Moonbeam 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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# eth_uninstallFilter
Uninstalls a filter on Moonbeam. 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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# grandpa_roundState
Returns the state of the current GRANDPA finality round on Moonbeam. 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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)
---
## Moonbeam RPC with Dwellir
# Moonbeam – Ethereum-Compatible Smart Contracts on Polkadot
## Why Build on Moonbeam?
Moonbeam is the leading Ethereum-compatible smart contract platform on Polkadot, offering seamless EVM compatibility with powerful cross-chain capabilities:
### 🔗 **Native Cross-Chain Integration**
- **Universal Connectivity** - Connect with 50+ blockchains via Axelar, LayerZero, Wormhole, and Hyperlane
- **Bridge-Free Communication** - Direct cross-chain messaging without traditional bridges
- **Multi-Chain dApps** - Build applications that interact with Ethereum, Polygon, Avalanche, and more
### ⚡ **Full Ethereum Compatibility**
- **100% EVM Compatible** - Deploy existing Solidity contracts without modification
- **Familiar Tooling** - Use MetaMask, Hardhat, Remix, and other Ethereum tools
- **Web3 API Mirror** - Complete Ethereum Web3 RPC implementation
### 🌐 **Polkadot Ecosystem Benefits**
- **Shared Security** - Protected by Polkadot's validator network
- **On-Chain Governance** - Community-driven protocol upgrades
- **Substrate Framework** - Advanced features beyond standard EVM
## Quick Start with Moonbeam
Connect to Moonbeam in seconds with Dwellir's optimized endpoints:
### Installation & Setup
```javascript
// Connect to Moonbeam mainnet
const provider = new JsonRpcProvider(
'https://api-moonbeam.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 (GLMR)
const balance = await provider.getBalance('0x...');
console.log('Balance:', balance.toString());
```
```javascript
const Web3 = require('web3');
// Connect to Moonbeam mainnet
const web3 = new Web3(
'https://api-moonbeam.n.dwellir.com/YOUR_API_KEY'
);
// Get chain ID to verify connection
const chainId = await web3.eth.getChainId();
console.log('Connected to Moonbeam:', chainId === 1284);
// Get gas price
const gasPrice = await web3.eth.getGasPrice();
console.log('Current gas price:', gasPrice);
```
```typescript
// Create Moonbeam client
const client = createPublicClient({
chain: moonbeam,
transport: http('https://api-moonbeam.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 Moonbeam mainnet
web3 = Web3(Web3.HTTPProvider(
'https://api-moonbeam.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
1284
Mainnet
Block Time
12 seconds
Average
Gas Token
GLMR
Native token
RPC Standard
Ethereum
EVM Compatible
## JSON-RPC API Reference
Moonbeam supports the full [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/) plus Substrate-specific methods.
## Common Integration Patterns
### 🔄 Cross-Chain Messaging
Leverage Moonbeam's native cross-chain capabilities:
```javascript
// Example: Send message to Ethereum via Axelar
const sdk = new AxelarGMPSDK({
environment: 'mainnet',
moonbeamRpcUrl: 'https://api-moonbeam.n.dwellir.com/YOUR_API_KEY'
});
// Send cross-chain transaction
const tx = await sdk.sendToken({
destinationChain: 'ethereum',
destinationAddress: '0x...',
symbol: 'USDC',
amount: '100'
});
```
### 💰 Multi-Asset Transactions
Work with GLMR and XC-20 tokens:
```javascript
// GLMR balance (native gas token)
const glmrBalance = await provider.getBalance(address);
// XC-20 token balance (ERC-20 compatible)
const tokenContract = new ethers.Contract(
'0xTokenAddress',
['function balanceOf(address) view returns (uint256)'],
provider
);
const tokenBalance = await tokenContract.balanceOf(address);
```
### 🔍 Event Filtering with Pagination
Query contract events efficiently:
```javascript
// Query events with proper 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. **WebSocket Subscriptions**
Use WebSockets for real-time updates:
```javascript
const wsProvider = new ethers.WebSocketProvider(
'wss://api-moonbeam.n.dwellir.com/YOUR_API_KEY'
);
// Subscribe to new blocks
wsProvider.on('block', (blockNumber) => {
console.log('New block:', blockNumber);
});
// Subscribe to pending transactions
wsProvider.on('pending', (txHash) => {
console.log('Pending tx:', txHash);
});
```
### 3. **Smart Caching**
Cache immutable blockchain data:
```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"
Ensure sufficient GLMR 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,
gasPrice: feeData.gasPrice, // Moonbeam uses legacy gas pricing
gasLimit: 21000n
};
```
### Error: "Rate limit exceeded"
Implement exponential backoff:
```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 Moonbeam mainnet
curl -X POST https://api-moonbeam.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}'
# Test Moonriver (testnet)
curl -X POST https://api-moonriver.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}'
```
### Test with Ethers.js
```javascript
// Test mainnet connection
const mainnetProvider = new JsonRpcProvider(
'https://api-moonbeam.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 1284n
```
### Test with Web3.py
```python
from web3 import Web3
# Test connection
web3 = Web3(Web3.HTTPProvider(
'https://api-moonbeam.n.dwellir.com/YOUR_API_KEY'
))
print('Connected:', web3.is_connected())
print('Chain ID:', web3.eth.chain_id) # Should be 1284
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-moonbeam.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
```
### Migrating from Ethereum
Moonbeam is fully EVM-compatible:
```javascript
// Your Ethereum contracts work on Moonbeam without changes
const contract = new ethers.Contract(
contractAddress,
abi,
provider // Just change the provider to Moonbeam!
);
// All contract interactions work the same
const result = await contract.someFunction();
```
## Resources & Tools
### Official Resources
- [Moonbeam Network](https://moonbeam.network/)
- [Moonbeam Documentation](https://docs.moonbeam.network/)
- [Moonbeam GitHub](https://github.com/moonbeam-foundation/moonbeam)
- [Moonscan Explorer](https://moonscan.io/)
### Cross-Chain Tools
- [Axelar Network](https://axelar.network/)
- [LayerZero](https://layerzero.network/)
- [Wormhole](https://wormhole.com/)
- [Hyperlane](https://hyperlane.xyz/)
### Developer Tools
- [Hardhat](https://hardhat.org/)
- [Remix IDE](https://remix.ethereum.org/)
- [Foundry](https://getfoundry.sh/)
- [Truffle](https://trufflesuite.com/)
### Need Help?
- 📧 **Email**: support@dwellir.com
- 📚 **Docs**: You're here!
- 🎯 **Dashboard**: [dashboard.dwellir.com](https://dashboard.dwellir.com)
---
*Start building cross-chain applications on Moonbeam with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## net_listening - Moonbeam RPC Method
# net_listening
Returns `true` if client is actively listening for network connections on Moonbeam.
## 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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# net_peerCount
Returns number of peers currently connected to Moonbeam 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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# net_version
Returns the current network ID on Moonbeam.
## 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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# payment_queryFeeDetails
Returns a detailed breakdown of fees for a given extrinsic on Moonbeam. 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-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# payment_queryInfo
Estimates the fee for an extrinsic on Moonbeam.
## Use Cases
- **Fee estimation** - Calculate transaction costs before sending
- **UI display** - Show fees to users for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# rpc_methods
Returns a list of all RPC methods available on Moonbeam.
## Use Cases
- **API discovery** - List all available methods
- **Compatibility checking** - Verify method availability for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# state_call
Calls a runtime API method on Moonbeam.
## Use Cases
- **Runtime computations** - Execute runtime logic without transactions
- **Account queries** - Use AccountNonceApi for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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(Moonbeam)
## 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-moonbeam.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-moonbeam.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-moonbeam.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-moonbeam.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`](./state_getKeysPaged) - Get keys with pagination
- [`state_getStorage`](./state_getStorage) - Get storage value
- [`state_getMetadata`](./state_getMetadata) - Get metadata to decode keys
---
## state_getKeysPaged - Moonbeam RPC Method
# state_getKeysPaged
Returns storage keys with pagination on Moonbeam.
## Use Cases
- **Storage iteration** - Enumerate storage map entries
- **Data export** - Bulk export chain data for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# state_getMetadata
Returns the runtime metadata on Moonbeam.
## Use Cases
- **Runtime introspection** - Discover available pallets and calls
- **Extrinsic building** - Get call and type information for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# state_getRuntimeVersion
Returns the runtime version on Moonbeam.
## Use Cases
- **Version checking** - Verify runtime compatibility
- **Upgrade detection** - Monitor for runtime upgrades on cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# state_getStorage
Returns a storage entry at a specific key on Moonbeam.
> **Why Moonbeam?** Build on the cross-chain connected EVM platform on Polkadot with $65M+ TVL and 100+ projects with full EVM compatibility on Polkadot, native XCM cross-chain messaging, 10K+ TPS, 24% staking APR, and $0.015 transaction costs.
## Use Cases
- **State queries** - Read on-chain storage values
- **Account balances** - Query account data for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# state_queryStorageAt
Query multiple storage keys at a specific block on Moonbeam.
## Use Cases
- **Batch queries** - Efficiently query multiple storage items
- **Snapshot state** - Get consistent multi-key state for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# system_chain
Returns the chain name on Moonbeam.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_chain",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl https://api-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# system_health
Returns the health status of the Moonbeam node.
## Use Cases
- **Health checks** - Monitor node availability
- **Load balancing** - Route traffic based on health for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# system_name
Returns the node implementation name on Moonbeam.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_name",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl https://api-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# system_properties
Returns chain properties including token symbol and decimals on Moonbeam.
## Use Cases
- **Token formatting** - Get decimals and symbol for cross-chain DeFi, multi-chain dApps, and Ethereum-to-Polkadot bridging via XCM, Axelar, LayerZero, and Wormhole
- **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-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# system_version
Returns the node implementation version on Moonbeam.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_version",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl https://api-moonbeam.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-moonbeam.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 - Moonbeam RPC Method
# web3_clientVersion
Returns the current client version on Moonbeam.
## 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-moonbeam.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-moonbeam.n.dwellir.com/YOUR_API_KEY');
const version = await provider.send('web3_clientVersion', []);
console.log('Client version:', version);
```
---
## web3_sha3 - Moonbeam RPC Method
# web3_sha3
Returns Keccak-256 (not standard SHA3-256) of the given data on Moonbeam.
## 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-moonbeam.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-moonbeam.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 - Moonriver RPC Method
# author_pendingExtrinsics
Returns all pending extrinsics in the transaction pool on Moonriver.
## Use Cases
- **Mempool monitoring** - Track pending transactions
- **Transaction status** - Check if your transaction is pending for production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "author_pendingExtrinsics",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Moonriver RPC Method
# author_rotateKeys
Generate a new set of session keys on Moonriver. 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 production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "author_rotateKeys",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Moonriver 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 production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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('');
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 = ''
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 - Moonriver RPC Method
# author_submitExtrinsic
Submit a signed extrinsic to Moonriver for inclusion in a block.
## Use Cases
- **Transaction submission** - Broadcast signed transactions
- **dApp interactions** - Execute on-chain operations for production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "author_submitExtrinsic",
"params": ["0x..."],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Moonriver RPC Method
# beefy_getFinalizedHead
Returns the block hash of the latest BEEFY-finalized block on Moonriver. 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 production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "beefy_getFinalizedHead",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Moonriver RPC Method
# chain_getBlock
Retrieves complete block information from Moonriver, including the block header, extrinsics, and justifications.
> **Why Moonriver?** Build on the Moonbeam canary network on Kusama for real-world testing of EVM dApps with Moonbeam code ships here first, full EVM compatibility on Kusama, 80% fee burn mechanism, and XCM cross-chain messaging.
## 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 production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "chain_getBlock",
"params": [],
"id": 1
}'
# Get specific block
curl \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "chain_getBlock",
"params": ["0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3"],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Moonriver RPC Method
# chain_getBlockHash
Returns the block hash for a given block number on Moonriver.
## Use Cases
- **Historical queries** - Convert block numbers to hashes
- **Block navigation** - Navigate blockchain history for production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "chain_getBlockHash",
"params": [1000000],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Moonriver RPC Method
# chain_getFinalizedHead
Returns the hash of the last finalized block on Moonriver.
## Use Cases
- **Confirmed state** - Query state that cannot be reverted
- **Transaction confirmation** - Verify transaction finality for production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "chain_getFinalizedHead",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Moonriver RPC Method
# chain_getHeader
Returns the block header for a given hash on Moonriver.
## Use Cases
- **Lightweight queries** - Get header without full block data
- **Chain synchronization** - Track block production for production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "chain_getHeader",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Moonriver RPC Method
# chain_subscribeFinalizedHeads
Subscribe to receive notifications when blocks are finalized on Moonriver. 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 production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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('');
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 = ''
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 - Moonriver RPC Method
# chain_subscribeNewHeads
Subscribe to receive notifications when new block headers are produced on Moonriver. This WebSocket subscription provides real-time updates for each new block.
## Use Cases
- **Block monitoring** - Track new blocks in real-time for production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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('');
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 = ''
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 - Moonriver RPC Method
# eth_accounts
Returns a list of addresses owned by the client on Moonriver.
> **Why Moonriver?** Build on the Moonbeam canary network on Kusama for real-world testing of EVM dApps with Moonbeam code ships here first, full EVM compatibility on Kusama, 80% fee burn mechanism, and XCM cross-chain messaging.
## 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 dApp developers testing on Kusama, early adopters, and teams requiring production-ready experimentation 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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_accounts",
"params": [],
"id": 1
}'
```
```javascript
// Using fetch
const response = await fetch('', {
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('');
const accounts = await provider.listAccounts();
console.log('Accounts:', accounts);
```
```python
def get_accounts():
response = requests.post(
'',
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(''))
print(f'Accounts: {w3.eth.accounts}')
```
```go
package main
"context"
"fmt"
"log"
"github.com/ethereum/go-ethereum/rpc"
)
func main() {
client, err := rpc.Dial("")
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 - Moonriver RPC Method
# eth_blockNumber
Returns the number of the most recent block on Moonriver.
> **Why Moonriver?** Build on the Moonbeam canary network on Kusama for real-world testing of EVM dApps with Moonbeam code ships here first, full EVM compatibility on Kusama, 80% fee burn mechanism, and XCM cross-chain messaging.
## When to Use This Method
`eth_blockNumber` is fundamental for dApp developers testing on Kusama, early adopters, and teams requiring production-ready experimentation:
- **Syncing Applications** — Keep your dApp in sync with the latest Moonriver blockchain state
- **Transaction Monitoring** — Verify confirmations by comparing block numbers
- **Event Filtering** — Set the correct block range for querying logs on production-grade dApp testing, early feature deployment, and Kusama-based 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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_blockNumber",
"params": [],
"id": 1
}'
```
```javascript
// Using fetch
const response = await fetch('', {
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('Moonriver block:', blockNumber);
// Using ethers.js
const provider = new JsonRpcProvider('');
const blockNumber = await provider.getBlockNumber();
console.log('Moonriver block:', blockNumber);
```
```python
def get_block_number():
response = requests.post(
'',
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'Moonriver block: {block_number}')
# Using web3.py
from web3 import Web3
w3 = Web3(Web3.HTTPProvider(''))
print(f'Moonriver block: {w3.eth.block_number}')
```
```go
package main
"context"
"fmt"
"log"
"github.com/ethereum/go-ethereum/ethclient"
)
func main() {
client, err := ethclient.Dial("")
if err != nil {
log.Fatal(err)
}
blockNumber, err := client.BlockNumber(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("Moonriver block: %d\n", blockNumber)
}
```
## Common Use Cases
### 1. Block Confirmation Counter
Monitor transaction confirmations on Moonriver:
```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 Moonriver:
```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 Moonriver 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('', {
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 - Moonriver RPC Method
# eth_call
Executes a new message call immediately without creating a transaction on Moonriver. Used for reading smart contract state.
> **Why Moonriver?** Build on the Moonbeam canary network on Kusama for real-world testing of EVM dApps with Moonbeam code ships here first, full EVM compatibility on Kusama, 80% fee burn mechanism, and XCM cross-chain messaging.
## 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 production-grade dApp testing, early feature deployment, and Kusama-based 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": "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 \
-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('');
// 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(''))
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("")
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 - Moonriver RPC Method
# eth_chainId
Returns the chain ID used for transaction signing on Moonriver.
> **Why Moonriver?** Build on the Moonbeam canary network on Kusama for real-world testing of EVM dApps with Moonbeam code ships here first, full EVM compatibility on Kusama, 80% fee burn mechanism, and XCM cross-chain messaging.
## 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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_chainId",
"params": [],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
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(''))
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("")
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 - Moonriver RPC Method
# eth_estimateGas
Estimates the gas necessary to execute a transaction on Moonriver.
> **Why Moonriver?** Build on the Moonbeam canary network on Kusama for real-world testing of EVM dApps with Moonbeam code ships here first, full EVM compatibility on Kusama, 80% fee burn mechanism, and XCM cross-chain messaging.
## 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 production-grade dApp testing, early feature deployment, and Kusama-based 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": "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 \
-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('');
// 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(''))
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("")
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 - Moonriver RPC Method
# eth_feeHistory
Returns historical gas information on Moonriver 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 production-grade dApp testing, early feature deployment, and Kusama-based 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 \
-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('');
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(''))
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 - Moonriver RPC Method
# eth_gasPrice
Returns the current gas price on Moonriver in wei.
> **Why Moonriver?** Build on the Moonbeam canary network on Kusama for real-world testing of EVM dApps with Moonbeam code ships here first, full EVM compatibility on Kusama, 80% fee burn mechanism, and XCM cross-chain messaging.
## 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 production-grade dApp testing, early feature deployment, and Kusama-based 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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_gasPrice",
"params": [],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
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(''))
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("")
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 - Moonriver RPC Method
# eth_getBalance
Returns the balance of a given address on Moonriver.
> **Why Moonriver?** Build on the Moonbeam canary network on Kusama for real-world testing of EVM dApps with Moonbeam code ships here first, full EVM compatibility on Kusama, 80% fee burn mechanism, and XCM cross-chain messaging.
## 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 production-grade dApp testing, early feature deployment, and Kusama-based 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": [
"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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
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(''))
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("")
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 - Moonriver RPC Method
# eth_getBlockByHash
Returns information about a block by hash on Moonriver.
> **Why Moonriver?** Build on the Moonbeam canary network on Kusama for real-world testing of EVM dApps with Moonbeam code ships here first, full EVM compatibility on Kusama, 80% fee burn mechanism, and XCM cross-chain messaging.
## 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 production-grade dApp testing, early feature deployment, and Kusama-based 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": [
"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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByHash",
"params": [
"0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3",
false
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
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(''))
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("")
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 - Moonriver RPC Method
# eth_getBlockByNumber
Returns information about a block by block number on Moonriver.
> **Why Moonriver?** Build on the Moonbeam canary network on Kusama for real-world testing of EVM dApps with Moonbeam code ships here first, full EVM compatibility on Kusama, 80% fee burn mechanism, and XCM cross-chain messaging.
## 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 production-grade dApp testing, early feature deployment, and Kusama-based 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": "0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3",
"parentHash": "0x...",
"timestamp": "0x64d8f6d0",
"gasUsed": "0x1234",
"gasLimit": "0x1c9c380",
"transactions": [],
"baseFeePerGas": "0x5f5e100"
}
}
```
## Code Examples
```bash
curl -X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params": ["latest", false],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
// 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(''))
# 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("")
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 - Moonriver RPC Method
# eth_getCode
Returns the bytecode at a given address on Moonriver.
> **Why Moonriver?** Build on the Moonbeam canary network on Kusama for real-world testing of EVM dApps with Moonbeam code ships here first, full EVM compatibility on Kusama, 80% fee burn mechanism, and XCM cross-chain messaging.
## 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 production-grade dApp testing, early feature deployment, and Kusama-based 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": [
"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
"latest"
],
"id": 1
}
```
## Returns
| Type | Description |
|------|-------------|
| `DATA` | Contract bytecode or `0x` if EOA |
## Code Examples
```bash
curl -X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getCode",
"params": [
"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
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(''))
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("")
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 - Moonriver RPC Method
# eth_getFilterChanges
Polling method for a filter on Moonriver, returns an array of logs since last poll.
## Use Cases
- **Event streaming** - Get new events incrementally
- **Real-time monitoring** - Track contract activity for production-grade dApp testing, early feature deployment, and Kusama-based 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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getFilterChanges",
"params": ["0x1"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
// 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 - Moonriver RPC Method
# eth_getFilterLogs
Returns an array of all logs matching filter with given ID on Moonriver.
## Use Cases
- **Historical queries** - Get all matching logs for a filter
- **Full event history** - Retrieve complete event data for production-grade dApp testing, early feature deployment, and Kusama-based 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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getFilterLogs",
"params": ["0x1"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
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 - Moonriver RPC Method
# eth_getLogs
Returns an array of all logs matching a given filter object on Moonriver.
> **Why Moonriver?** Build on the Moonbeam canary network on Kusama for real-world testing of EVM dApps with Moonbeam code ships here first, full EVM compatibility on Kusama, 80% fee burn mechanism, and XCM cross-chain messaging.
## Use Cases
The `eth_getLogs` method is essential for:
- **Event indexing** - Track contract events for production-grade dApp testing, early feature deployment, and Kusama-based 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": "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 \
-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('');
// 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(''))
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("")
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 - Moonriver RPC Method
# eth_getStorageAt
Returns the value from a storage position at a given address on Moonriver.
## Use Cases
- **Contract analysis** - Read raw storage values
- **State verification** - Verify contract state
- **Security auditing** - Analyze storage layout for production-grade dApp testing, early feature deployment, and Kusama-based 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": [
"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
"0x0",
"latest"
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getStorageAt",
"params": [
"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
"0x0",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
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(''))
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 - Moonriver RPC Method
# eth_getTransactionByHash
Returns the information about a transaction by transaction hash on Moonriver.
> **Why Moonriver?** Build on the Moonbeam canary network on Kusama for real-world testing of EVM dApps with Moonbeam code ships here first, full EVM compatibility on Kusama, 80% fee burn mechanism, and XCM cross-chain messaging.
## 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 production-grade dApp testing, early feature deployment, and Kusama-based 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": [""],
"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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionByHash",
"params": [""],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
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(''))
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("")
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 - Moonriver RPC Method
# eth_getTransactionCount
Returns the number of transactions sent from an address on Moonriver (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 production-grade dApp testing, early feature deployment, and Kusama-based 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": [
"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
"latest"
],
"id": 1
}
```
## Code Examples
```bash
curl -X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [
"5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
"latest"
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
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(''))
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 - Moonriver RPC Method
# eth_getTransactionReceipt
Returns the receipt of a transaction by transaction hash on Moonriver. Receipt is only available for mined transactions.
> **Why Moonriver?** Build on the Moonbeam canary network on Kusama for real-world testing of EVM dApps with Moonbeam code ships here first, full EVM compatibility on Kusama, 80% fee burn mechanism, and XCM cross-chain messaging.
## 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 production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
## 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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": [""],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
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(''))
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("")
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 - Moonriver RPC Method
# eth_maxPriorityFeePerGas
Returns the current recommended priority fee per gas on Moonriver 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 production-grade dApp testing, early feature deployment, and Kusama-based 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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_maxPriorityFeePerGas",
"params": [],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
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(''))
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 - Moonriver RPC Method
# eth_newBlockFilter
Creates a filter on Moonriver 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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_newBlockFilter",
"params": [],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
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 - Moonriver RPC Method
# eth_newFilter
Creates a filter object on Moonriver to notify when state changes (logs).
## Use Cases
- **Event monitoring** - Subscribe to contract events
- **Real-time updates** - Track events for production-grade dApp testing, early feature deployment, and Kusama-based 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": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY",
"topics": [""]
}],
"id": 1
}
```
## Returns
| Type | Description |
|------|-------------|
| `QUANTITY` | Filter ID |
## Code Examples
```bash
curl -X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_newFilter",
"params": [{
"fromBlock": "latest",
"address": "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
// 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 - Moonriver RPC Method
# eth_newPendingTransactionFilter
Creates a filter on Moonriver 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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_newPendingTransactionFilter",
"params": [],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
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 - Moonriver RPC Method
# eth_sendRawTransaction
Submits a pre-signed transaction for broadcast to Moonriver.
> **Why Moonriver?** Build on the Moonbeam canary network on Kusama for real-world testing of EVM dApps with Moonbeam code ships here first, full EVM compatibility on Kusama, 80% fee burn mechanism, and XCM cross-chain messaging.
## 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 production-grade dApp testing, early feature deployment, and Kusama-based 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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_sendRawTransaction",
"params": ["0xf86c808504a817c80082520894..."],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
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(''))
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("")
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 - Moonriver RPC Method
# eth_syncing
Returns syncing status of Moonriver 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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_syncing",
"params": [],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
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 - Moonriver RPC Method
# eth_uninstallFilter
Uninstalls a filter on Moonriver. 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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_uninstallFilter",
"params": ["0x1"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
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 - Moonriver RPC Method
# grandpa_roundState
Returns the state of the current GRANDPA finality round on Moonriver. GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) is the finality gadget used by Substrate chains.
## Use Cases
- **Finality monitoring** - Track consensus progress for production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "grandpa_roundState",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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)
---
## Moonriver RPC with Dwellir
# Moonriver – Moonbeam's Canary Network on Kusama
## Why Build on Moonriver?
Moonriver is Moonbeam’s canary network on Kusama, delivering the same Substrate foundation and EVM compatibility with faster iteration cycles. It is ideal for deploying and testing EVM and Substrate-based functionality under real economic conditions before promoting to Moonbeam.
### ⚡ Fast Iteration, Real Economics
- Rapid runtime upgrade cadence enables shipping features earlier than Moonbeam.
- Real MOVR token economics and on-chain governance for production-like validation.
- Shared Kusama security provides fast finality while enabling experimentation.
### 🔗 EVM + Substrate Interop
- Full EVM compatibility via Frontier with MetaMask, Hardhat, and Solidity tooling.
- Native Substrate interfaces for storage, blocks, and runtime APIs.
- Seamless migration path to Moonbeam after validation on Moonriver.
## Quick Start with Moonriver
Connect to Moonriver production endpoints with Dwellir’s global network.
### Installation & Setup
```bash
curl -s https://api-moonriver.n.dwellir.com/YOUR_API_KEY \
-H 'Content-Type: application/json' \
-d '{
"jsonrpc": "2.0",
"method": "chain_getHeader",
"params": [],
"id": 1
}'
```
```typescript
async function main() {
const provider = new WsProvider('wss://api-moonriver.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} at ${header.hash}`);
});
// Stop after a short period
setTimeout(async () => {
await unsub();
await api.disconnect();
}, 15000);
}
main().catch(console.error);
```
```rust
use subxt::{OnlineClient, PolkadotConfig};
#[tokio::main]
async fn main() -> Result<(), Box> {
let api = OnlineClient::::from_url(
"wss://api-moonriver.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-moonriver.n.dwellir.com/YOUR_API_KEY"
)
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
0x401a1f9d…1474b
chain_getBlockHash(0)
Native Token
MOVR
18 decimals
SS58 Prefix
1285
system_properties
Relay / Para ID
Kusama / 2023
Parachain on Kusama
Runtime Spec Version
3900
As of 9 Oct 2025
Transaction Version
3
state_getRuntimeVersion
Explorer
Moonscan
moonriver.moonscan.io
### Example Values Used in Docs
These chain-specific variables are used across Moonriver examples:
## Substrate JSON-RPC API Reference
Moonriver exposes standard Substrate RPC namespaces for node telemetry, block production, storage access, and fee estimation. Open method guides from the dropdown below.
## Common Integration Patterns
### Track new blocks (subscriptions)
```typescript
const unsub = await api.rpc.chain.subscribeNewHeads((header) => {
console.log(`New #${header.number} (${header.hash})`);
});
```
### Paginate large storage scans
```typescript
const page = await api.rpc.state.getKeysPaged(
api.query.system.account.keyPrefix(),
100,
'0x',
null
);
console.log('Fetched', page.length, 'System.Account keys');
```
### Estimate fees before broadcast
```typescript
const ext = api.tx.balances.transferAllowDeath(dest, amount);
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 reuse a single ApiPromise instance.
- Use `state_getKeysPaged` for large scans; avoid full-chain traversals.
- Exponential backoff on retries for transient `-32010`/`TooManyRequests` errors.
## Troubleshooting
- **WebSocket failure** – Verify your API key and outbound TCP/443. Try HTTPS for single calls.
- **Type mismatches** – Refresh metadata after runtime upgrades (`api.runtimeVersion`).
- **Invalid address** – Moonriver uses SS58 prefix `1285` for Substrate addresses; EVM `0x…` accounts are also supported in the runtime.
- **Extrinsic rejected** – Decode with `api.registry.findMetaError` to surface module/error.
## Smoke Tests
Run these checks against production endpoints (values as of 9 Oct 2025):
```bash
# Node health
curl -s https://api-moonriver.n.dwellir.com/YOUR_API_KEY \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"system_health","params":[]}'
# Latest block header
curl -s https://api-moonriver.n.dwellir.com/YOUR_API_KEY \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"chain_getHeader","params":[]}'
# Runtime version
curl -s https://api-moonriver.n.dwellir.com/YOUR_API_KEY \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"state_getRuntimeVersion","params":[]}'
```
## Migration Guide
- **Endpoints** – Replace Polkadot/Moonbeam URLs with `https://api-moonriver.n.dwellir.com/YOUR_API_KEY` or `wss://api-moonriver.n.dwellir.com/YOUR_API_KEY`.
- **Addresses** – Use SS58 prefix `1285` for Substrate-style addresses when needed; EVM `0x…` addresses remain valid for account state.
- **Runtime types** – Update custom type bundles as needed and refresh metadata caches after upgrades (specVersion `3900` on Oct 9, 2025).
- **Fees** – Calibrate using `payment_queryInfo`/`payment_queryFeeDetails` for MOVR-denominated fees.
- **XCM/Parachain** – Confirm HRMP channels and destination parachain IDs for XCM; Moonriver is parachain `2023` on Kusama.
## Resources & Tools
- [Moonriver Moonscan Explorer](https://moonriver.moonscan.io)
- [Subscan – Moonriver](https://moonriver.subscan.io)
- [Moonbeam Docs – Moonriver](https://docs.moonbeam.network/builders/get-started/networks/moonriver/)
- [Substrate Developer Hub](https://docs.substrate.io/)
- [Dwellir Dashboard – Get your API key](https://dashboard.dwellir.com/register)
---
## net_listening - Moonriver RPC Method
# net_listening
Returns `true` if client is actively listening for network connections on Moonriver.
## 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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "net_listening",
"params": [],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
const listening = await provider.send('net_listening', []);
console.log('Node listening:', listening);
```
## Related Methods
- [`net_peerCount`](./net_peerCount) - Get peer count
---
## net_peerCount - Moonriver RPC Method
# net_peerCount
Returns number of peers currently connected to Moonriver 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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "net_peerCount",
"params": [],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
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 - Moonriver RPC Method
# net_version
Returns the current network ID on Moonriver.
## 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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "net_version",
"params": [],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
const networkId = await provider.send('net_version', []);
console.log('Network ID:', networkId);
```
## Related Methods
- [`eth_chainId`](./eth_chainId) - Get chain ID
---
## payment_queryFeeDetails - Moonriver RPC Method
# payment_queryFeeDetails
Returns a detailed breakdown of fees for a given extrinsic on Moonriver. 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 production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "payment_queryFeeDetails",
"params": ["0x...encodedExtrinsic"],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
# 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 - Moonriver RPC Method
# payment_queryInfo
Estimates the fee for an extrinsic on Moonriver.
## Use Cases
- **Fee estimation** - Calculate transaction costs before sending
- **UI display** - Show fees to users for production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "payment_queryInfo",
"params": ["0x..."],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Moonriver RPC Method
# rpc_methods
Returns a list of all RPC methods available on Moonriver.
## Use Cases
- **API discovery** - List all available methods
- **Compatibility checking** - Verify method availability for production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "rpc_methods",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Moonriver RPC Method
# state_call
Calls a runtime API method on Moonriver.
## Use Cases
- **Runtime computations** - Execute runtime logic without transactions
- **Account queries** - Use AccountNonceApi for production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-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('');
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(Moonriver)
## 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-moonriver.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-moonriver.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-moonriver.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-moonriver.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`](./state_getKeysPaged) - Get keys with pagination
- [`state_getStorage`](./state_getStorage) - Get storage value
- [`state_getMetadata`](./state_getMetadata) - Get metadata to decode keys
---
## state_getKeysPaged - Moonriver RPC Method
# state_getKeysPaged
Returns storage keys with pagination on Moonriver.
## Use Cases
- **Storage iteration** - Enumerate storage map entries
- **Data export** - Bulk export chain data for production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "state_getKeysPaged",
"params": ["0x26aa394eea5630e07c48ae0c9558cef7", 100],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Moonriver RPC Method
# state_getMetadata
Returns the runtime metadata on Moonriver.
## Use Cases
- **Runtime introspection** - Discover available pallets and calls
- **Extrinsic building** - Get call and type information for production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "state_getMetadata",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Moonriver RPC Method
# state_getRuntimeVersion
Returns the runtime version on Moonriver.
## Use Cases
- **Version checking** - Verify runtime compatibility
- **Upgrade detection** - Monitor for runtime upgrades on production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "state_getRuntimeVersion",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Moonriver RPC Method
# state_getStorage
Returns a storage entry at a specific key on Moonriver.
> **Why Moonriver?** Build on the Moonbeam canary network on Kusama for real-world testing of EVM dApps with Moonbeam code ships here first, full EVM compatibility on Kusama, 80% fee burn mechanism, and XCM cross-chain messaging.
## Use Cases
- **State queries** - Read on-chain storage values
- **Account balances** - Query account data for production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "state_getStorage",
"params": [""],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Moonriver RPC Method
# state_queryStorageAt
Query multiple storage keys at a specific block on Moonriver.
## Use Cases
- **Batch queries** - Efficiently query multiple storage items
- **Snapshot state** - Get consistent multi-key state for production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "state_queryStorageAt",
"params": [[""]],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Moonriver RPC Method
# system_chain
Returns the chain name on Moonriver.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_chain",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "system_chain",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Moonriver RPC Method
# system_health
Returns the health status of the Moonriver node.
## Use Cases
- **Health checks** - Monitor node availability
- **Load balancing** - Route traffic based on health for production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "system_health",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 = ''
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 - Moonriver RPC Method
# system_name
Returns the node implementation name on Moonriver.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_name",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "system_name",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Moonriver RPC Method
# system_properties
Returns chain properties including token symbol and decimals on Moonriver.
## Use Cases
- **Token formatting** - Get decimals and symbol for production-grade dApp testing, early feature deployment, and Kusama-based EVM applications
- **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 \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "system_properties",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Moonriver RPC Method
# system_version
Returns the node implementation version on Moonriver.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_version",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl \
-X POST \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "system_version",
"params": [],
"id": 1
}'
```
```javascript
const provider = new WsProvider('');
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 - Moonriver RPC Method
# web3_clientVersion
Returns the current client version on Moonriver.
## 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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "web3_clientVersion",
"params": [],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
const version = await provider.send('web3_clientVersion', []);
console.log('Client version:', version);
```
---
## web3_sha3 - Moonriver RPC Method
# web3_sha3
Returns Keccak-256 (not standard SHA3-256) of the given data on Moonriver.
## 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 \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "web3_sha3",
"params": ["0x68656c6c6f"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('');
// 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);
```
---
## BlockSTM — Parallel Execution
## Overview
BlockSTM executes non-conflicting transactions in parallel using optimistic concurrency. This increases throughput while preserving deterministic results.
## Developer Guidance
- Minimize write conflicts: design contracts/modules so that common transactions touch disjoint storage/resources.
- Batch reads: group read-heavy operations to reduce contention.
- Idempotent semantics: ensure handlers tolerate retries in speculative execution.
## Practical Tips
- Structure Move resources so unrelated operations touch distinct objects/resources.
## Observability
- Monitor gas usage and failure modes during spikes.
- Use Move simulations and load testing to forecast cost under load.
---
## Fast Finality Settlement (1–3s)
## Overview
Transactions on Movement finalize quickly, providing a near real-time UX. Builders can reduce polling intervals and provide faster confirmations.
## How It Works
Movement achieves fast finality through its optimized consensus mechanism and the Move VM's parallel execution engine. Unlike traditional blockchains where finality can take minutes or even hours, Movement's architecture combines Byzantine Fault Tolerant (BFT) consensus with optimistic execution to deliver transaction finality in 1-3 seconds. The shared sequencer (M1) pre-orders transactions deterministically, while the Move VM executes them in parallel using Block-STM, eliminating many of the bottlenecks that slow down other chains.
This fast finality is cryptographically guaranteed, meaning once a transaction is finalized, it cannot be reverted or reorganized. The combination of Move's strong type system and Movement's consensus layer ensures that finality is both fast and secure, providing developers with reliable state transitions they can immediately build upon.
## Why It Matters
Fast finality fundamentally transforms user experience and enables new categories of applications. Traditional blockchain delays force users to wait anxiously while transactions confirm, leading to abandoned carts in DeFi, poor gaming experiences, and frustrated users. With Movement's 1-3 second finality, applications can provide near-instant feedback comparable to Web2 experiences.
For developers, fast finality means reduced complexity in state management, fewer edge cases to handle, and the ability to build multi-step workflows that complete in seconds rather than minutes. It also significantly reduces the capital efficiency requirements for bridges, DEXs, and lending protocols by minimizing the time that assets need to remain locked.
## Developer Use Cases
### 1. High-Frequency Trading Platforms
Build DEX interfaces that support professional traders with near-instant order confirmation. Fast finality enables market makers to update quotes rapidly and arbitrageurs to close loops efficiently without waiting through multiple block confirmations.
### 2. Gaming and NFT Marketplaces
Create responsive gaming experiences where in-game purchases, item trades, and battle outcomes finalize in real-time. NFT marketplaces can process listings and sales with immediate ownership transfer, matching Web2 marketplace experiences.
### 3. Payment Systems
Implement point-of-sale systems and payment processors that confirm transactions fast enough for retail environments. Merchants receive guaranteed settlement in seconds, not minutes, making blockchain payments practical for everyday commerce.
### 4. Cross-Chain Bridges
Develop faster bridge protocols with reduced lockup periods. The quick finality means bridge operators can safely release assets on the destination chain much sooner, improving capital efficiency and user experience.
### 5. Social and Content Platforms
Build social applications where likes, posts, and tips finalize instantly, providing the responsive feedback loops users expect from modern social platforms without sacrificing decentralization.
### 6. Automated Trading Strategies
Implement complex DeFi strategies that execute multiple steps in rapid succession. Fast finality ensures each step completes before the next begins, reducing slippage and enabling more sophisticated algorithmic trading.
## Integration Tips
- **UX**: show a "confirming" state for ~1–3s; then display final status.
- **Indexers**: short polling backoff on tx/receipt queries.
- **Bridges**: wait for finality signals before unlocking assets cross-VM.
## Best Practices
### Polling and State Management
Instead of traditional 15-30 second polling intervals, configure your application to poll every 1-2 seconds. Use exponential backoff starting at 500ms for the most responsive UX. WebSocket connections can provide even better real-time updates when supported by your RPC provider.
### Transaction Confirmation UX
Design confirmation flows that match the actual finality time. Show a brief loading state (1-3 seconds) rather than lengthy "this may take several minutes" warnings. Consider using optimistic UI updates with automatic rollback on the rare occasion a transaction fails.
### Error Handling
While finality is fast, network issues can still cause delays. Implement timeout handling at 10 seconds (well beyond normal finality time) and provide clear error messages. Include retry mechanisms with proper nonce management.
### Multi-Step Workflows
Chain dependent transactions carefully. While you can submit the next transaction immediately after the previous finalizes, ensure your state queries have refreshed before building subsequent transactions that depend on updated state.
## Performance Considerations
### Network Latency Impact
Your physical distance from Movement RPC nodes affects the perceived finality time. Users in regions far from node clusters may experience an additional 100-300ms of network latency. Consider using geographically distributed RPC endpoints or CDN-based providers to minimize this impact.
### Gas and Priority
While finality is fast by default, during high network congestion, transactions with higher gas prices may finalize marginally faster. However, the difference is typically minimal compared to networks with longer block times. Monitor network congestion and adjust gas price recommendations accordingly.
### State Query Timing
After a transaction finalizes, allow 100-200ms for state to propagate through indexers and RPC nodes before querying dependent state. While the chain has finalized the transaction, some infrastructure may need a moment to update their cached views.
## Comparison with Other Approaches
Traditional Ethereum Layer 1 requires 12-15 minutes for safe finality (multiple block confirmations). Even Ethereum Layer 2s typically need 1-5 minutes for their fraud proof windows or optimistic periods. Solana offers fast confirmation but with occasional rollbacks during network congestion, providing speed without the same finality guarantees.
Movement's approach combines the best of both worlds: the speed of high-performance chains with the cryptographic finality guarantees of BFT consensus. This makes it particularly suitable for applications where both speed and certainty are critical, such as financial applications, gaming, and cross-chain protocols.
---
## MEV Protection
## Overview
Movement's shared sequencer and infrastructure aim to mitigate harmful MEV and improve fairness.
## How It Works
Maximal Extractable Value (MEV) occurs when validators or sequencers reorder, insert, or censor transactions to extract profit at the expense of users. Movement addresses this through its shared sequencer (M1) which implements MEV-aware ordering policies and transparent sequencing rules. Unlike traditional mempools where pending transactions are visible to all, Movement's architecture provides mechanisms for private transaction submission and fair ordering.
The M1 sequencer employs sophisticated ordering algorithms that prioritize fairness over pure profit maximization. Transactions can be submitted through private relays that shield them from public observation until they're included in a block. The sequencer also implements protection against sandwich attacks, frontrunning, and other common MEV exploitation vectors by using time-weighted ordering and batch auctions for certain transaction types.
Additionally, Movement's integration of the Move VM provides language-level protections. Move's resource-oriented programming model and explicit capability system make certain types of MEV attacks harder to execute compared to account-based models. The combination of secure language primitives and protocol-level MEV mitigation creates multiple layers of protection.
## Why It Matters
MEV has become one of the most significant issues in DeFi, extracting billions of dollars from users annually through frontrunning, sandwich attacks, and other predatory practices. For end users, this manifests as unexpectedly poor trade execution, failed transactions, and a general sense that the system is rigged against them. For developers, MEV creates a hostile environment where building fair applications requires constant vigilance and sophisticated countermeasures.
Movement's MEV protection framework fundamentally changes this dynamic. By providing protocol-level defenses, it allows developers to focus on building innovative applications rather than defending against attacks. Users receive fairer execution prices, fewer failed transactions, and greater confidence in the system. This protection also enables new categories of applications that would be impractical in high-MEV environments, such as sealed-bid auctions, fair token launches, and prediction markets.
The economic impact is substantial. Reduced MEV means more value stays with users and legitimate protocols rather than being extracted by sophisticated MEV bots. This improved efficiency can translate directly into better yields for liquidity providers, tighter spreads on DEXs, and more competitive pricing for DeFi services.
## Developer Use Cases
### 1. Decentralized Exchanges (DEXs)
Build DEX interfaces with built-in slippage protection that leverages Movement's MEV-resistant ordering. Users receive execution prices closer to quoted prices without suffering from last-block arbitrage or sandwich attacks that plague traditional AMMs.
### 2. NFT Minting and Drops
Launch fair NFT drops where mint order is determined by MEV-resistant sequencing rather than gas wars. Implement dutch auctions or batch minting that ensure collectors have equal access regardless of their technical sophistication or bot capabilities.
### 3. Lending and Liquidation Systems
Design lending protocols where liquidations happen fairly without allowing MEV bots to frontrun legitimate liquidators. The predictable ordering ensures that liquidation incentives work as designed without excessive profits being extracted through manipulation.
### 4. Token Launch Platforms
Create token launch mechanisms with sealed-bid participation where early buyers can't be frontrun. Implement fair price discovery where the opening price truly reflects market demand rather than being manipulated through strategic transaction ordering.
### 5. Prediction Markets
Build prediction markets where bet placement order doesn't leak information to other participants. The MEV protection ensures that large bets can't be frontrun and that market odds update fairly based on actual participation.
### 6. Cross-Chain Bridges
Develop bridge protocols that aren't vulnerable to MEV attacks on either side of the transfer. The protected ordering ensures users receive fair exchange rates and that bridge operators can't extract value through strategic transaction sequencing.
## Builder Guidance
- **Use private tx relays** where available to reduce frontrunning.
- **Minimize public mempool leakage** for sensitive operations.
- **Consider commit-reveal or sealed-bid patterns** for auctions.
## Best Practices
### Private Transaction Submission
For high-value or price-sensitive transactions, always submit through Movement's private relay infrastructure. This prevents your transaction from appearing in the public mempool where it could be observed and exploited. Configure your transaction submission libraries to prefer private routes by default for swaps above certain thresholds.
### Slippage and Timeout Settings
Even with MEV protection, set reasonable slippage tolerances. The protection layer reduces but doesn't eliminate market impact. Use dynamic slippage calculation based on liquidity depth and recent volatility. Implement shorter timeout windows since fast finality means transactions that don't execute quickly likely face unfavorable conditions.
### Batch Transactions Strategically
When executing multiple related transactions (like approvals followed by swaps), consider whether they should be batched into a single atomic transaction or submitted separately. Atomic batching prevents partial execution but may reveal your full strategy, while sequential submission maintains flexibility but requires careful ordering.
### Monitor and Respond
Implement monitoring to detect unusual execution patterns that might indicate MEV despite protocol protections. Track metrics like effective price vs. quoted price, transaction revert rates, and execution delays. Use these signals to adjust your integration strategy over time.
## Performance Considerations
### Private Relay Latency
Private transaction submission may add 100-500ms of latency compared to direct mempool submission. For most use cases, this tradeoff is worthwhile for the MEV protection, but latency-critical applications should measure and optimize their relay selection.
### Gas Costs of Protection
Some MEV protection mechanisms, like commit-reveal schemes, require multiple transactions and thus higher cumulative gas costs. Calculate the break-even point where the MEV protection value exceeds the additional gas costs, typically around $100-500 transaction values depending on network congestion.
### Ordering Guarantees
Movement's MEV protection provides strong but not absolute guarantees. Extremely sophisticated attacks or collusion scenarios may still extract some value. Design your applications with defense in depth, combining protocol-level protection with application-level safeguards.
## Comparison with Other Approaches
Traditional Ethereum relies entirely on application-layer MEV protection like Flashbots Protect, which requires users to opt-in and only protects during the submission phase. Ethereum's PBS (Proposer-Builder Separation) aims to democratize MEV but doesn't eliminate it. Solana's lack of mempool reduces some MEV but allows validators to reorder transactions within their leader slots.
Movement's approach provides protocol-level MEV protection by default, meaning all users benefit without needing to understand MEV or take special precautions. The shared sequencer's transparent rules and the Move VM's safety features create a more fundamentally fair environment than purely application-layer solutions or systems that rely on obscurity rather than cryptographic guarantees.
## Advanced Techniques
### Sealed-Bid Mechanisms
Implement cryptographic commitment schemes where participants submit hashed bids that can only be revealed after the bidding window closes. Movement's MEV protection ensures these reveals happen in a fair, un-frontrunnable sequence.
### Time-Weighted Average Price (TWAP) Orders
Execute large trades across multiple blocks using TWAP algorithms. Movement's consistent ordering and MEV protection ensure each sub-transaction executes fairly without being exploited by MEV bots anticipating future parts of your order.
### Programmable Privacy
Use Move's capability system to create assets and operations that have limited visibility to the sequencer. While the sequencer must order transactions, careful use of Move's type system can hide transaction details until execution.
---
## Shared Sequencer (M1)
## Overview
Movement uses a decentralized shared sequencer (M1) for ordering with MEV-awareness. This improves fairness and reduces censorship risk.
## How It Works
The M1 shared sequencer is a decentralized network of nodes that collectively determine transaction ordering for Movement blockchain. Unlike traditional blockchains where individual validators or centralized sequencers control ordering, M1 uses a distributed consensus protocol to provide censorship-resistant, fair transaction sequencing. The sequencer network operates independently from block production, separating the concerns of ordering (handled by M1) from execution (handled by Movement validators).
M1 employs a sophisticated consensus mechanism that achieves Byzantine Fault Tolerance while maintaining high throughput. The sequencer nodes stake collateral and participate in a reputation system that incentivizes honest behavior. Transactions submitted to the network are batched and ordered according to transparent rules that prioritize fairness over pure profit extraction. The resulting transaction sequence is then committed to Movement's data availability layer, creating an immutable record of the canonical ordering.
This architecture provides atomic composability across different execution environments and rollups that use M1. Multiple chains can share the same sequencer, enabling seamless cross-chain interactions without traditional bridge delays. The sequencer's MEV-aware policies are implemented at the protocol level, meaning developers and users benefit automatically without needing special integrations.
The M1 network also implements slashing conditions for malicious behavior. Sequencer nodes that attempt to reorder transactions unfairly, censor valid transactions, or engage in other misbehavior risk losing their staked collateral. This economic security model ensures long-term reliability and trustworthiness of the sequencing layer.
## Why It Matters
Sequencer centralization has become a critical problem in the blockchain ecosystem. Most Layer 2 rollups rely on single, centrally-operated sequencers that represent single points of failure and censorship. If the sequencer goes offline, the entire chain stops processing transactions. If the sequencer operator acts maliciously, they can extract MEV, censor transactions, or manipulate ordering for profit.
Movement's shared sequencer approach solves these problems through decentralization while adding unique benefits. The censorship resistance ensures that valid transactions will always be included, making the system more credibly neutral. The shared aspect enables cross-chain atomic transactions and composability that's impossible with isolated sequencers. For developers, this means building applications that can interact seamlessly across different execution environments without complex bridge protocols.
The economic implications are significant. Shared sequencer fees are distributed among decentralized operators rather than accruing to a single entity, creating a more sustainable and equitable economic model. The MEV-aware policies ensure that the value created by the network flows to users and builders rather than being extracted by sophisticated arbitrageurs.
## Developer Use Cases
### 1. Cross-Chain DeFi Applications
Build DeFi protocols that execute atomic transactions across multiple chains sharing the M1 sequencer. Implement flash loans that work across execution environments, arbitrage strategies that don't require bridges, or liquidity pools that span multiple chains with instant rebalancing.
### 2. Decentralized Order Books
Create orderbook-based exchanges that leverage the shared sequencer for fair price-time priority matching. The decentralized ordering ensures no single party can manipulate order execution or extract unfair value from the matching process.
### 3. Multi-Chain Gaming Platforms
Design gaming experiences where assets and state exist across multiple chains but interact atomically through the shared sequencer. Players can execute complex in-game actions that span different execution environments without waiting for cross-chain bridges.
### 4. Fair Launch Platforms
Implement token launch mechanisms that use the sequencer's transparent ordering to ensure fair participation. The decentralized nature prevents the launch platform operator from favorably ordering their own transactions or those of privileged users.
### 5. Cross-Chain Governance Systems
Build DAO governance systems where proposals and votes can originate from multiple chains but are sequenced fairly. The shared sequencer ensures vote ordering is tamper-proof and that governance actions execute atomically across all participating chains.
### 6. Censorship-Resistant Applications
Develop applications that require strong censorship resistance guarantees, such as prediction markets, whistleblowing platforms, or free speech applications. The decentralized sequencer ensures that valid transactions cannot be censored by any single party.
## Notes for Builders
- **Submit txs through standard RPC**; sequencing is handled by M1.
- **MEV-aware ordering policies** aim to protect users and builders.
## Best Practices
### Transaction Submission Strategy
Submit transactions through any M1-compatible RPC endpoint - the decentralized network ensures consistent treatment regardless of your entry point. For latency-sensitive applications, connect to geographically proximate RPC nodes. Consider implementing fallback to multiple RPC providers to maintain uptime even if one provider experiences issues.
### Handling Sequencer Guarantees
Design your applications to leverage M1's ordering guarantees. Once a transaction receives a sequencing commitment, you can build subsequent logic that depends on that transaction's execution. This enables more complex multi-step workflows that would be risky with less reliable sequencing.
### Cross-Chain Interactions
When building cross-chain features, take advantage of M1's atomic composability. Structure your transactions to either fully succeed or fully revert across all participating chains. This eliminates the complex error handling required with traditional bridges where operations can succeed on one chain but fail on another.
### Monitoring Sequencer Health
Implement monitoring of M1 network health metrics. Track sequencer uptime, finality times, and any slashing events. While the decentralized nature provides resilience, monitoring helps you understand network conditions and adjust application behavior during unusual circumstances.
## Performance Considerations
### Sequencing Latency
The shared sequencer adds minimal latency to transaction processing - typically 100-300ms for sequencing commitment before execution begins. This is substantially faster than cross-chain bridges (minutes to hours) while providing stronger guarantees. For most applications, this tradeoff is extremely favorable.
### Network Congestion Handling
During high congestion, the sequencer prioritizes transactions using transparent rules based on fees and timing. Unlike centralized sequencers that might have opaque priority mechanisms, M1's rules are public and deterministic. Implement dynamic fee estimation that accounts for current network conditions.
### Cross-Chain Transaction Costs
Atomic cross-chain transactions incur sequencing fees from M1 plus execution fees on each participating chain. While more expensive than single-chain transactions, they're substantially cheaper and faster than achieving similar atomicity through traditional bridge protocols with their lock-and-mint mechanisms.
### Finality Guarantees
M1 provides probabilistic finality that strengthens over time as more sequencer nodes commit to the ordering. For critical operations, wait for sufficient sequencer confirmations (typically 2-3 seconds) before considering the order immutable. Less critical operations can proceed with single-node commitments.
## Comparison with Other Approaches
Centralized sequencers (used by most L2s like Optimism and Arbitrum) offer simplicity and low latency but suffer from single points of failure and censorship risks. Fully decentralized L1 consensus (like Ethereum) provides stronger decentralization but at the cost of throughput and latency. Solana's leader rotation provides some decentralization but with periods of centralized control during each validator's leader slot.
Movement's M1 shared sequencer strikes a balance: it's decentralized enough to resist censorship and single points of failure, yet efficient enough to provide sub-second sequencing commitments. The shared aspect is unique - while other chains have decentralized sequencers, M1's ability to sequence transactions across multiple execution environments enables entirely new categories of cross-chain applications.
Compared to cross-chain bridges, M1 provides faster, cheaper, and more secure cross-chain interaction. Traditional bridges require locking assets on the source chain, transmitting messages, and minting wrapped assets on the destination chain - a process that takes minutes to hours. M1 enables atomic execution across chains in seconds.
## Advanced Integration Patterns
### Atomic Cross-Chain Swaps
Implement trustless cross-chain swaps that leverage M1's atomic sequencing. Users can swap assets on different chains without requiring wrapped tokens, bridge operators, or long waiting periods. The sequencer ensures both legs of the swap execute together or not at all.
### Shared Liquidity Pools
Create liquidity pools that exist across multiple chains but operate as a single logical pool. The shared sequencer enables atomically updating pool state across all chains, preventing arbitrage opportunities that typically arise from fragmented liquidity.
### Multi-Chain Smart Contracts
Design smart contracts that call functions on contracts deployed to different chains. The shared sequencer ensures these cross-chain calls execute atomically, enabling complex application logic that spans multiple execution environments.
### Sequencer-Aware MEV Protection
Build MEV protection directly into your application logic by leveraging M1's transparent ordering rules. Submit bundles of transactions that should execute together, with the sequencer ensuring they maintain their relative ordering without interference from third-party MEV bots.
## Security Considerations
The shared sequencer's security derives from its Byzantine Fault Tolerant consensus and economic stake. As long as more than two-thirds of sequencer nodes by stake remain honest, the network provides correct ordering. The slashing mechanism ensures that attempting to manipulate ordering results in substantial financial loss, making attacks economically irrational for rational actors.
Applications should still implement defense-in-depth security. While M1 provides strong ordering guarantees, smart contract logic should validate all inputs and maintain invariants regardless of transaction ordering. The sequencer protects against ordering manipulation but doesn't prevent bugs in contract logic or attacks that don't rely on transaction ordering.
---
## Movement — Move REST API Guide
## Why Build on Movement
- Move-first execution environment with resource-oriented safety
- BlockSTM parallel execution for high throughput
- 1–3 second fast finality UX
- Compatibility with existing Aptos tooling and REST schemas
## Quick Start
### Endpoints
### SDK Installation
```bash
npm i @aptos-labs/ts-sdk
```
```typescript
const config = new AptosConfig({
network: Network.CUSTOM,
fullnode: 'https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1'
});
const aptos = new Aptos(config);
const ledger = await aptos.getLedgerInfo();
console.log('Move chain ID:', ledger.chain_id);
```
```bash
# Example usage placeholder — configure your CLI with the endpoint above
# API Base: https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1
```
## Network Information
API Base
/v1
Aptos-compatible REST
Native Token
MOVE
Finality
~1–3s
Fast confirmations
- Movement API Base: `https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1`
## Move REST API Reference
Movement exposes Aptos-compatible REST APIs at `/v1` for MoveVM operations.
- [Accounts](/movement/accounts)
- [Account Resources](/movement/account_resources)
- [Account Modules](/movement/account_modules)
- [Blocks](/movement/blocks)
- [Transactions](/movement/transactions)
- [Transaction Encode](/movement/transaction_encode)
- [Transaction Simulate](/movement/transaction_simulate)
- [Events](/movement/events)
- [Tables](/movement/tables)
- [Ledger](/movement/ledger)
- [Health](/movement/health)
## Movement-Specific Features
- [BlockSTM Parallel Execution](/movement/blockstm)
- [Fast Finality Settlement](/movement/fast_finality)
- [Shared Sequencer (M1)](/movement/shared_sequencer)
- [MEV Protection](/movement/mev_protection)
## Common Integration Patterns
- DEX or payments: leverage Move resources for precise asset accounting
- Data services: poll `/v1/blocks` and `/v1/transactions` for real-time indexing
- Custody/wallets: query account resources and event streams to reflect balances
## Performance Best Practices
- Design for BlockSTM: avoid write conflicts to maximize parallelism
- Gas optimization: use Move simulations to estimate gas under load
- Finality-aware UX: consider 1–3s finality in confirmations and polling intervals
## Migration Guides
- From Aptos: reuse Move modules with minimal changes; update REST base to Movement `/v1`
- From Sui: port object/resource models to Move on Movement; adjust package layout
## Troubleshooting
- Ensure correct address format (hex with `0x` prefix) and fully qualified module/function IDs
- Encode payloads with BCS and confirm signatures before submission
- Check `/v1/-/healthy` for node health and `/v1/ledger` for latest version
## Resources & Tools
- Move SDKs: Aptos TypeScript & Python SDKs
- Explorer: https://explorer.movementnetwork.xyz/
- Get your API key: https://dashboard.dwellir.com/register
---
## Account Modules — Move REST API
## Overview
Lists Move modules published under a specific account.
## Endpoint
`GET /v1/accounts/{address}/modules`
## Movement-Specific Notes
- Module ABI and bytecode can be retrieved via separate endpoints.
## Request
### Parameters
| Name | Type | Location | Required | Description |
|------|------|----------|----------|-------------|
| address | string | path | Yes | Publisher address |
## Response
### Success Response (200)
```json
[
{
"bytecode": "0x...",
"abi": { "name": "MyModule", "exposed_functions": [] }
}
]
```
## Code Examples
```bash
curl -X GET https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/modules \
-H "Accept: application/json"
```
```python
from aptos_sdk.client import RestClient
client = RestClient('https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1')
modules = client.account_modules('0x1')
print(modules)
```
```typescript
const cfg = new AptosConfig({ network: Network.CUSTOM, fullnode: 'https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1' });
const aptos = new Aptos(cfg);
const modules = await aptos.getAccountModules({ accountAddress: '0x1' });
console.log(modules);
```
---
## Account Resources — Move REST API
## Overview
Lists all Move resources under an account. Useful for token balances and on-chain state.
## Endpoint
`GET /v1/accounts/{address}/resources`
## Movement-Specific Notes
- Resource types use canonical `0x...::module::Type` identifiers.
## Request
### Parameters
| Name | Type | Location | Required | Description |
|------|------|----------|----------|-------------|
| address | string | path | Yes | Hex account address |
## Response
### Success Response (200)
```json
[
{
"type": "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>",
"data": { "coin": { "value": "123" } }
}
]
```
## Code Examples
```bash
curl -X GET https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/resources \
-H "Accept: application/json"
```
```python
from aptos_sdk.client import RestClient
client = RestClient('https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1')
resources = client.account_resources('0x1')
print(resources)
```
```typescript
const cfg = new AptosConfig({ network: Network.CUSTOM, fullnode: 'https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1' });
const aptos = new Aptos(cfg);
const resources = await aptos.getAccountResources({ accountAddress: '0x1' });
console.log(resources);
```
---
## Accounts — Move REST API
## Overview
Query Move accounts, including basic info, resources, and modules. Movement uses Aptos-compatible endpoints at `/v1`.
## Endpoint
`GET /v1/accounts/{address}`
## Movement-Specific Notes
- Use `0x`-prefixed addresses.
- Move balances are tracked as on-chain resources; query the relevant coin resource for balances.
## Request
### Parameters
| Name | Type | Location | Required | Description |
|------|------|----------|----------|-------------|
| address | string | path | Yes | Hex account address |
## Response
### Success Response (200)
```json
{
"sequence_number": "string",
"authentication_key": "string",
"address": "0x..."
}
```
## Code Examples
```bash
curl -X GET https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1 \
-H "Accept: application/json"
```
```python
from aptos_sdk.client import RestClient
client = RestClient('https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1')
info = client.account('0x1')
print(info)
```
```typescript
const config = new AptosConfig({ network: Network.CUSTOM, fullnode: 'https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1' });
const aptos = new Aptos(config);
const account = await aptos.getAccountInfo({ accountAddress: '0x1' });
console.log(account);
```
---
## Blocks — Query Blocks (Move REST)
# Blocks — Query Blocks
## Overview
Fetch block data by height or by version.
## Endpoints
`GET /v1/blocks/by_height/{height}`
`GET /v1/blocks/by_version/{version}`
## Request
### Parameters
| Name | Type | Location | Required | Description |
|------|------|----------|----------|-------------|
| height | string | path | Yes | Block height |
| version | string | path | Yes | Ledger version |
## Response
### Success Response (200)
```json
{ "block_height": "0", "block_hash": "0x...", "first_version": "0" }
```
## Code Examples
```bash
curl -X GET https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/blocks/by_height/0 -H "Accept: application/json"
```
```python
from aptos_sdk.client import RestClient
client = RestClient('https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1')
block = client.block_by_height('0')
print(block)
```
```typescript
const cfg = new AptosConfig({ network: Network.CUSTOM, fullnode: 'https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1' });
const aptos = new Aptos(cfg);
const block = await aptos.getBlockByHeight({ blockHeight: '0' });
console.log(block);
```
---
## Events — Move REST API
## Overview
Query events by handle and creation number, or via event keys.
## Endpoint
`GET /v1/accounts/{address}/events/{creation_number}`
## Movement-Specific Notes
- Event handles are stored in account resources.
## Request
### Parameters
| Name | Type | Location | Required | Description |
|------|------|----------|----------|-------------|
| address | string | path | Yes | Account address owning the handle |
| creation_number | string | path | Yes | Creation number of the event counter |
## Response
### Success Response (200)
```json
[{ "sequence_number": "0", "type": "0x...::module::Event", "data": {} }]
```
## Code Examples
```bash
curl -X GET https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/events/0 \
-H "Accept: application/json"
```
```typescript
const res = await fetch('https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/events/0');
console.log(await res.json());
```
---
## Health — Service Health (Move REST)
# Health — Service Health
## Overview
Simple endpoint to check service availability.
## Endpoint
`GET /v1/-/health`
## Response
### Success Response (200)
Healthy service returns HTTP 200 with empty body.
## Code Examples
```bash
curl -I https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/-/health
```
```python
resp = requests.get('https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/-/health')
print(resp.status_code)
```
```typescript
const res = await fetch('https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/-/health');
console.log(res.status);
```
---
## Ledger — Chain Info (Move REST)
# Ledger — Chain Info
## Overview
Returns basic ledger information for the Move chain.
## Endpoint
`GET /v1` and `GET /v1/ledger/info`
## Movement-Specific Notes
- Use this to fetch `chain_id`, ledger version, and timestamps.
## Request
### Parameters
| Name | Type | Location | Required | Description |
|------|------|----------|----------|-------------|
| (none) | — | — | — | — |
## Response
### Success Response (200)
```json
{
"chain_id": 0,
"ledger_version": "0",
"ledger_timestamp": "0"
}
```
## Code Examples
```bash
curl -X GET https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1 -H "Accept: application/json"
```
```python
from aptos_sdk.client import RestClient
client = RestClient('https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1')
info = client.ledger()
print(info)
```
```typescript
const cfg = new AptosConfig({ network: Network.CUSTOM, fullnode: 'https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1' });
const aptos = new Aptos(cfg);
const info = await aptos.getLedgerInfo();
console.log(info);
```
---
## Modules — ABI (Move REST)
# Modules — ABI
## Overview
Retrieve ABI for Move modules, including exposed functions and structs.
## Endpoint
`GET /v1/accounts/{address}/module/{module_name}`
## Movement-Specific Notes
- ABI helps construct view and entry function payloads.
## Request
### Parameters
| Name | Type | Location | Required | Description |
|------|------|----------|----------|-------------|
| address | string | path | Yes | Publisher address |
| module_name | string | path | Yes | Module name |
## Response
### Success Response (200)
```json
{ "abi": { "name": "MyModule", "exposed_functions": [] } }
```
## Code Examples
```bash
curl -X GET https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/module/MyModule \
-H "Accept: application/json"
```
```typescript
const res = await fetch('https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/module/MyModule');
const json = await res.json();
console.log(json);
```
---
## Modules — View Functions (Move REST)
# Modules — View Functions
## Overview
Execute read-only Move view functions without submitting a transaction.
## Endpoint
`POST /v1/view`
## Movement-Specific Notes
- Provide the fully-qualified function `0x...::module::fn`.
## Request
### Body Schema
```json
{
"function": "0x1::chain_id::get",
"type_arguments": [],
"arguments": []
}
```
## Response
### Success Response (200)
```json
["0x..."]
```
## Code Examples
```bash
curl -X POST https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/view \
-H "Content-Type: application/json" \
-d '{"function":"0x1::chain_id::get","type_arguments":[],"arguments":[]}'
```
```python
# Use aptos_sdk view helpers (or direct REST call)
```
```typescript
const cfg = new AptosConfig({ network: Network.CUSTOM, fullnode: 'https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1' });
const aptos = new Aptos(cfg);
const res = await aptos.view({ function: '0x1::chain_id::get', typeArguments: [], functionArguments: [] });
console.log(res);
```
---
## Tables — Move REST API
## Overview
Query on-chain Move tables using table handle and key payload.
## Endpoint
`POST /v1/tables/{handle}/item`
## Movement-Specific Notes
- Keys/values are BCS-encoded; provide `key_type` and `value_type` with JSON-encoded key.
## Request
### Body Schema
```json
{
"key_type": "0x1::string::String",
"value_type": "0x1::string::String",
"key": "example"
}
```
## Response
### Success Response (200)
```json
"value"
```
## Code Examples
```bash
curl -X POST https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/tables/0x/item \
-H "Content-Type: application/json" \
-d '{"key_type":"0x1::string::String","value_type":"0x1::string::String","key":"example"}'
```
```typescript
const res = await fetch('https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/tables/0x/item', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key_type: '0x1::string::String', value_type: '0x1::string::String', key: 'example' })
});
console.log(await res.json());
```
---
## Transaction Encode — Move REST API
## Overview
Encodes transactions in BCS format for signing/submission.
## Endpoint
`POST /v1/transactions/encode_submission`
## Movement-Specific Notes
- Use correct function/module/type arguments for entry functions.
## Request
### Body Schema
```json
{ "sender": "0x...", "payload": { "type": "entry_function_payload", "function": "..." } }
```
## Response
### Success Response (200)
```json
"0x..."
```
## Code Examples
```bash
curl -X POST https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/transactions/encode_submission \
-H "Content-Type: application/json" \
-d '{"sender":"0x...","payload":{}}'
```
```python
# Build payload using aptos_sdk types and encode
```
```typescript
// SDK provides encode helpers for building payloads
```
---
## Transaction Simulate — Move REST API
## Overview
Simulate a signed or unsigned transaction to preview effects and gas.
## Endpoint
`POST /v1/transactions/simulate`
## Movement-Specific Notes
- Use realistic parameters to improve accuracy.
## Request
### Body Schema
```json
[{ "sender": "0x...", "payload": { "type": "entry_function_payload", "function": "..." } }]
```
## Response
### Success Response (200)
```json
[{ "gas_used": "1234", "success": true, "vm_status": "Executed successfully" }]
```
## Code Examples
```bash
curl -X POST https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/transactions/simulate \
-H "Content-Type: application/json" \
-d '[{"sender":"0x...","payload":{}}]'
```
```python
# Use aptos_sdk simulate helpers (where available)
```
```typescript
const cfg = new AptosConfig({ network: Network.CUSTOM, fullnode: 'https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1' });
const aptos = new Aptos(cfg);
// Use aptos.simulateTransaction helpers
```
---
## Transactions — Move REST API
## Overview
Submit signed Move transactions and query by hash or version.
## Endpoint
`POST /v1/transactions`
## Movement-Specific Notes
- Ensure payloads are properly BCS-encoded.
- Fast finality: transactions confirm in ~1–3 seconds typically.
## Request
### Body Schema
```json
{
"sender": "0x...",
"sequence_number": "string",
"max_gas_amount": "string",
"gas_unit_price": "string",
"expiration_timestamp_secs": "string",
"payload": { "type": "entry_function_payload", "function": "...", "type_arguments": [], "arguments": [] },
"signature": { "type": "ed25519_signature", "public_key": "0x...", "signature": "0x..." }
}
```
## Response
### Success Response (202)
```json
{ "hash": "0x..." }
```
## Code Examples
```bash
curl -X POST https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1/transactions \
-H "Content-Type: application/json" \
-d '{"sender":"0x...","payload":{}}'
```
```python
from aptos_sdk.client import RestClient
client = RestClient('https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1')
# Build/sign/submit using aptos-sdk helpers
```
```typescript
const cfg = new AptosConfig({ network: Network.CUSTOM, fullnode: 'https://api-movement-mainnet.n.dwellir.com/YOUR_API_KEY/v1' });
const aptos = new Aptos(cfg);
// Build + sign + submit transaction via SDK helpers
```
---
## author_pendingExtrinsics - Mythos RPC Method
# author_pendingExtrinsics
Returns all pending extrinsics in the transaction pool on Mythos.
## Use Cases
- **Mempool monitoring** - Track pending transactions
- **Transaction status** - Check if your transaction is pending for AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# author_rotateKeys
Generate a new set of session keys on Mythos. 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 AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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-mythos-archive.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 - Mythos 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 AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# author_submitExtrinsic
Submit a signed extrinsic to Mythos for inclusion in a block.
## Use Cases
- **Transaction submission** - Broadcast signed transactions
- **dApp interactions** - Execute on-chain operations for AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# beefy_getFinalizedHead
Returns the block hash of the latest BEEFY-finalized block on Mythos. 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 AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# chain_getBlock
Retrieves complete block information from Mythos, including the block header, extrinsics, and justifications.
> **Why Mythos?** Build on the gaming blockchain powering FIFA Rivals and NFL Rivals with World ID verification with World ID proof-of-humanity, Polkadot security, Snowbridge cross-chain bridge, and 1M+ downloads per title.
## 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 AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# chain_getBlockHash
Returns the block hash for a given block number on Mythos.
## Use Cases
- **Historical queries** - Convert block numbers to hashes
- **Block navigation** - Navigate blockchain history for AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# chain_getFinalizedHead
Returns the hash of the last finalized block on Mythos.
## Use Cases
- **Confirmed state** - Query state that cannot be reverted
- **Transaction confirmation** - Verify transaction finality for AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# chain_getHeader
Returns the block header for a given hash on Mythos.
## Use Cases
- **Lightweight queries** - Get header without full block data
- **Chain synchronization** - Track block production for AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# chain_subscribeFinalizedHeads
Subscribe to receive notifications when blocks are finalized on Mythos. 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 AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# chain_subscribeNewHeads
Subscribe to receive notifications when new block headers are produced on Mythos. This WebSocket subscription provides real-time updates for each new block.
## Use Cases
- **Block monitoring** - Track new blocks in real-time for AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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
---
## Cross-Game Assets on Mythos
# Cross-Game Asset Strategy
Mythos positions NFTs as shared player identity across flagship titles, from NFL Rivals to Nitro Nation World Tour. GAM3S’ Mythical Forest event established the blueprint: complete quests in one title, receive cosmetics that unlock everywhere else.
## Design Principles
1. **Quest-Based Unlocks** – Drive engagement by linking challenges in one game to unlockables in another, as demonstrated by Mythical Forest signature rewards.
2. **Metadata Harmonization** – Use `pallet_nfts` attribute namespaces to map shared stats (rarity, franchise, power score) across titles.
3. **Marketplace Liquidity** – Encourage secondary trading on Mythical Marketplace where multi-game items retain value regardless of their origin title.
## Migration Checklist
- **Legacy Collections:** Follow Mythical’s migration guidance to reissue Blankos Block Party assets on Mythos before new season launches.
- **Player Inventories:** Sync Beamable SDK across Unity and Unreal builds so wallets reflect newly bridged items.
- **Governance Alignment:** Coordinate DAO proposals for cross-game reward pools and MYTH incentives to maintain balance between franchises.
## Future Outlook
- **XCM Expansion:** Mythos is preparing Moonbeam and Hydration channels, enabling DeFi use cases for cosmetics and passes. Track XCM status to plan staking or collateral utilities.
- **Esports & Live Events:** With 400k+ monthly players, shared assets can power league-wide leaderboards and sponsor activations at scale.
---
## Mythos Gaming NFTs
# Gaming NFTs on Mythos
Mythos extends Substrate’s `pallet_nfts` to enable zero-deposit minting, serial issuance, and cross-game metadata locks tailored for Mythical titles.
## Core Capabilities
- **Free-to-Mint Collections:** Collection and item deposits are set to zero, letting studios airdrop assets without reserve capital.
- **Serial & Pre-Signed Minting:** `mint_pre_signed` enables controlled releases (e.g., playoff passes) while `MintSettings` enforce windows and ownership prerequisites.
- **Attribute Governance:** Attribute namespaces (`CollectionOwner`, `ItemOwner`, `Pallet`, `Account`) let designers lock rarity traits while still enabling player-driven upgrades.
## Example: Minting a Nitro Nation Crate
A production mint executed in block `2,611,955` shows Mythos’ NFT pipeline in action:
```json
{
"extrinsic_hash": "0x6f26cdb2c3398f2cabaa0bf51d3c8ec3f3cbe75ffb8b9b8853718055517b2497",
"call": "nfts.mint",
"collection": "0xfa",
"item": "0x02",
"owner": "0x6f88…b0d5"
}
```
View full details on Subscan to inspect fees, event logs, and signer reputation.
## Mint Workflow
1. **Create Collection** – Call `pallet_nfts.create` with mint settings (start/end block, whitelist) and any metadata URI.
2. **Configure Attributes** – Use `set_attribute` or `force_set_attribute` for cosmetics, team names, or rarity. Lock values for seasonal archives.
3. **Distribute Items** – Choose between `mint`, `force_mint`, or `mint_pre_signed` depending on automation, KYC, or sponsor involvement.
4. **Lifecycle Management** – Approve transfers, set prices, or initiate swaps via `pallet_marketplace` and `pallet_dmarket`.
## Tips for Game Studios
- Batch NFT drops with `pallet_multibatching` to keep UX smooth even during primetime events.
- Combine Beamable inventory sync with Mythos NFTs so Unity/Unreal builds reflect ownership instantly.
- Align DAO governance proposals with upcoming drops to secure MYTH staking incentives.
---
## Marketplace Integration on Mythos
# Marketplace Integration
Mythos pairs `pallet_marketplace`, `pallet_escrow`, and `pallet_dmarket` to recreate Mythical Marketplace functionality directly on-chain. Listings, bids, and escrowed settlements are handled without centralized custody.
## Architectural Overview
- **Listings & Orders:** `pallet_marketplace` lets studios configure timed listings, whitelisted buyers, and royalties via runtime constants.
- **Escrow Management:** `pallet_escrow` holds MYTH payments until both sides confirm, protecting buyers during cross-game swaps.
- **Signed Trades:** `pallet_dmarket` exposes helper APIs to pre-sign off-chain bids/asks that settle on-chain for minimal latency.
## Integrating with Backend Services
1. **Index Events:** Subscribe to `marketplace.ItemBought` and `pallet_escrow` events via `author_subscribeExtrinsic` to update storefronts.
2. **Price Discovery:** Use DotLake analytics (3.3M+ Mythos transactions) to monitor floor prices and adjust in-game economy levers.
3. **KYC or Limited Access:** Combine DAO governance proposals with `set_price` whitelists for age-gated drops or region-specific campaigns.
## Sample Listing Flow
```mermaid
graph TD;
A[Player signs ask via pallet_dmarket helper] --> B[Submit author_submitExtrinsic call];
B --> C[pallet_marketplace::set_price];
C --> D{Buyer executes buy_item}
D -->|Escrow payment| E[pallet_escrow::make_deposit];
D -->|NFT transfer| F[pallet_nfts::transfer];
E --> G[Funds released after Block Finalization];
```
Recent sale proof: extrinsic `0x6f26cdb2c3398f2cabaa0bf51d3c8ec3f3cbe75ffb8b9b8853718055517b2497` minted and listed a Nitro Nation crate, demonstrating end-to-end settlement on Mythos.
## UX Best Practices
- Batch listing updates with `pallet_multibatching` when rotating store catalogs.
- Surface escrow status inside game HUDs to educate players during first purchases.
- Encourage MYTH staking incentives through DAO proposals aligned with marketplace campaigns.
---
## Player & Creator Economics on Mythos
# Player & Creator Economics
Mythos aligns player ownership with the MYTH governance token, DAO incentives, and runtime fee mechanics optimized for high-frequency gameplay.
## MYTH Token Utility
- **Governance:** Vote on ecosystem onboarding, marketplace fees, and cross-game reward pools through the Mythos DAO.
- **Staking & Incentives:** DAO proposals channel MYTH rewards to featured games, ensuring creators and competitive players share upside from new drops.
- **Marketplace Medium:** MYTH powers marketplace escrows, DMarket orders, and bulk crafting costs.
## Fee Model
- Weight-based fees rely on `WeightToFee`, scaling with the higher of execution weight or proof size, then multiplied by `FEE_MULTIPLIER = 7` for predictable cost ceilings.
- Deposits for NFT metadata and attributes are set to zero, encouraging frequent cosmetic updates without penalizing studios.
## Adoption Metrics
- Since launch, DotLake recorded 3.3M Mythos transactions and 3.6M legacy accounts bridged into Polkadot, providing immediate liquidity for creators.
- 400k+ monthly active players give live-service titles enough throughput to experiment with leaderboards, loot boxes, and dynamic pricing.
## Balancing Tips
1. **Seasonal Treasury Allocations:** Use DAO proposals to top up prize pools ahead of marquee events (e.g., NFL kickoff).
2. **Dynamic Pricing:** Monitor DotLake’s fee analytics to adjust MYTH sinks or faucets week over week.
3. **Onboarding Subsidies:** Pair free-mint NFTs with sponsor-funded MYTH airdrops using `pallet_escrow` and `pallet_multibatching` for mass distribution.
---
## gaming_getPlayerAssets (Mythos inventory patt...
# Enumerate Mythos player assets
Mythos inventories live in `pallet_nfts::Account` and `pallet_nfts::Item`. Although legacy guides referenced a `gaming_getPlayerAssets` RPC, the recommended approach is to page through the on-chain storage keys, then hydrate each item. The examples below use Dwellir’s managed endpoint `https://api-mythos-archive.n.dwellir.com/YOUR_API_KEY`.
## Step 1 – List owned collections
Use `state_getKeysPaged` with the prefix returned by `api.query.nfts.account.keyPrefix()`. The prefix encodes the player address, letting you iterate collections in batches.
```bash
ACCOUNT=0x6f5e2dee7182143c809c6606f5c50ffb0cc7f4dd
PREFIX=$(npx ts-node -e "const { ApiPromise, WsProvider } = require('@polkadot/api');(async () => { const api = await ApiPromise.create({ provider: new WsProvider('wss://api-mythos-archive.n.dwellir.com/YOUR_API_KEY') }); console.log(api.query.nfts.account.keyPrefix('$ACCOUNT').toHex()); process.exit(0); })();")
curl https://api-mythos-archive.n.dwellir.com/YOUR_API_KEY -H "Content-Type: application/json" -d '{
"jsonrpc": "2.0",
"method": "state_getKeysPaged",
"params": ["'"${PREFIX}"'", 64, null],
"id": 21
}'
```
**Sample response (shortened)**
```json
{
"result": [
"0xeab5cb3142f74ec1…0000000000000000000000000000000000000000000000000000000000000afb",
"0xeab5cb3142f74ec1…0000000000000000000000000000000000000000000000000000000000000b11"
]
}
```
Each key encodes `(accountId, collectionId)`. For the account above, the first entry corresponds to **collection 2783**.
## Step 2 – Hydrate individual items
With the collection ID in hand, iterate item IDs using `api.query.nfts.item.keys(collectionId)` or another `state_getKeysPaged` call. Then read each item via `api.query.nfts.item(collectionId, itemId)`.
```typescript
const ACCOUNT = '0x6f5e2dee7182143c809c6606f5c50ffb0cc7f4dd';
const provider = new WsProvider('wss://api-mythos-archive.n.dwellir.com/YOUR_API_KEY');
const api = await ApiPromise.create({ provider });
for (const [collectionId, itemList] of await api.query.nfts.account.entries(ACCOUNT)) {
const collection = collectionId.args[1].toNumber();
for (const itemKey of await api.query.nfts.item.keys(collection)) {
const itemId = itemKey.args[1].toNumber();
const details = await api.query.nfts.item(collection, itemId);
if (details.isSome) {
console.log({ collection, itemId, owner: details.unwrap().owner.toHex() });
}
}
}
```
Sample console output (3 Oct 2025):
```
{ collection: 2783, itemId: 21, owner: '0x6f5e2dee7182143c809c6606f5c50ffb0cc7f4dd' }
{ collection: 2783, itemId: 22, owner: '0x6f5e2dee7182143c809c6606f5c50ffb0cc7f4dd' }
```
## Step 3 – Attach marketplace listings
For each `(collectionId, itemId)` pair, read `Marketplace::Asks(collectionId, itemId)` to attach live pricing data (see [nft_getAsset](/mythos/nft_getAsset)). Items not listed will return `None`.
## Pagination tips
- Tune the `state_getKeysPaged` `pageSize` (128–256) to balance throughput and latency.
- Persist cursors in your backend so clients can resume from the last key without rescanning.
- When serving real-time UIs, subscribe to `state_subscribeStorage` on `Nfts::Item` to push updates as ownership changes.
---
## grandpa_roundState - Mythos RPC Method
# grandpa_roundState
Returns the state of the current GRANDPA finality round on Mythos. GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) is the finality gadget used by Substrate chains.
## Use Cases
- **Finality monitoring** - Track consensus progress for AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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-mythos-archive.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)
---
## Mythos - Web3 Gaming Parachain Documentation
# Mythos - Build Cross-Game Play-and-Own Experiences
## Why Build on Mythos?
Mythos is Mythical Games’ dedicated Polkadot parachain for Web3 gaming, bringing over 3.6 million existing player accounts and titles like NFL Rivals, Nitro Nation World Tour, and Blankos Block Party into a shared economy that now settles on Polkadot relay chain security.
### 🎮 **Play-and-Own at Scale**
- 400,000+ monthly active players already engage with Mythical titles, ensuring organic demand for on-chain assets.
- Mythos finalized its migration to Polkadot in September 2024, inheriting relay chain security while unlocking greater throughput for in-game economies.
- Mythical Marketplace processed millions of transactions pre-launch; Polkadot integration adds XCM channels for future loot drops and championships.
### 🧬 **Cross-Game NFT Interoperability**
- GAM3S’ Mythical Forest became the flagship cross-game quest hub, distributing interoperable cosmetics across the Mythos ecosystem.
- Mythical outlined mandatory migration paths for Blankos Block Party collectibles, guaranteeing existing player items persist on Mythos Mainnet.
### 🗳️ **DAO-Governed Ecosystem**
- The Mythos DAO stewards decision-making on game onboarding, marketplace fees, and ecosystem grants, backed by the MYTH governance token supply.
- Polkadot’s OpenGov approved Mythos’ parachain slot, aligning DAO proposals with parachain treasury workflows.
## Quick Start with Mythos
Connect to Mythos Mainnet over Dwellir’s low-latency infrastructure:
> 💡 **Tip:** Sign in to the Dwellir dashboard and **Get your API key** before adding endpoints to production clients.
Use HTTPS for servers and `wss://api-mythos-archive.n.dwellir.com/YOUR_API_KEY` for latency-sensitive WebSocket subscriptions.
### Installation & Setup
```javascript
async function connect() {
const provider = new WsProvider('wss://api-mythos-archive.n.dwellir.com/YOUR_API_KEY');
const api = await ApiPromise.create({ provider });
// Fetch the latest finalized block number
const finalized = await api.rpc.chain.getFinalizedHead();
const header = await api.rpc.chain.getHeader(finalized);
console.log('Finalized block:', header.number.toString());
return api;
}
connect().catch(console.error);
```
```rust
use subxt::{ OnlineClient, PolkadotConfig };
#[tokio::main]
async fn main() -> subxt::Result<()> {
let api = OnlineClient::::from_url(
"https://api-mythos-archive.n.dwellir.com/YOUR_API_KEY"
).await?;
// Query total issuance for MYTH (Balances pallet)
let total: u128 = api
.storage()
.at(None)
.await?
.fetch(&subxt::dynamic::storage("Balances", "TotalIssuance"))
.await?
.unwrapping();
println!("Total MYTH issuance: {total}");
Ok(())
}
```
```csharp
using Beamable.Server.Clients;
using System.Threading.Tasks;
public class MythosLogin : MonoBehaviour
{
async Task Start()
{
var beamContext = await BeamContext.Default;
await beamContext.Player.LoginSilent();
// Fetch Mythos inventory via Beamable's Mythical integration
var items = await beamContext.Inventory.GetItems();
Debug.Log($"Items synced from Mythos: {items.Count}");
}
}
```
> Beamable’s SDK now supports Mythos chain connectivity across Unity projects, streamlining wallet onboarding and in-game asset sync.
## Network Information
Parachain ID
3369
Assigned via Mythos genesis preset
Average Block Time
6 seconds
Aura slots tuned for gameplay
Consensus
Aura + GRANDPA
Relay chain finalized
Native Token
MYTH
Governance & marketplace utility
Mythos inherits Substrate defaults while enabling 6-second blocks, 10 MB PoV limits, and economics optimized around the MYTH token with weight-based transaction fees.
## Available JSON-RPC Methods
Mythos inherits the standard Substrate JSON-RPC namespaces while layering on gaming-focused runtime calls for NFTs, marketplace activity, and player inventory sync. Use the tables below to jump directly to the method reference pages that matter for your integration.
### Core Substrate namespaces
| Group | Purpose | Key Methods |
|-------|---------|-------------|
| `chain_*` | Block data, headers, and finality tracking | [`chain_getBlock`](/mythos/chain_getBlock) |
| `state_*` | Inspect storage and runtime metadata for pallets such as `pallet_nfts` | [`state_getStorage`](/mythos/state_getStorage) |
| `author_*` | Submit extrinsics and monitor the transaction queue | [`author_submitExtrinsic`](/mythos/author_submitExtrinsic) |
| `rpc_methods` | Enumerate every enabled RPC namespace on your node | `rpc_methods` |
### Mythos gaming runtime APIs
| Namespace | Purpose | Method Reference |
|-----------|---------|------------------|
| `nft_*` | Fetch collection metadata and individual asset attributes for Mythos NFTs | [`nft_getAsset`](/mythos/nft_getAsset) |
| `gaming_*` | Synchronize cross-game inventory, player loadouts, and progression | [`gaming_getPlayerAssets`](/mythos/gaming_getPlayerAssets) |
| `marketplace_*` | Query live marketplace listings, escrow terms, and order book depth | [`marketplace_getListings`](/mythos/marketplace_getListings) |
## Gaming Features
### NFT & Asset Lifecycle
- `pallet_nfts` enables zero-deposit collection creation, serial minting, and attribute locking to ship seasonal collectibles.
- Developers can gate minting via whitelists or pre-signed approvals, ideal for tournament drops or rarity tiers.
### Cross-Game Compatibility
- Beamable’s Mythos integration syncs player inventory across Unity and Unreal projects, minimizing engine-specific logic.
- Mythical Marketplace analytics show sustained trading volume across titles, ensuring liquidity for interoperable skins.
### Marketplace & Escrow
- `pallet_marketplace` plus `pallet_escrow` facilitate trustless swaps, timed listings, and fee sharing via Mythos DAO policy.
- Example sale: extrinsic `0x6f26cdb2c3398f2cabaa0bf51d3c8ec3f3cbe75ffb8b9b8853718055517b2497` executed `nfts.mint` for a Nitro Nation crate on block 2,611,955.
## SDK Integration Patterns
### Unity & Unreal
- Beamable Mercury SDK adds first-party Unreal support for Mythos inventory endpoints, mirroring Unity parity.
- Use Beamable’s Content flow to push Mythos NFT templates directly into LiveOps campaigns, removing bespoke backend needs.
### Web & Backend Services
- REST backends can leverage `subxt` or Polkadot.js server-side to stream marketplace events and update web portals.
- DotLake analytics confirm 3.3 million Mythos transactions since launch—plan pagination and caching strategies accordingly.
## DAO Governance
- MYTH staking and proposal voting determine future drops, marketplace fee tweaks, and title onboarding through the Mythos DAO.
- Post-launch, the DAO coordinated token swaps to Polkadot-native assets, aligning treasury with relay-chain liquidity.
## Cross-Game Assets
- Seasonal events like Mythical Forest supply interoperable cosmetics that unlock across NFL Rivals, Nitro Nation, and Blankos, with quests rewarding MYTH-backed NFTs.
- Cross-parachain plans include bridging Mythos assets to Moonbeam and Hydration for DeFi utility once XCM channels graduate from testing.
## Development Guides
- **Game Integration:** Start with the `Subxt` example above, then wire in Beamable or custom wallets to mint NFTs post-level completion.
- **NFT Creation:** Configure collection metadata and mint settings via `pallet_nfts.create` followed by `mint_pre_signed` for controlled drops.
- **Marketplace Setup:** Use `pallet_marketplace` order flows and `pallet_dmarket` signatures to enable player-to-player sales with escrow.
## Troubleshooting
- **Slow Finality:** Verify collator health and check parachain finality vs. relay chain using `chain_getFinalizedHead`.
- **Asset Transfer Failures:** Review NFT attribute locks and collection settings—locked metadata or expired approvals cause `MethodDisabled` or `ApprovalExpired` errors.
- **High Fees:** `WeightToFee` scales with max(weight.ref_time, weight.proof_size). Batch extrinsics or use `pallet_multibatching` to amortize costs.
## Resources & Tools
- Mythos migration FAQ and DAO updates on the Mythical Games blog.
- DotLake analytics dashboards for live broadcast of transactions, accounts, and top collections.
- Beamable SDK documentation for Unity and Unreal integration of Mythos wallets.
---
## marketplace_getListings (Mythos marketplace p...
# Read Mythos marketplace listings
Mythos marketplace data lives in `pallet_marketplace` and `pallet_dmarket`. Use `state_getStorage` or higher-level SDKs to pull current asks, bids, and settlement metadata. The examples below use block data from **3 Oct 2025**.
## Storage entries
| Entry | Purpose |
|-------|---------|
| `Marketplace::Asks(collectionId, itemId)` | Fixed-price listings (seller, price, fee, expiration, escrow agent) |
| `Marketplace::Bids(collectionId, itemId)` | Active bids awaiting seller acceptance |
| `Marketplace::Nonces(accountId)` | Monotonic nonce per seller (useful for off-chain signatures) |
| `Dmarket::ClosedAsks` / `ClosedBids` | Historical fills for analytics |
## Fetching live asks
```bash
curl https://api-mythos-archive.n.dwellir.com/YOUR_API_KEY -H "Content-Type: application/json" -d '{
"jsonrpc": "2.0",
"method": "state_getStorage",
"params": [
"0xb8f32c9f36429933d924999a1b87423f9be4002e98967383af7072a5f12bde48001352fa0fbf816218e34d69e86c8929df0a0000000000000000000000000000000000000000000000000000000000000af23d6fc2fce072a34ac19d2a5553b615000000000000000000000000000000"
],
"id": 31
}'
```
**Response**
```json
{
"jsonrpc": "2.0",
"id": 31,
"result": "0x6f5e2dee7182143c809c6606f5c50ffb0cc7f4dd000050efe2d6e41a1b0000000000000000d8c32cbb030000000058c51ff571cb030000000000000001dbe1638c2063432d6923e30d2f4406e2e91e767f"
}
```
Decoded fields:
- `collectionId = 2783`
- `itemId = 21`
- `seller = 0x6f5e2dee7182143c809c6606f5c50ffb0cc7f4dd`
- `price = 500000000000000000000` plancks (0.50 MYTH)
- `fee = 70000000000000000000` plancks (0.07 MYTH)
- `expiration = 4102444800000`
- `escrow_agent = 0xdbe1638c2063432d6923e30d2f4406e2e91e767f`
### JavaScript helper
```typescript
const api = await ApiPromise.create({ provider: new WsProvider('wss://api-mythos-archive.n.dwellir.com/YOUR_API_KEY') });
const ask = await api.query.marketplace.asks(2783, 21);
if (ask.isSome) {
const details = ask.unwrap();
console.log({
seller: details.seller.toHex(),
price: details.price.toString(),
fee: details.fee.toString(),
expires: details.expiration.toNumber()
});
}
```
## Enumerating all listings
1. Use `state_getKeysPaged` with the prefix from `api.query.marketplace.asks.keyPrefix()` to page through asks.
2. Hydrate each key via `api.query.marketplace.asks.at(blockHash, collectionId, itemId)` if you need historical snapshots.
3. Optionally join `Marketplace::Bids` for the same `(collectionId, itemId)` tuple to surface highest bids alongside asks.
## Historical fills
`Dmarket::ClosedAsks` and `Dmarket::ClosedBids` store settled trades. Iterate those maps to build price charts or compliance exports.
## Operational tips
- Normalize planck values to MYTH by dividing by `1e18`.
- Large marketplaces should cache decoded asks and poll every few seconds, or subscribe to `state_subscribeStorage` on the `Marketplace::Asks` prefix.
- Always re-check the ask immediately before executing a purchase extrinsic to avoid stale pricing.
---
## nft_getAsset (Mythos NFT helper)
# Retrieve Mythos NFT asset data
Mythos nodes do not expose a bespoke `nft_getAsset` RPC endpoint. Instead, combine the core Substrate methods `state_getStorage` and `state_getKeysPaged` (or higher level SDK calls) to read `pallet_nfts` storage and any marketplace listings. The examples below were captured on **3 Oct 2025** using the public endpoint `https://api-mythos-archive.n.dwellir.com/YOUR_API_KEY`.
## Storage layout
| Storage entry | Purpose |
|---------------|---------|
| `Nfts::Item(collectionId, itemId)` | Owner, approvals, and deposit metadata for a specific NFT |
| `Nfts::Collection(collectionId)` | Collection owner, minted counts, and attribute flags |
| `Marketplace::Asks(collectionId, itemId)` | Active fixed-price listings (seller, price, expiry, escrow agent) |
## Example: collection `2783`, item `21`
The following request reads `Nfts::Item(2783, 21)`—an NFT owned by `0x6f5e2dee7182143c809c6606f5c50ffb0cc7f4dd`. The storage key was generated with `api.query.nfts.item.key(2783, 21)`.
```bash
curl https://api-mythos-archive.n.dwellir.com/YOUR_API_KEY -H "Content-Type: application/json" -d '{
"jsonrpc": "2.0",
"method": "state_getStorage",
"params": [
"0xe8d49389c2e23e152fdd6364daadd2cce6636c7091b616c035068763633f33e2001352fa0fbf816218e34d69e86c8929df0a0000000000000000000000000000000000000000000000000000000000000af23d6fc2fce072a34ac19d2a5553b615000000000000000000000000000000"
],
"id": 11
}'
```
**Sample response**
```json
{
"jsonrpc": "2.0",
"id": 11,
"result": "0x6f5e2dee7182143c809c6606f5c50ffb0cc7f4dd00b78aec3ecc939755abfe78aba306f2bf428da63700000000000000000000000000000000"
}
```
Decoding the SCALE payload as `ItemDetails` yields:
- `owner = 0x6f5e2dee7182143c809c6606f5c50ffb0cc7f4dd`
- `deposit.account = 0xb78aec3ecc939755abfe78aba306f2bf428da637`
- `deposit.amount = 0`
- `approvals = []`
### JavaScript helper
```typescript
async function loadItem(collectionId: number, itemId: number) {
const api = await ApiPromise.create({ provider: new WsProvider('wss://api-mythos-archive.n.dwellir.com/YOUR_API_KEY') });
const item = await api.query.nfts.item(collectionId, itemId);
if (item.isNone) {
throw new Error('Item not found');
}
const details = item.unwrap();
console.log(`Owner: ${details.owner.toHex()}`);
console.log(`Deposit account: ${details.deposit.account.toHex()}`);
}
loadItem(2783, 21).catch(console.error);
```
## Joining marketplace data
`Marketplace::Asks(2783, 21)` contains the active listing for the same asset. The seller, price, and escrow agent are combined in a single SCALE payload.
```bash
curl https://api-mythos-archive.n.dwellir.com/YOUR_API_KEY -H "Content-Type: application/json" -d '{
"jsonrpc": "2.0",
"method": "state_getStorage",
"params": [
"0xb8f32c9f36429933d924999a1b87423f9be4002e98967383af7072a5f12bde48001352fa0fbf816218e34d69e86c8929df0a0000000000000000000000000000000000000000000000000000000000000af23d6fc2fce072a34ac19d2a5553b615000000000000000000000000000000"
],
"id": 12
}'
```
**Sample response**
```json
{
"jsonrpc": "2.0",
"id": 12,
"result": "0x6f5e2dee7182143c809c6606f5c50ffb0cc7f4dd000050efe2d6e41a1b0000000000000000d8c32cbb030000000058c51ff571cb030000000000000001dbe1638c2063432d6923e30d2f4406e2e91e767f"
}
```
Decoding yields:
- `seller = 0x6f5e2dee7182143c809c6606f5c50ffb0cc7f4dd`
- `price = 500000000000000000000` plancks (0.500000000000000000 MYTH)
- `fee = 70000000000000000000` plancks (0.070000000000000000 MYTH)
- `expiration = 4102444800000` (Unix millis; effectively no expiry)
- `escrow_agent = 0xdbe1638c2063432d6923e30d2f4406e2e91e767f`
### Rust (dynamic API)
```rust
use subxt::{dynamic::Value, OnlineClient, config::substrate::SubstrateConfig};
#[tokio::main]
async fn main() -> subxt::Result<()> {
let api = OnlineClient::::from_url("wss://api-mythos-archive.n.dwellir.com/YOUR_API_KEY").await?;
let item: Value = api
.storage()
.at(None)
.await?
.fetch(&Value::from_parts("Nfts", "Item", (2783u32, 21u128)))?
.expect("item exists");
println!("Item details: {item:?}");
let ask: Value = api
.storage()
.at(None)
.await?
.fetch(&Value::from_parts("Marketplace", "Asks", (2783u32, 21u128)))?
.expect("ask exists");
println!("Listing: {ask:?}");
Ok(())
}
```
## Best practices
- Cache decoded JSON in your asset or marketplace service; most fields only change on ownership transfers or new listings.
- Use `state_getKeysPaged` on `Nfts::Item` to backfill entire collections without overloading the RPC node (e.g., batches of 256 keys).
- Always confirm a listing exists before letting players buy—prices may be updated or removed between UI refreshes and submission time.
---
## payment_queryFeeDetails - Mythos RPC Method
# payment_queryFeeDetails
Returns a detailed breakdown of fees for a given extrinsic on Mythos. 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 AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# payment_queryInfo
Estimates the fee for an extrinsic on Mythos.
## Use Cases
- **Fee estimation** - Calculate transaction costs before sending
- **UI display** - Show fees to users for AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# rpc_methods
Returns a list of all RPC methods available on Mythos.
## Use Cases
- **API discovery** - List all available methods
- **Compatibility checking** - Verify method availability for AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# state_call
Calls a runtime API method on Mythos.
## Use Cases
- **Runtime computations** - Execute runtime logic without transactions
- **Account queries** - Use AccountNonceApi for AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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 (Mythos)
# state_getKeys – Mythos JSON-RPC Method
Returns all storage keys with the given prefix. This is useful when inspecting NFT collections, marketplace listings, or DAO proposals stored in maps.
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `keyPrefix` | string | Yes | Hex-encoded storage key prefix (usually `twox128(pallet) + twox128(storageItem)`). |
| `at` | string | No | Block hash to query. Defaults to latest. |
## Request Example
```json
{
"jsonrpc": "2.0",
"method": "state_getKeys",
"params": [
"0x26aa394eea5630e07c48ae0c9558cef7",
null
],
"id": 1
}
```
## Tips
- The response can be large for popular pallets; prefer `state_getKeysPaged` for pagination.
- Combine with `state_getStorage` to fetch the associated values.
## Related Methods
- [`state_getKeysPaged`](/mythos/state_getKeysPaged)
- [`state_getStorage`](/mythos/state_getStorage)
- [`state_getMetadata`](/mythos/state_getMetadata)
---
## state_getKeysPaged - Mythos RPC Method
# state_getKeysPaged
Returns storage keys with pagination on Mythos.
## Use Cases
- **Storage iteration** - Enumerate storage map entries
- **Data export** - Bulk export chain data for AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# state_getMetadata
Returns the runtime metadata on Mythos.
## Use Cases
- **Runtime introspection** - Discover available pallets and calls
- **Extrinsic building** - Get call and type information for AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# state_getRuntimeVersion
Returns the runtime version on Mythos.
## Use Cases
- **Version checking** - Verify runtime compatibility
- **Upgrade detection** - Monitor for runtime upgrades on AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# state_getStorage
Returns a storage entry at a specific key on Mythos.
> **Why Mythos?** Build on the gaming blockchain powering FIFA Rivals and NFL Rivals with World ID verification with World ID proof-of-humanity, Polkadot security, Snowbridge cross-chain bridge, and 1M+ downloads per title.
## Use Cases
- **State queries** - Read on-chain storage values
- **Account balances** - Query account data for AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# state_queryStorageAt
Query multiple storage keys at a specific block on Mythos.
## Use Cases
- **Batch queries** - Efficiently query multiple storage items
- **Snapshot state** - Get consistent multi-key state for AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# system_chain
Returns the chain name on Mythos.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_chain",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl https://api-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# system_health
Returns the health status of the Mythos node.
## Use Cases
- **Health checks** - Monitor node availability
- **Load balancing** - Route traffic based on health for AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# system_name
Returns the node implementation name on Mythos.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_name",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl https://api-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# system_properties
Returns chain properties including token symbol and decimals on Mythos.
## Use Cases
- **Token formatting** - Get decimals and symbol for AAA gaming (FIFA Rivals, NFL Rivals, Pudgy Party), player-owned economies, and bot-resistant matchmaking
- **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-mythos-archive.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-mythos-archive.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 - Mythos RPC Method
# system_version
Returns the node implementation version on Mythos.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_version",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl https://api-mythos-archive.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-mythos-archive.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 - Neuroweb RPC Method
# author_pendingExtrinsics
Returns all pending extrinsics in the transaction pool on Neuroweb.
## Use Cases
- **Mempool monitoring** - Track pending transactions
- **Transaction status** - Check if your transaction is pending for decentralized knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# author_rotateKeys
Generate a new set of session keys on Neuroweb. 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 knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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-neuroweb.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 - Neuroweb 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 knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# author_submitExtrinsic
Submit a signed extrinsic to Neuroweb for inclusion in a block.
## Use Cases
- **Transaction submission** - Broadcast signed transactions
- **dApp interactions** - Execute on-chain operations for decentralized knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# beefy_getFinalizedHead
Returns the block hash of the latest BEEFY-finalized block on Neuroweb. 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 knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# chain_getBlock
Retrieves complete block information from Neuroweb, including the block header, extrinsics, and justifications.
> **Why Neuroweb?** Build on the decentralized AI blockchain powering 125M+ Knowledge Assets with MIT-awarded technology with OriginTrail DKG V8 with 500-1000x scalability, 40% of US imports secured, EVM compatibility, and Best Decentralized AI Project (MIT).
## 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 knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# chain_getBlockHash
Returns the block hash for a given block number on Neuroweb.
## Use Cases
- **Historical queries** - Convert block numbers to hashes
- **Block navigation** - Navigate blockchain history for decentralized knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# chain_getFinalizedHead
Returns the hash of the last finalized block on Neuroweb.
## Use Cases
- **Confirmed state** - Query state that cannot be reverted
- **Transaction confirmation** - Verify transaction finality for decentralized knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# chain_getHeader
Returns the block header for a given hash on Neuroweb.
## Use Cases
- **Lightweight queries** - Get header without full block data
- **Chain synchronization** - Track block production for decentralized knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# chain_subscribeFinalizedHeads
Subscribe to receive notifications when blocks are finalized on Neuroweb. 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 knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# chain_subscribeNewHeads
Subscribe to receive notifications when new block headers are produced on Neuroweb. This WebSocket subscription provides real-time updates for each new block.
## Use Cases
- **Block monitoring** - Track new blocks in real-time for decentralized knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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(Neuroweb)
# eth_accounts
List available accounts on the Neuroweb network.
## Parameters
Varies by method. Please refer to the official [Neuroweb 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-neuroweb.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-neuroweb.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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_blockNumber - Get Latest Block Number(Neuroweb)
# eth_blockNumber
Returns the number of the most recent block on Neuroweb 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-neuroweb.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-neuroweb.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-neuroweb.n.dwellir.com/YOUR_API_KEY');
const blockNumber = await provider.getBlockNumber();
console.log('Current block:', blockNumber);
```
```python
def get_block_number():
url = 'https://api-neuroweb.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-neuroweb.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-neuroweb.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-neuroweb.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(Neuroweb)
# 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-neuroweb.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-neuroweb.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"; // Neuroweb 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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_chainId - Get chain ID(Neuroweb)
# eth_chainId
Get chain ID on the Neuroweb network.
## Parameters
Varies by method. Please refer to the official [Neuroweb 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-neuroweb.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-neuroweb.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 Neuroweb mainnet.
---
*Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Neuroweb documentation](/docs/neuroweb).*
---
## eth_coinbase - Get coinbase address(Neuroweb)
# eth_coinbase
Get coinbase address on the Neuroweb network.
## Parameters
Varies by method. Please refer to the official [Neuroweb 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-neuroweb.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-neuroweb.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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_estimateGas - Estimate Transaction Gas(Neuroweb)
# 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-neuroweb.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 Neuroweb 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) {
// Neuroweb 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-neuroweb.n.dwellir.com/YOUR_API_KEY'))
class GasCalculator:
"""Calculate and optimize gas for Neuroweb 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 (Neuroweb 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 Neuroweb Mainnet"""
# Serialize transaction to estimate size
tx_data = self.w3.to_json(transaction)
data_size = len(tx_data.encode('utf-8'))
# Neuroweb 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 # Neuroweb 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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_feeHistory - Get historical gas prices(Neuroweb)
# eth_feeHistory
Returns historical gas information for the Neuroweb 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-neuroweb.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-neuroweb.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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_gasPrice - Get Current Gas Price(Neuroweb)
# eth_gasPrice
Returns the current gas price in wei. This represents the median gas price from recent blocks on Neuroweb 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-neuroweb.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-neuroweb.n.dwellir.com/YOUR_API_KEY'))
class GasPriceAnalyzer:
"""Analyze and optimize gas prices on Neuroweb 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 - Neuroweb 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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_getBalance - Query Account Balance(Neuroweb)
# eth_getBalance
Returns the ETH balance of a given address on Neuroweb 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": [
"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"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-neuroweb.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": [
"0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
"latest"
],
"id": 1
}'
```
```javascript
// Using ethers.js
const provider = new JsonRpcProvider('https://api-neuroweb.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-neuroweb.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-neuroweb.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
address := common.HexToAddress("0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb")
// 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-neuroweb.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-neuroweb.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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_getBlockByHash - Get block Info by hash...
# eth_getBlockByHash
Retrieves comprehensive information about a block on Neuroweb 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 Neuroweb 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 Neuroweb 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 Neuroweb 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-neuroweb.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 response = await fetch('https://api-neuroweb.n.dwellir.com/YOUR_API_KEY', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_getBlockByHash',
params: [
'0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd',
false // Set to true for full transaction objects
],
id: 1
})
});
const data = await response.json();
console.log(data.result);
```
```python
url = 'https://api-neuroweb.n.dwellir.com/YOUR_API_KEY'
headers = {'Content-Type': 'application/json'}
payload = {
"jsonrpc": "2.0",
"method": "eth_getBlockByHash",
"params": [
"0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd",
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": "0x4e3a3754410177e6937ef1f84bba68ea139e8d1a2258c5f85db9f1cd715a1bdd",
"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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_getBlockByNumber - Get Block Details(Neuroweb)
# eth_getBlockByNumber
Returns information about a block by block number on Neuroweb 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., `"0x5BAD55"`)
2. **Transaction Details** - `Boolean`
- `true` - Returns full transaction objects
- `false` - Returns only transaction hashes
```json
{
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params": [
"0x5BAD55",
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 (Neuroweb specific) |
## Implementation Examples
```bash
# Get block with transaction hashes only
curl -X POST https://api-neuroweb.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-neuroweb.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByNumber",
"params": ["0x5BAD55", true],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-neuroweb.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('Neuroweb 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-neuroweb.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-neuroweb.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": "0x5bad55",
"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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_getCode - Get Neuroweb Contract Bytecode
# eth_getCode
Retrieves the compiled bytecode of a smart contract deployed on the Neuroweb 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-neuroweb.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-neuroweb.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-neuroweb.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
- Neuroweb is the main Layer 1 blockchain using Proof of Stake consensus
- Bytecode format is identical to Neuroweb mainnet
- Gas costs for contract deployment and execution are significantly lower
- Full compatibility with Neuroweb smart contracts and tooling
---
*Need help? Contact our [support team](mailto:support@dwellir.com) or check the [Neuroweb documentation](/docs/neuroweb).*
---
## eth_getFilterChanges - Poll filter for changes
# eth_getFilterChanges
Polling method for a filter, which returns an array of events that have occurred since the last poll on the Neuroweb 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
curl -X POST https://api-neuroweb.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getFilterChanges",
"params": ["0x16"],
"id": 1
}'
```
```javascript
const response = await fetch('https://api-neuroweb.n.dwellir.com/YOUR_API_KEY', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_getFilterChanges',
params: ['0x16'],
id: 1
})
});
const data = await response.json();
console.log(data.result);
```
```python
url = 'https://api-neuroweb.n.dwellir.com/YOUR_API_KEY'
headers = {'Content-Type': 'application/json'}
payload = {
"jsonrpc": "2.0",
"method": "eth_getFilterChanges",
"params": ["0x16"],
"id": 1
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
data = response.json()
print(data['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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_getFilterLogs - Get Filter Logs(Neuroweb)
# eth_getFilterLogs
Returns an array of all logs matching filter with given id on the Neuroweb 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
curl -X POST https://api-neuroweb.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getFilterLogs",
"params": ["0x16"],
"id": 1
}'
```
```javascript
const response = await fetch('https://api-neuroweb.n.dwellir.com/YOUR_API_KEY', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_getFilterLogs',
params: ['0x16'],
id: 1
})
});
const data = await response.json();
console.log(data.result);
```
```python
url = 'https://api-neuroweb.n.dwellir.com/YOUR_API_KEY'
headers = {'Content-Type': 'application/json'}
payload = {
"jsonrpc": "2.0",
"method": "eth_getFilterLogs",
"params": ["0x16"],
"id": 1
}
response = requests.post(url, headers=headers, data=json.dumps(payload))
data = response.json()
print(data['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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_getLogs - Query Event Logs(Neuroweb)
# 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-neuroweb.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getLogs",
"params": [{
"fromBlock": "0x1",
"toBlock": "latest",
"address": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
"topics": [
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
]
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-neuroweb.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-neuroweb.n.dwellir.com/YOUR_API_KEY'))
class LogAnalyzer:
"""Analyze and query event logs on Neuroweb 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
- Neuroweb 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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_getStorageAt - Get Contract Storage Values
# eth_getStorageAt
Retrieves the value from a storage position at a given address on the Neuroweb 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-neuroweb.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 Neuroweb USDC contract
const getStorage = async () => {
const response = await fetch('https://api-neuroweb.n.dwellir.com/YOUR_API_KEY', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_getStorageAt',
params: [
'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // Neuroweb 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-neuroweb.n.dwellir.com/YOUR_API_KEY',
json=payload,
headers={'Content-Type': 'application/json'}
)
return response.json()['result']
# Example: Read from Neuroweb 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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_getTransactionByHash - Get Transaction...
# 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": [
"0x88df016429689c079f3b2f6ad39fa052532c56795b733da78a91ebe6a713944b"
],
"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-neuroweb.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-neuroweb.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(
"0x88df016429689c079f3b2f6ad39fa052532c56795b733da78a91ebe6a713944b"
)
# Analyze transaction
analysis = monitor.analyze_transaction(
"0x88df016429689c079f3b2f6ad39fa052532c56795b733da78a91ebe6a713944b"
)
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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_getTransactionCount - Get Neuroweb Nonce
# eth_getTransactionCount
Retrieves the number of transactions sent from an account on the Neuroweb 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 Neuroweb 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 Neuroweb Mainnet network.
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `address` | string | Yes | The Neuroweb 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-neuroweb.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [
"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"latest"
],
"id": 1
}'
# Get pending transaction count (includes mempool)
curl -X POST https://api-neuroweb.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [
"0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"pending"
],
"id": 2
}'
```
```javascript
// Get confirmed transaction count for wallet
async function getAccountNonce(address) {
const response = await fetch('https://api-neuroweb.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-neuroweb.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 = '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045';
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-neuroweb.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 = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
# 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
### Neuroweb Network Specifics
- Neuroweb uses a sequential nonce system for transaction ordering
- Transaction finality depends on network confirmation requirements
- Nonce management is crucial for Neuroweb 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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_getTransactionReceipt - Get Receipt(Neuroweb)
# 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": [
"0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"
],
"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 (Neuroweb specific)
- `l1GasPrice` - L1 gas price used (Neuroweb specific)
- `l1GasUsed` - L1 gas consumed (Neuroweb specific)
## Implementation Examples
```javascript
const provider = new JsonRpcProvider('https://api-neuroweb.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,
// Neuroweb 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-neuroweb.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),
# Neuroweb 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 (Neuroweb 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(
"0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"
)
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(
"0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"
)
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(
"0xb903239f8543d04b5dc1ba6579132b143087c68db1b2168786408fcbce568238"
)
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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_hashrate - Get node hashrate(Neuroweb)
# eth_hashrate
Get node hashrate on the Neuroweb network.
## Parameters
Varies by method. Please refer to the official [Neuroweb 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-neuroweb.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-neuroweb.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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_maxPriorityFeePerGas - Get priority fee...
# eth_maxPriorityFeePerGas
Returns the priority fee needed for inclusion in the next block on the Neuroweb 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-neuroweb.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-neuroweb.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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_mining - Check if node is mining(Neuroweb)
# eth_mining
Check if node is mining on the Neuroweb network.
## Parameters
Varies by method. Please refer to the official [Neuroweb 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-neuroweb.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-neuroweb.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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_newBlockFilter - Subscribe to new blocks(Neuroweb)
# eth_newBlockFilter
Subscribe to new blocks on the Neuroweb network.
## Parameters
Varies by method. Please refer to the official [Neuroweb 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-neuroweb.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-neuroweb.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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_newFilter - Create event filter(Neuroweb)
# eth_newFilter
Creates a filter object, based on filter options, to notify when the state changes (logs) on the Neuroweb 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-neuroweb.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-neuroweb.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-neuroweb.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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_newPendingTransactionFilter - Monitor p...
# eth_newPendingTransactionFilter
Monitor pending transactions on the Neuroweb network.
## Parameters
Varies by method. Please refer to the official [Neuroweb 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-neuroweb.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-neuroweb.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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_protocolVersion - Get protocol version(Neuroweb)
# eth_protocolVersion
Get protocol version on the Neuroweb network.
## Parameters
Varies by method. Please refer to the official [Neuroweb 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-neuroweb.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-neuroweb.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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_sendRawTransaction - Broadcast Signed T...
# 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-neuroweb.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),
// Neuroweb uses EIP-1559 transactions
type: 2,
chainId: 1, // Neuroweb 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-neuroweb.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 # Neuroweb 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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_sendTransaction - Send transaction (wal...(Neuroweb)
# eth_sendTransaction
> **Important**: Dwellir's shared Neuroweb 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-neuroweb.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...(Neuroweb)
# 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-neuroweb.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-neuroweb.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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_syncing - Check node sync status(Neuroweb)
# eth_syncing
Check node sync status on the Neuroweb network.
## Parameters
Varies by method. Please refer to the official [Neuroweb 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-neuroweb.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-neuroweb.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 [Neuroweb documentation](/docs/neuroweb).*
---
## eth_uninstallFilter - Uninstall Filter(Neuroweb)
# eth_uninstallFilter
Remove filter subscription on the Neuroweb network.
## Parameters
Varies by method. Please refer to the official [Neuroweb 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
curl -X POST https://api-neuroweb.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_uninstallFilter",
"params": [],
"id": 1
}'
```
```javascript
const response = await fetch('https://api-neuroweb.n.dwellir.com/YOUR_API_KEY', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'eth_uninstallFilter',
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 [Neuroweb documentation](/docs/neuroweb).*
---
## grandpa_roundState - Neuroweb RPC Method
# grandpa_roundState
Returns the state of the current GRANDPA finality round on Neuroweb. 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 knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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-neuroweb.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)
---
## NeuroWeb RPC Documentation
# NeuroWeb RPC API Documentation
## Overview
NeuroWeb is a decentralized AI blockchain and Polkadot parachain designed to incentivize knowledge creation, connectivity, and sharing through Knowledge Mining. Built on the Substrate framework and evolved from OriginTrail Parachain, NeuroWeb enables the creation and management of verifiable knowledge assets, powering the Decentralized Knowledge Graph (DKG) that organizes humanity's most important assets.
This documentation provides comprehensive coverage of NeuroWeb's JSON-RPC API methods, enabling developers to interact with NeuroWeb nodes for building applications, wallets, explorers, and other blockchain tools.
## Network Information
### Mainnet (NeuroWeb)
- **Parachain ID**: 2043
- **Native Token**: NEURO
- **Consensus**: Nominated Proof-of-Stake (NPoS) via Polkadot
- **Framework**: Substrate
- **Special Features**: EVM-enabled, Decentralized Knowledge Graph, AI-focused
## Connection Endpoints
### HTTPS Endpoint
```
https://api-neuroweb.n.dwellir.com/{YOUR_API_KEY}
```
### WebSocket Endpoint
```
wss://api-neuroweb.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
NeuroWeb's RPC API is organized into the following method categories:
### Core APIs
#### [Author Methods](/neuroweb#author-methods)
Submit and manage extrinsics (transactions) on the network.
#### [Chain Methods](/neuroweb#chain-methods)
Query blockchain data including blocks, headers, and finalized state.
#### [State Methods](/neuroweb#state-methods)
Access runtime storage, metadata, and proof generation.
#### [System Methods](/neuroweb#system-methods)
Node information, health checks, and network properties.
### Specialized APIs
#### [BEEFY Methods](/neuroweb#beefy-methods)
Bridge Efficiency Enabling Finality Yielder protocol operations.
#### [Grandpa Methods](/neuroweb#grandpa-methods)
GRANDPA finality gadget operations and proofs.
#### [Child State Methods](/neuroweb#child-state-methods)
Manage child storage tries for contracts and parachains.
#### [Sync State Methods](/neuroweb#sync-state-methods)
Monitor and manage node synchronization state.
## Quick Start Examples
### Get Latest Block
```javascript
const response = await fetch('https://api-neuroweb.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-neuroweb.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-neuroweb.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
NeuroWeb 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 NeuroWeb)
- **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-neuroweb.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;
}
```
## NeuroWeb Features
### Decentralized Knowledge Graph
NeuroWeb powers the Decentralized Knowledge Graph (DKG), enabling the creation and management of verifiable knowledge assets. The network has scaled to support billions of interconnected knowledge assets with recent V8 improvements.
### AI-Focused Infrastructure
As a decentralized AI blockchain, NeuroWeb incentivizes knowledge creation and sharing through Knowledge Mining, providing infrastructure for AI applications that require verifiable, trustworthy data.
### EVM Compatibility
NeuroWeb is EVM-enabled, allowing developers to deploy Ethereum-compatible smart contracts alongside Substrate-native pallets, providing flexibility for various application architectures.
### Polkadot Integration
As a Polkadot parachain, NeuroWeb 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
- [NeuroWeb Official Website](https://neuroweb.ai/)
- [NeuroWeb Documentation](https://docs.neuroweb.ai/)
- [OriginTrail Documentation](https://docs.origintrail.io/)
- [NeuroWeb GitHub](https://github.com/OriginTrail/neuroweb)
- [Polkadot Parachains Info](https://parachains.info/details/neuroweb)
- [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(Neuroweb)
# net_listening
Check if node is listening on the Neuroweb network.
## Parameters
Varies by method. Please refer to the official [Neuroweb 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-neuroweb.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-neuroweb.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 [Neuroweb documentation](/docs/neuroweb).*
---
## net_peerCount - Get connected peer count(Neuroweb)
# net_peerCount
Get connected peer count on the Neuroweb network.
## Parameters
Varies by method. Please refer to the official [Neuroweb 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-neuroweb.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-neuroweb.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 [Neuroweb documentation](/docs/neuroweb).*
---
## net_version - Get network ID(Neuroweb)
# net_version
Get network ID on the Neuroweb network.
## Parameters
Varies by method. Please refer to the official [Neuroweb 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-neuroweb.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-neuroweb.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 [Neuroweb documentation](/docs/neuroweb).*
---
## payment_queryFeeDetails - Neuroweb RPC Method
# payment_queryFeeDetails
Returns a detailed breakdown of fees for a given extrinsic on Neuroweb. 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 knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# payment_queryInfo
Estimates the fee for an extrinsic on Neuroweb.
## Use Cases
- **Fee estimation** - Calculate transaction costs before sending
- **UI display** - Show fees to users for decentralized knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# rpc_methods
Returns a list of all RPC methods available on Neuroweb.
## Use Cases
- **API discovery** - List all available methods
- **Compatibility checking** - Verify method availability for decentralized knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# state_call
Calls a runtime API method on Neuroweb.
## Use Cases
- **Runtime computations** - Execute runtime logic without transactions
- **Account queries** - Use AccountNonceApi for decentralized knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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(Neuroweb)
## 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-neuroweb.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-neuroweb.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-neuroweb.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-neuroweb.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`](./state_getKeysPaged) - Get keys with pagination
- [`state_getStorage`](./state_getStorage) - Get storage value
- [`state_getMetadata`](./state_getMetadata) - Get metadata to decode keys
---
## state_getKeysPaged - Neuroweb RPC Method
# state_getKeysPaged
Returns storage keys with pagination on Neuroweb.
## Use Cases
- **Storage iteration** - Enumerate storage map entries
- **Data export** - Bulk export chain data for decentralized knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# state_getMetadata
Returns the runtime metadata on Neuroweb.
## Use Cases
- **Runtime introspection** - Discover available pallets and calls
- **Extrinsic building** - Get call and type information for decentralized knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# state_getRuntimeVersion
Returns the runtime version on Neuroweb.
## Use Cases
- **Version checking** - Verify runtime compatibility
- **Upgrade detection** - Monitor for runtime upgrades on decentralized knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# state_getStorage
Returns a storage entry at a specific key on Neuroweb.
> **Why Neuroweb?** Build on the decentralized AI blockchain powering 125M+ Knowledge Assets with MIT-awarded technology with OriginTrail DKG V8 with 500-1000x scalability, 40% of US imports secured, EVM compatibility, and Best Decentralized AI Project (MIT).
## Use Cases
- **State queries** - Read on-chain storage values
- **Account balances** - Query account data for decentralized knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# state_queryStorageAt
Query multiple storage keys at a specific block on Neuroweb.
## Use Cases
- **Batch queries** - Efficiently query multiple storage items
- **Snapshot state** - Get consistent multi-key state for decentralized knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# system_chain
Returns the chain name on Neuroweb.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_chain",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl https://api-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# system_health
Returns the health status of the Neuroweb node.
## Use Cases
- **Health checks** - Monitor node availability
- **Load balancing** - Route traffic based on health for decentralized knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# system_name
Returns the node implementation name on Neuroweb.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_name",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl https://api-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# system_properties
Returns chain properties including token symbol and decimals on Neuroweb.
## Use Cases
- **Token formatting** - Get decimals and symbol for decentralized knowledge graphs (DKG), verifiable AI, supply chain audits, and knowledge mining
- **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-neuroweb.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-neuroweb.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 - Neuroweb RPC Method
# system_version
Returns the node implementation version on Neuroweb.
## Parameters
This method accepts no parameters.
## Request
```json
{
"jsonrpc": "2.0",
"method": "system_version",
"params": [],
"id": 1
}
```
## Code Examples
```bash
curl https://api-neuroweb.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-neuroweb.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(Neuroweb)
# web3_clientVersion
Get client version on the Neuroweb network.
## Parameters
Varies by method. Please refer to the official [Neuroweb 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-neuroweb.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-neuroweb.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 [Neuroweb documentation](/docs/neuroweb).*
---
## web3_sha3 - Calculate Keccak-256 Hash on Ne...
# web3_sha3
Calculate Keccak-256 hash on the Neuroweb network.
## Parameters
Varies by method. Please refer to the official [Neuroweb 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-neuroweb.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "web3_sha3",
"params": [],
"id": 1
}'
```
```javascript
const response = await fetch('https://api-neuroweb.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 [Neuroweb documentation](/docs/neuroweb).*
---
## debug_traceBlock - opBNB RPC Method
# debug_traceBlock
Traces all transactions in a block on opBNB 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 fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
## 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-opbnb-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-opbnb-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 - opBNB RPC Method
# debug_traceBlockByHash
Traces all transactions in a block on opBNB 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": ["0x95db196d5589ba674d0397bf718f513e7d0e8509ba6829bd3e4435b87562e286", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceBlockByHash",
"params": ["0x95db196d5589ba674d0397bf718f513e7d0e8509ba6829bd3e4435b87562e286", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0x95db196d5589ba674d0397bf718f513e7d0e8509ba6829bd3e4435b87562e286';
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 - opBNB RPC Method
# debug_traceBlockByNumber
Traces all transactions in a block on opBNB 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-opbnb-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-opbnb-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 - opBNB RPC Method
# debug_traceCall
Traces a call without creating a transaction on opBNB.
:::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 fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
## 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-opbnb-mainnet.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-opbnb-mainnet.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 - opBNB RPC Method
# debug_traceTransaction
Traces a transaction execution on opBNB 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 fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
## 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": ["0xf8ee79d0a4a8ab785a1971caa68937195b4908c72d749a38c3188ed967501f1d", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceTransaction",
"params": ["0xf8ee79d0a4a8ab785a1971caa68937195b4908c72d749a38c3188ed967501f1d", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY');
const txHash = '0xf8ee79d0a4a8ab785a1971caa68937195b4908c72d749a38c3188ed967501f1d';
// 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-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0xf8ee79d0a4a8ab785a1971caa68937195b4908c72d749a38c3188ed967501f1d'
# 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 - opBNB RPC Method
# eth_accounts
Returns a list of addresses owned by the client on opBNB.
> **Why opBNB?** Build on Binance's high-performance L2 processing 100M+ daily transactions with the lowest L2 gas fees with sub-$0.0001 gas fees, 5-10K TPS, sub-second block times via Volta/Maxwell upgrades, and OP Stack architecture.
## 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 GameFi developers, high-frequency dApp builders, and teams requiring BNB Chain integration 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-opbnb-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-opbnb-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-opbnb-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-opbnb-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-opbnb-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-opbnb-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 - opBNB RPC Method
# eth_blockNumber
Returns the number of the most recent block on opBNB.
> **Why opBNB?** Build on Binance's high-performance L2 processing 100M+ daily transactions with the lowest L2 gas fees with sub-$0.0001 gas fees, 5-10K TPS, sub-second block times via Volta/Maxwell upgrades, and OP Stack architecture.
## When to Use This Method
`eth_blockNumber` is fundamental for GameFi developers, high-frequency dApp builders, and teams requiring BNB Chain integration:
- **Syncing Applications** — Keep your dApp in sync with the latest opBNB blockchain state
- **Transaction Monitoring** — Verify confirmations by comparing block numbers
- **Event Filtering** — Set the correct block range for querying logs on fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
- **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-opbnb-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-opbnb-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('opBNB block:', blockNumber);
// Using ethers.js
const provider = new JsonRpcProvider('https://api-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockNumber = await provider.getBlockNumber();
console.log('opBNB block:', blockNumber);
```
```python
def get_block_number():
response = requests.post(
'https://api-opbnb-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'opBNB block: {block_number}')
# Using web3.py
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY'))
print(f'opBNB 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-opbnb-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("opBNB block: %d\n", blockNumber)
}
```
## Common Use Cases
### 1. Block Confirmation Counter
Monitor transaction confirmations on opBNB:
```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 opBNB:
```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 opBNB 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-opbnb-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 - opBNB RPC Method
# eth_call
Executes a new message call immediately without creating a transaction on opBNB. Used for reading smart contract state.
> **Why opBNB?** Build on Binance's high-performance L2 processing 100M+ daily transactions with the lowest L2 gas fees with sub-$0.0001 gas fees, 5-10K TPS, sub-second block times via Volta/Maxwell upgrades, and OP Stack architecture.
## 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 fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
- **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-opbnb-mainnet.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-opbnb-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-opbnb-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(
'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-opbnb-mainnet.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 - opBNB RPC Method
# eth_chainId
Returns the chain ID used for transaction signing on opBNB.
> **Why opBNB?** Build on Binance's high-performance L2 processing 100M+ daily transactions with the lowest L2 gas fees with sub-$0.0001 gas fees, 5-10K TPS, sub-second block times via Volta/Maxwell upgrades, and OP Stack architecture.
## 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-opbnb-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-opbnb-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-opbnb-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-opbnb-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(Opbnb)
# eth_coinbase
Get coinbase address on the opBNB 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-opbnb-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-opbnb-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 [opBNB documentation](/docs/opbnb).*
---
## eth_estimateGas - opBNB RPC Method
# eth_estimateGas
Estimates the gas necessary to execute a transaction on opBNB.
> **Why opBNB?** Build on Binance's high-performance L2 processing 100M+ daily transactions with the lowest L2 gas fees with sub-$0.0001 gas fees, 5-10K TPS, sub-second block times via Volta/Maxwell upgrades, and OP Stack architecture.
## 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 fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
## 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-opbnb-mainnet.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-opbnb-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-opbnb-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('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-opbnb-mainnet.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_feeHistory - opBNB RPC Method
# eth_feeHistory
Returns historical gas information on opBNB 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 fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
## 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-opbnb-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-opbnb-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-opbnb-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 - opBNB RPC Method
# eth_gasPrice
Returns the current gas price on opBNB in wei.
> **Why opBNB?** Build on Binance's high-performance L2 processing 100M+ daily transactions with the lowest L2 gas fees with sub-$0.0001 gas fees, 5-10K TPS, sub-second block times via Volta/Maxwell upgrades, and OP Stack architecture.
## 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 fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
## 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-opbnb-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-opbnb-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-opbnb-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-opbnb-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 - opBNB RPC Method
# eth_getBalance
Returns the balance of a given address on opBNB.
> **Why opBNB?** Build on Binance's high-performance L2 processing 100M+ daily transactions with the lowest L2 gas fees with sub-$0.0001 gas fees, 5-10K TPS, sub-second block times via Volta/Maxwell upgrades, and OP Stack architecture.
## 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 fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
- **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-opbnb-mainnet.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-opbnb-mainnet.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-opbnb-mainnet.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-opbnb-mainnet.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 - opBNB RPC Method
# eth_getBlockByHash
Returns information about a block by hash on opBNB.
> **Why opBNB?** Build on Binance's high-performance L2 processing 100M+ daily transactions with the lowest L2 gas fees with sub-$0.0001 gas fees, 5-10K TPS, sub-second block times via Volta/Maxwell upgrades, and OP Stack architecture.
## 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 fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
- **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": [
"0x95db196d5589ba674d0397bf718f513e7d0e8509ba6829bd3e4435b87562e286",
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-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByHash",
"params": [
"0x95db196d5589ba674d0397bf718f513e7d0e8509ba6829bd3e4435b87562e286",
false
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0x95db196d5589ba674d0397bf718f513e7d0e8509ba6829bd3e4435b87562e286';
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-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY'))
block_hash = '0x95db196d5589ba674d0397bf718f513e7d0e8509ba6829bd3e4435b87562e286'
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-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
blockHash := common.HexToHash("0x95db196d5589ba674d0397bf718f513e7d0e8509ba6829bd3e4435b87562e286")
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 - opBNB RPC Method
# eth_getBlockByNumber
Returns information about a block by block number on opBNB.
> **Why opBNB?** Build on Binance's high-performance L2 processing 100M+ daily transactions with the lowest L2 gas fees with sub-$0.0001 gas fees, 5-10K TPS, sub-second block times via Volta/Maxwell upgrades, and OP Stack architecture.
## 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 fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
- **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": "0x95db196d5589ba674d0397bf718f513e7d0e8509ba6829bd3e4435b87562e286",
"parentHash": "0x...",
"timestamp": "0x64d8f6d0",
"gasUsed": "0x1234",
"gasLimit": "0x1c9c380",
"transactions": [],
"baseFeePerGas": "0x5f5e100"
}
}
```
## Code Examples
```bash
curl -X POST https://api-opbnb-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-opbnb-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-opbnb-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-opbnb-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 - opBNB RPC Method
# eth_getCode
Returns the bytecode at a given address on opBNB.
> **Why opBNB?** Build on Binance's high-performance L2 processing 100M+ daily transactions with the lowest L2 gas fees with sub-$0.0001 gas fees, 5-10K TPS, sub-second block times via Volta/Maxwell upgrades, and OP Stack architecture.
## 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 fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
## 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-opbnb-mainnet.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-opbnb-mainnet.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-opbnb-mainnet.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-opbnb-mainnet.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 - opBNB RPC Method
# eth_getFilterChanges
Polling method for a filter on opBNB, returns an array of logs since last poll.
## Use Cases
- **Event streaming** - Get new events incrementally
- **Real-time monitoring** - Track contract activity for fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
- **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-opbnb-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-opbnb-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 - opBNB RPC Method
# eth_getFilterLogs
Returns an array of all logs matching filter with given ID on opBNB.
## Use Cases
- **Historical queries** - Get all matching logs for a filter
- **Full event history** - Retrieve complete event data for fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
## 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-opbnb-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-opbnb-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 - opBNB RPC Method
# eth_getLogs
Returns an array of all logs matching a given filter object on opBNB.
> **Why opBNB?** Build on Binance's high-performance L2 processing 100M+ daily transactions with the lowest L2 gas fees with sub-$0.0001 gas fees, 5-10K TPS, sub-second block times via Volta/Maxwell upgrades, and OP Stack architecture.
## Use Cases
The `eth_getLogs` method is essential for:
- **Event indexing** - Track contract events for fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
- **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-opbnb-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": "0x4200000000000000000000000000000000000006",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-opbnb-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(
'0x4200000000000000000000000000000000000006',
'latest',
'latest'
);
console.log('Transfer events:', events);
```
```python
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-opbnb-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(
'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-opbnb-mainnet.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 - opBNB RPC Method
# eth_getStorageAt
Returns the value from a storage position at a given address on opBNB.
## Use Cases
- **Contract analysis** - Read raw storage values
- **State verification** - Verify contract state
- **Security auditing** - Analyze storage layout for fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
- **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-opbnb-mainnet.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-opbnb-mainnet.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-opbnb-mainnet.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 - opBNB RPC Method
# eth_getTransactionByHash
Returns the information about a transaction by transaction hash on opBNB.
> **Why opBNB?** Build on Binance's high-performance L2 processing 100M+ daily transactions with the lowest L2 gas fees with sub-$0.0001 gas fees, 5-10K TPS, sub-second block times via Volta/Maxwell upgrades, and OP Stack architecture.
## 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 fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
- **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": ["0xf8ee79d0a4a8ab785a1971caa68937195b4908c72d749a38c3188ed967501f1d"],
"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-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionByHash",
"params": ["0xf8ee79d0a4a8ab785a1971caa68937195b4908c72d749a38c3188ed967501f1d"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY');
const txHash = '0xf8ee79d0a4a8ab785a1971caa68937195b4908c72d749a38c3188ed967501f1d';
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-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0xf8ee79d0a4a8ab785a1971caa68937195b4908c72d749a38c3188ed967501f1d'
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-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0xf8ee79d0a4a8ab785a1971caa68937195b4908c72d749a38c3188ed967501f1d")
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 - opBNB RPC Method
# eth_getTransactionCount
Returns the number of transactions sent from an address on opBNB (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 fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
## 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-opbnb-mainnet.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-opbnb-mainnet.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-opbnb-mainnet.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 - opBNB RPC Method
# eth_getTransactionReceipt
Returns the receipt of a transaction by transaction hash on opBNB. Receipt is only available for mined transactions.
> **Why opBNB?** Build on Binance's high-performance L2 processing 100M+ daily transactions with the lowest L2 gas fees with sub-$0.0001 gas fees, 5-10K TPS, sub-second block times via Volta/Maxwell upgrades, and OP Stack architecture.
## 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 fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `transactionHash` | `DATA` | Yes | 32-byte transaction hash |
## Request
```json
{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0xf8ee79d0a4a8ab785a1971caa68937195b4908c72d749a38c3188ed967501f1d"],
"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-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0xf8ee79d0a4a8ab785a1971caa68937195b4908c72d749a38c3188ed967501f1d"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY');
const txHash = '0xf8ee79d0a4a8ab785a1971caa68937195b4908c72d749a38c3188ed967501f1d';
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-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0xf8ee79d0a4a8ab785a1971caa68937195b4908c72d749a38c3188ed967501f1d'
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-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0xf8ee79d0a4a8ab785a1971caa68937195b4908c72d749a38c3188ed967501f1d")
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(Opbnb)
# eth_hashrate
Get node hashrate on the opBNB 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-opbnb-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-opbnb-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 [opBNB documentation](/docs/opbnb).*
---
## eth_maxPriorityFeePerGas - opBNB RPC Method
# eth_maxPriorityFeePerGas
Returns the current recommended priority fee per gas on opBNB 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 fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
## 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-opbnb-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-opbnb-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-opbnb-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(Opbnb)
# eth_mining
Check if node is mining on the opBNB 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-opbnb-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-opbnb-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 [opBNB documentation](/docs/opbnb).*
---
## eth_newBlockFilter - opBNB RPC Method
# eth_newBlockFilter
Creates a filter on opBNB 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-opbnb-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-opbnb-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 - opBNB RPC Method
# eth_newFilter
Creates a filter object on opBNB to notify when state changes (logs).
## Use Cases
- **Event monitoring** - Subscribe to contract events
- **Real-time updates** - Track events for fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
- **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-opbnb-mainnet.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-opbnb-mainnet.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 - opBNB RPC Method
# eth_newPendingTransactionFilter
Creates a filter on opBNB 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-opbnb-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-opbnb-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(Opbnb)
# eth_protocolVersion
Get protocol version on the opBNB 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-opbnb-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-opbnb-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 [opBNB documentation](/docs/opbnb).*
---
## eth_sendRawTransaction - opBNB RPC Method
# eth_sendRawTransaction
Submits a pre-signed transaction for broadcast to opBNB.
> **Why opBNB?** Build on Binance's high-performance L2 processing 100M+ daily transactions with the lowest L2 gas fees with sub-$0.0001 gas fees, 5-10K TPS, sub-second block times via Volta/Maxwell upgrades, and OP Stack architecture.
## 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 fully on-chain games, high-frequency DeFi, and cost-sensitive applications on BNB Chain
- **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-opbnb-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-opbnb-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-opbnb-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-opbnb-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("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...(Opbnb)
# eth_sendTransaction
> **Important**: Dwellir's shared opBNB 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-opbnb-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 (rarely...(Opbnb)
# 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-opbnb-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-opbnb-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 [opBNB documentation](/docs/opbnb).*
---
## eth_syncing - opBNB RPC Method
# eth_syncing
Returns syncing status of opBNB 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-opbnb-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-opbnb-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 - opBNB RPC Method
# eth_uninstallFilter
Uninstalls a filter on opBNB. 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-opbnb-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-opbnb-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
---
## opBNB RPC with Dwellir
# opBNB - Build on BNB Chain's High-Performance Layer 2
## Why Build on opBNB?
opBNB is BNB Chain's Layer 2 solution, designed to offer ultra-low fees and lightning-fast transaction processing. Built on Optimism's OP Stack, opBNB delivers:
### ⚡ **Ultra-High Performance**
- **Sub-second block times** - Experience instant transaction confirmations
- **100x lower fees** than BNB Smart Chain mainnet
- **150M gas limit** - Massive throughput for complex applications
### 🛡️ **Enterprise-Grade Security**
- **Backed by BNB Chain** - Leverages proven Layer 1 infrastructure
- **Optimistic rollup technology** - Inherits Ethereum-level security guarantees
- **Battle-tested architecture** - Built on proven OP Stack foundation
### 🌐 **Thriving Ecosystem**
- **Native BNB token** - No new tokens to manage
- **EVM compatibility** - Deploy existing contracts seamlessly
- **Growing DeFi ecosystem** - Access to expanding financial infrastructure
## Quick Start with opBNB
Connect to opBNB in seconds with Dwellir's optimized endpoints:
### Installation & Setup
```javascript
// Connect to opBNB mainnet
const provider = new JsonRpcProvider(
'https://api-opbnb-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 opBNB mainnet
const web3 = new Web3(
'https://api-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY'
);
// Get chain ID to verify connection
const chainId = await web3.eth.getChainId();
console.log('Connected to opBNB:', chainId === 204);
// Get gas price for optimal transaction pricing
const gasPrice = await web3.eth.getGasPrice();
console.log('Current gas price:', gasPrice);
```
```typescript
// Create opBNB client
const client = createPublicClient({
chain: opBNB,
transport: http('https://api-opbnb-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 opBNB mainnet
w3 = Web3(Web3.HTTPProvider('https://api-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY'))
# Verify connection
print(f"Connected: {w3.is_connected()}")
print(f"Chain ID: {w3.eth.chain_id}")
print(f"Latest block: {w3.eth.block_number}")
# Get account balance
balance = w3.eth.get_balance('0x...')
print(f"Balance: {w3.from_wei(balance, 'ether')} BNB")
```
## Network Information
Chain ID
204
Mainnet
Gas Limit
150M
Per block
Gas Token
BNB
Native token
RPC Standard
Ethereum
JSON-RPC 2.0
## JSON-RPC API Reference
opBNB supports the full [Ethereum JSON-RPC API specification](https://ethereum.org/developers/docs/apis/json-rpc/). Access all standard methods plus Layer 2 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);
// Check transaction status
if (receipt.status === 1) {
console.log('Transaction confirmed:', receipt.transactionHash);
}
return receipt;
}
```
### 💰 Gas Optimization
Optimize gas costs on opBNB Layer 2:
```javascript
// Get current fee data
const feeData = await provider.getFeeData();
// Estimate gas for transaction
const gasEstimate = await provider.estimateGas({
to: recipient,
value: amount,
data: '0x'
});
// Calculate total cost
const totalCost = gasEstimate * feeData.gasPrice;
console.log(`Transaction cost: ${totalCost} wei`);
```
### 🔍 Event Filtering
Efficiently query contract events with 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 = 5000; // opBNB recommended batch size
const currentBlock = await provider.getBlockNumber();
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 OpBNBProvider {
static instance = null;
static getInstance() {
if (!this.instance) {
this.instance = new JsonRpcProvider(
'https://api-opbnb-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
### Wrong Chain ID Error
opBNB uses specific chain IDs for mainnet and testnet:
```javascript
// Always verify chain ID matches expected network
const chainId = await provider.send('eth_chainId', []);
if (chainId === '0xcc') {
console.log('Connected to opBNB Mainnet (204)');
} else if (chainId === '0x15eb') {
console.log('Connected to opBNB Testnet (5611)');
} else {
throw new Error(`Unexpected chain ID: ${chainId}`);
}
```
### Transaction Underpriced Error
opBNB uses 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
};
```
### 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
**Q: What's the difference between opBNB and BNB Smart Chain?**
A: opBNB is a Layer 2 scaling solution built on top of BNB Smart Chain, offering much lower fees and faster transactions while maintaining full EVM compatibility.
**Q: Can I use the same wallet for opBNB and BSC?**
A: Yes, any Ethereum-compatible wallet works with opBNB. Simply add the opBNB network configuration to your wallet.
**Q: How do I bridge assets to opBNB?**
A: Use the official opBNB Bridge at [https://opbnb-bridge.bnbchain.org](https://opbnb-bridge.bnbchain.org) to transfer assets between BNB Smart Chain and opBNB.
## Smoke Tests
### Quick Connection Tests
**Mainnet Connection:**
```bash
curl -X POST https://api-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}'
```
**Testnet Connection:**
```bash
curl -X POST https://api-opbnb-testnet.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}'
```
### Ethers.js Verification:
```javascript
const provider = new JsonRpcProvider('https://api-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY');
// Test connection
const blockNumber = await provider.getBlockNumber();
const network = await provider.getNetwork();
console.log(`Block: ${blockNumber}, Chain ID: ${network.chainId}`);
```
### Web3.py Verification:
```python
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY'))
print(f"Connected: {w3.is_connected()}")
print(f"Chain ID: {w3.eth.chain_id}")
print(f"Block Number: {w3.eth.block_number}")
```
## Migration Guide
### From BNB Smart Chain to opBNB
Migrating from BSC to opBNB requires minimal code changes:
```javascript
// Before (BSC)
const provider = new JsonRpcProvider('https://bsc-dataseed.bnbchain.org');
// After (opBNB)
const provider = new JsonRpcProvider(
'https://api-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY'
);
// ✅ Smart contracts work identically
// ✅ Same tooling and libraries
// ⚠️ Different chain ID (204 vs 56)
// ⚠️ Separate block numbers
// ⚠️ Much lower gas fees
```
## Resources & Tools
### Official Resources
- [opBNB Documentation](https://docs.bnbchain.org/bnb-opbnb/)
- [opBNB Bridge](https://opbnb-bridge.bnbchain.org)
- [opBNB Block Explorer](https://opbnbscan.com)
### Developer Tools
- [opBNB Documentation](https://docs.bnbchain.org/bnb-opbnb/)
- [Remix IDE Integration](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 opBNB with Dwellir's enterprise-grade RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register)*
---
## net_listening - opBNB RPC Method
# net_listening
Returns `true` if client is actively listening for network connections on opBNB.
## 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-opbnb-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-opbnb-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 - opBNB RPC Method
# net_peerCount
Returns number of peers currently connected to opBNB 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-opbnb-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-opbnb-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 - opBNB RPC Method
# net_version
Returns the current network ID on opBNB.
## 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-opbnb-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-opbnb-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 - opBNB RPC Method
# web3_clientVersion
Returns the current client version on opBNB.
## 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-opbnb-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-opbnb-mainnet.n.dwellir.com/YOUR_API_KEY');
const version = await provider.send('web3_clientVersion', []);
console.log('Client version:', version);
```
---
## web3_sha3 - opBNB RPC Method
# web3_sha3
Returns Keccak-256 (not standard SHA3-256) of the given data on opBNB.
## 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-opbnb-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-opbnb-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 - Optimism RPC Method
# debug_traceBlock
Traces all transactions in a block on Optimism 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 cross-chain DeFi, Superchain-interoperable dApps, and public goods funding recipients
## 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-optimism-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-optimism-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 - Optimism RPC Method
# debug_traceBlockByHash
Traces all transactions in a block on Optimism 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": ["0x76cde4f6f885fe27962356115e0ff0539058a03e8b9e15dac3fb40a9caa0bc47", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceBlockByHash",
"params": ["0x76cde4f6f885fe27962356115e0ff0539058a03e8b9e15dac3fb40a9caa0bc47", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0x76cde4f6f885fe27962356115e0ff0539058a03e8b9e15dac3fb40a9caa0bc47';
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 - Optimism RPC Method
# debug_traceBlockByNumber
Traces all transactions in a block on Optimism 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-optimism-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-optimism-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 - Optimism RPC Method
# debug_traceCall
Traces a call without creating a transaction on Optimism.
:::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 cross-chain DeFi, Superchain-interoperable dApps, and public goods funding recipients
## 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-optimism-mainnet-archive.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-optimism-mainnet-archive.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 - Optimism RPC Method
# debug_traceTransaction
Traces a transaction execution on Optimism 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 cross-chain DeFi, Superchain-interoperable dApps, and public goods funding recipients
## 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": ["0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3", {"tracer": "callTracer"}],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "debug_traceTransaction",
"params": ["0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3", {"tracer": "callTracer"}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const txHash = '0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3';
// 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-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3'
# 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 - Optimism RPC Method
# eth_accounts
Returns a list of addresses owned by the client on Optimism.
> **Why Optimism?** Build on the heart of the Superchain powering 60%+ of Ethereum L2 transactions with $6B+ TVL with OP Stack modularity, Superchain interoperability, 17M+ daily transactions across 33 chains, and 20% of tokens for public goods.
## 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 L2 builders, DeFi developers, and teams launching Superchain-compatible apps 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-optimism-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-optimism-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-optimism-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-optimism-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-optimism-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-optimism-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 - Optimism RPC Method
# eth_blockNumber
Returns the number of the most recent block on Optimism.
> **Why Optimism?** Build on the heart of the Superchain powering 60%+ of Ethereum L2 transactions with $6B+ TVL with OP Stack modularity, Superchain interoperability, 17M+ daily transactions across 33 chains, and 20% of tokens for public goods.
## When to Use This Method
`eth_blockNumber` is fundamental for L2 builders, DeFi developers, and teams launching Superchain-compatible apps:
- **Syncing Applications** — Keep your dApp in sync with the latest Optimism blockchain state
- **Transaction Monitoring** — Verify confirmations by comparing block numbers
- **Event Filtering** — Set the correct block range for querying logs on cross-chain DeFi, Superchain-interoperable dApps, and public goods funding recipients
- **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-optimism-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-optimism-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('Optimism block:', blockNumber);
// Using ethers.js
const provider = new JsonRpcProvider('https://api-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const blockNumber = await provider.getBlockNumber();
console.log('Optimism block:', blockNumber);
```
```python
def get_block_number():
response = requests.post(
'https://api-optimism-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'Optimism block: {block_number}')
# Using web3.py
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
print(f'Optimism 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-optimism-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("Optimism block: %d\n", blockNumber)
}
```
## Common Use Cases
### 1. Block Confirmation Counter
Monitor transaction confirmations on Optimism:
```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 Optimism:
```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 Optimism 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-optimism-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 - Optimism RPC Method
# eth_call
Executes a new message call immediately without creating a transaction on Optimism. Used for reading smart contract state.
> **Why Optimism?** Build on the heart of the Superchain powering 60%+ of Ethereum L2 transactions with $6B+ TVL with OP Stack modularity, Superchain interoperability, 17M+ daily transactions across 33 chains, and 20% of tokens for public goods.
## 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, Superchain-interoperable dApps, and public goods funding recipients
- **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-optimism-mainnet-archive.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-optimism-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-optimism-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(
'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-optimism-mainnet-archive.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 - Optimism RPC Method
# eth_chainId
Returns the chain ID used for transaction signing on Optimism.
> **Why Optimism?** Build on the heart of the Superchain powering 60%+ of Ethereum L2 transactions with $6B+ TVL with OP Stack modularity, Superchain interoperability, 17M+ daily transactions across 33 chains, and 20% of tokens for public goods.
## 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-optimism-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-optimism-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-optimism-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-optimism-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(Optimism)
# eth_coinbase
Returns the client coinbase address on Optimism Layer 2.
## Implementation Examples
```bash
curl -X POST https://api-optimism-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-optimism-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 - Optimism RPC Method
# eth_estimateGas
Estimates the gas necessary to execute a transaction on Optimism.
> **Why Optimism?** Build on the heart of the Superchain powering 60%+ of Ethereum L2 transactions with $6B+ TVL with OP Stack modularity, Superchain interoperability, 17M+ daily transactions across 33 chains, and 20% of tokens for public goods.
## 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, Superchain-interoperable dApps, and public goods funding recipients
## 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-optimism-mainnet-archive.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-optimism-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-optimism-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('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-optimism-mainnet-archive.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_estimateL1Fee - Estimate L1 Data Fee(Optimism)
# 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-optimism-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-optimism-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-optimism-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-optimism-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-optimism-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-optimism-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-optimism-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 - Optimism RPC Method
# eth_feeHistory
Returns historical gas information on Optimism 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, Superchain-interoperable dApps, and public goods funding recipients
## 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-optimism-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-optimism-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-optimism-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 - Optimism RPC Method
# eth_gasPrice
Returns the current gas price on Optimism in wei.
> **Why Optimism?** Build on the heart of the Superchain powering 60%+ of Ethereum L2 transactions with $6B+ TVL with OP Stack modularity, Superchain interoperability, 17M+ daily transactions across 33 chains, and 20% of tokens for public goods.
## 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, Superchain-interoperable dApps, and public goods funding recipients
## 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-optimism-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-optimism-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-optimism-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-optimism-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 - Optimism RPC Method
# eth_getBalance
Returns the balance of a given address on Optimism.
> **Why Optimism?** Build on the heart of the Superchain powering 60%+ of Ethereum L2 transactions with $6B+ TVL with OP Stack modularity, Superchain interoperability, 17M+ daily transactions across 33 chains, and 20% of tokens for public goods.
## 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, Superchain-interoperable dApps, and public goods funding recipients
- **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-optimism-mainnet-archive.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-optimism-mainnet-archive.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-optimism-mainnet-archive.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-optimism-mainnet-archive.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 - Optimism RPC Method
# eth_getBlockByHash
Returns information about a block by hash on Optimism.
> **Why Optimism?** Build on the heart of the Superchain powering 60%+ of Ethereum L2 transactions with $6B+ TVL with OP Stack modularity, Superchain interoperability, 17M+ daily transactions across 33 chains, and 20% of tokens for public goods.
## 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, Superchain-interoperable dApps, and public goods funding recipients
- **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": [
"0x76cde4f6f885fe27962356115e0ff0539058a03e8b9e15dac3fb40a9caa0bc47",
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-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getBlockByHash",
"params": [
"0x76cde4f6f885fe27962356115e0ff0539058a03e8b9e15dac3fb40a9caa0bc47",
false
],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const blockHash = '0x76cde4f6f885fe27962356115e0ff0539058a03e8b9e15dac3fb40a9caa0bc47';
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-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
block_hash = '0x76cde4f6f885fe27962356115e0ff0539058a03e8b9e15dac3fb40a9caa0bc47'
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-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
blockHash := common.HexToHash("0x76cde4f6f885fe27962356115e0ff0539058a03e8b9e15dac3fb40a9caa0bc47")
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 - Optimism RPC Method
# eth_getBlockByNumber
Returns information about a block by block number on Optimism.
> **Why Optimism?** Build on the heart of the Superchain powering 60%+ of Ethereum L2 transactions with $6B+ TVL with OP Stack modularity, Superchain interoperability, 17M+ daily transactions across 33 chains, and 20% of tokens for public goods.
## 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, Superchain-interoperable dApps, and public goods funding recipients
- **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": "0x76cde4f6f885fe27962356115e0ff0539058a03e8b9e15dac3fb40a9caa0bc47",
"parentHash": "0x...",
"timestamp": "0x64d8f6d0",
"gasUsed": "0x1234",
"gasLimit": "0x1c9c380",
"transactions": [],
"baseFeePerGas": "0x5f5e100"
}
}
```
## Code Examples
```bash
curl -X POST https://api-optimism-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-optimism-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-optimism-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-optimism-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 - Optimism RPC Method
# eth_getCode
Returns the bytecode at a given address on Optimism.
> **Why Optimism?** Build on the heart of the Superchain powering 60%+ of Ethereum L2 transactions with $6B+ TVL with OP Stack modularity, Superchain interoperability, 17M+ daily transactions across 33 chains, and 20% of tokens for public goods.
## 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, Superchain-interoperable dApps, and public goods funding recipients
## 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-optimism-mainnet-archive.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-optimism-mainnet-archive.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-optimism-mainnet-archive.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-optimism-mainnet-archive.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 - Optimism RPC Method
# eth_getFilterChanges
Polling method for a filter on Optimism, 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, Superchain-interoperable dApps, and public goods funding recipients
- **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-optimism-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-optimism-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 - Optimism RPC Method
# eth_getFilterLogs
Returns an array of all logs matching filter with given ID on Optimism.
## Use Cases
- **Historical queries** - Get all matching logs for a filter
- **Full event history** - Retrieve complete event data for cross-chain DeFi, Superchain-interoperable dApps, and public goods funding recipients
## 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-optimism-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-optimism-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 - Optimism RPC Method
# eth_getLogs
Returns an array of all logs matching a given filter object on Optimism.
> **Why Optimism?** Build on the heart of the Superchain powering 60%+ of Ethereum L2 transactions with $6B+ TVL with OP Stack modularity, Superchain interoperability, 17M+ daily transactions across 33 chains, and 20% of tokens for public goods.
## Use Cases
The `eth_getLogs` method is essential for:
- **Event indexing** - Track contract events for cross-chain DeFi, Superchain-interoperable dApps, and public goods funding recipients
- **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-optimism-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": "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
"topics": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-optimism-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(
'0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',
'latest',
'latest'
);
console.log('Transfer events:', events);
```
```python
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://api-optimism-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(
'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-optimism-mainnet-archive.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 - Optimism RPC Method
# eth_getStorageAt
Returns the value from a storage position at a given address on Optimism.
## Use Cases
- **Contract analysis** - Read raw storage values
- **State verification** - Verify contract state
- **Security auditing** - Analyze storage layout for cross-chain DeFi, Superchain-interoperable dApps, and public goods funding recipients
- **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-optimism-mainnet-archive.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-optimism-mainnet-archive.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-optimism-mainnet-archive.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 - Optimism RPC Method
# eth_getTransactionByHash
Returns the information about a transaction by transaction hash on Optimism.
> **Why Optimism?** Build on the heart of the Superchain powering 60%+ of Ethereum L2 transactions with $6B+ TVL with OP Stack modularity, Superchain interoperability, 17M+ daily transactions across 33 chains, and 20% of tokens for public goods.
## 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, Superchain-interoperable dApps, and public goods funding recipients
- **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": ["0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3"],
"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-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionByHash",
"params": ["0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const txHash = '0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3';
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-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3'
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-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3")
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 - Optimism RPC Method
# eth_getTransactionCount
Returns the number of transactions sent from an address on Optimism (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, Superchain-interoperable dApps, and public goods funding recipients
## 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-optimism-mainnet-archive.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-optimism-mainnet-archive.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-optimism-mainnet-archive.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 - Optimism RPC Method
# eth_getTransactionReceipt
Returns the receipt of a transaction by transaction hash on Optimism. Receipt is only available for mined transactions.
> **Why Optimism?** Build on the heart of the Superchain powering 60%+ of Ethereum L2 transactions with $6B+ TVL with OP Stack modularity, Superchain interoperability, 17M+ daily transactions across 33 chains, and 20% of tokens for public goods.
## 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, Superchain-interoperable dApps, and public goods funding recipients
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `transactionHash` | `DATA` | Yes | 32-byte transaction hash |
## Request
```json
{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3"],
"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-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "eth_getTransactionReceipt",
"params": ["0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const txHash = '0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3';
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-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
tx_hash = '0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3'
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-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY")
if err != nil {
log.Fatal(err)
}
txHash := common.HexToHash("0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3")
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(Optimism)
# 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-optimism-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-optimism-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 - Optimism RPC Method
# eth_maxPriorityFeePerGas
Returns the current recommended priority fee per gas on Optimism 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, Superchain-interoperable dApps, and public goods funding recipients
## 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-optimism-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-optimism-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-optimism-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(Optimism)
# 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-optimism-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-optimism-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 - Optimism RPC Method
# eth_newBlockFilter
Creates a filter on Optimism 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-optimism-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-optimism-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 - Optimism RPC Method
# eth_newFilter
Creates a filter object on Optimism to notify when state changes (logs).
## Use Cases
- **Event monitoring** - Subscribe to contract events
- **Real-time updates** - Track events for cross-chain DeFi, Superchain-interoperable dApps, and public goods funding recipients
- **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-optimism-mainnet-archive.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-optimism-mainnet-archive.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 - Optimism RPC Method
# eth_newPendingTransactionFilter
Creates a filter on Optimism 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-optimism-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-optimism-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(Optimism)
# eth_protocolVersion
Returns the current ethereum protocol version used by Optimism Layer 2.
## Implementation Examples
```bash
curl -X POST https://api-optimism-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-optimism-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 - Optimism RPC Method
# eth_sendRawTransaction
Submits a pre-signed transaction for broadcast to Optimism.
> **Why Optimism?** Build on the heart of the Superchain powering 60%+ of Ethereum L2 transactions with $6B+ TVL with OP Stack modularity, Superchain interoperability, 17M+ daily transactions across 33 chains, and 20% of tokens for public goods.
## 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, Superchain-interoperable dApps, and public goods funding recipients
- **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-optimism-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-optimism-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-optimism-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-optimism-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("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(Optimism)
# eth_sendTransaction
> **Important**: Dwellir's shared Optimism 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-optimism-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(Optimism)
# 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-optimism-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-optimism-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 - Optimism RPC Method
# eth_syncing
Returns syncing status of Optimism 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-optimism-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-optimism-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 - Optimism RPC Method
# eth_uninstallFilter
Uninstalls a filter on Optimism. 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-optimism-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-optimism-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
---
## Optimism RPC - Fast & Reliable Optimism Node API
# Optimism RPC Documentation
## Network Overview
Optimism is a Layer 2 scaling solution for Ethereum that uses optimistic rollups to achieve faster transactions and lower fees while maintaining Ethereum's security. As one of the leading L2 solutions, Optimism provides an EVM-equivalent environment that makes it easy for developers to deploy existing Ethereum applications.
## Key Features
### 🚀 High Performance
- **Fast Transactions**: Sub-second block times with instant transaction confirmation
- **Low Costs**: Up to 100x lower gas fees compared to Ethereum mainnet
- **High Throughput**: Process thousands of transactions per second
### 🔒 Security & Reliability
- **Ethereum Security**: Inherits security from Ethereum mainnet
- **Fraud Proofs**: Optimistic rollup design with challenge period for security
- **99.99% Uptime**: Enterprise-grade infrastructure with global redundancy
### 🛠️ Developer Experience
- **EVM Equivalence**: Deploy existing Solidity contracts without modification
- **Full JSON-RPC**: Complete [Ethereum JSON-RPC API](https://ethereum.org/developers/docs/apis/json-rpc/) compatibility
- **Archive Data**: Access to full historical blockchain data
- **Debug & Trace APIs**: Advanced debugging capabilities for developers
## Quick Start
## Network Information
### Mainnet Configuration
- **Network Name**: Optimism Mainnet
- **Chain ID**: 10 (0xa)
- **Currency Symbol**: ETH
- **Block Explorer**: https://optimistic.etherscan.io
### Testnet Configuration
- **Network Name**: Optimism Sepolia
- **Chain ID**: 11155420 (0xaa37dc)
- **Currency Symbol**: ETH
- **Block Explorer**: https://sepolia-optimism.etherscan.io
## Supported APIs
Our Optimism endpoints support the complete Ethereum JSON-RPC specification plus Optimism-specific methods:
### Core APIs
- ✅ **Standard Ethereum JSON-RPC**: All eth_* methods
- ✅ **Web3 Methods**: web3_clientVersion, web3_sha3
- ✅ **Net Methods**: net_version, net_listening, net_peerCount
- ✅ **Debug API**: Transaction and block tracing
- ✅ **Filter API**: Event and log filtering
- ✅ **Subscription API**: Real-time updates via WebSocket
### Optimism L2 Specific
- ✅ **Gas Estimation**: L1 and L2 gas cost estimation
- ✅ **Rollup Info**: Access rollup-specific information
- ✅ **L1 Data Fee**: Calculate L1 data submission costs
- ✅ **Sequencer Status**: Monitor sequencer health
## Use Cases
### DeFi Applications
Build decentralized exchanges, lending protocols, and yield optimizers with low transaction costs and fast confirmation times.
### NFT Marketplaces
Deploy NFT collections and marketplaces with affordable minting and trading, perfect for high-volume applications.
### Gaming & Metaverse
Create blockchain games and virtual worlds where users can perform frequent transactions without high gas costs.
### DAO Infrastructure
Implement governance systems with affordable voting and proposal execution, enabling more democratic participation.
## Integration Examples
### Web3.js
```javascript
const Web3 = require('web3');
const web3 = new Web3('https://api-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
// Get latest block
const block = await web3.eth.getBlock('latest');
console.log('Latest block:', block.number);
// Check balance
const balance = await web3.eth.getBalance('0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0');
console.log('Balance:', web3.utils.fromWei(balance, 'ether'), 'ETH');
```
### Ethers.js
```javascript
const { ethers } = require('ethers');
const provider = new ethers.JsonRpcProvider('https://api-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
// Get network info
const network = await provider.getNetwork();
console.log('Connected to:', network.name, 'Chain ID:', network.chainId);
// Estimate L2 gas
const gasPrice = await provider.getFeeData();
console.log('Gas price:', ethers.formatUnits(gasPrice.gasPrice, 'gwei'), 'gwei');
```
### viem
```typescript
const client = createPublicClient({
chain: optimism,
transport: http('https://api-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY'),
});
// Get chain ID
const chainId = await client.getChainId();
console.log('Chain ID:', chainId);
// Read contract
const balance = await client.getBalance({
address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb0',
});
console.log('Balance:', balance);
```
## Migration Guide
### From Other Providers
Migrating to Dwellir is simple:
1. Sign up for an API key at https://dashboard.dwellir.com
2. Replace your current RPC URL with Dwellir's Optimism endpoint
3. No code changes required - we support the full Ethereum JSON-RPC spec
### From Ethereum Mainnet
Deploying from Ethereum to Optimism:
1. Your Solidity contracts work without modification
2. Use the same deployment tools (Hardhat, Truffle, Foundry)
3. Update your provider URL to our Optimism endpoint
4. Benefit from 100x lower gas costs
## Best Practices
### Optimize for L2
- **Batch Operations**: Group multiple operations to save on L1 data costs
- **Event Monitoring**: Use filters and subscriptions for efficient event tracking
- **Gas Estimation**: Always estimate both L1 and L2 costs before transactions
### Error Handling
```javascript
try {
const result = await provider.send('eth_call', [tx, 'latest']);
return result;
} catch (error) {
if (error.code === -32603) {
// Internal error, retry with exponential backoff
await delay(1000);
return retry();
}
throw error;
}
```
## Troubleshooting
### Common Issues
**Connection Timeouts**
- Check your API key is valid
- Ensure you're using the correct network endpoint
- Verify your firewall allows HTTPS connections
**Nonce Too Low**
- Optimism processes transactions quickly
- Always fetch the latest nonce before sending transactions
- Consider using pending nonce for successive transactions
**L1 Data Fee Estimation**
- Use `eth_estimateGas` for L2 execution cost
- Calculate L1 data fee separately using rollup gas oracle
- Total cost = L2 execution cost + L1 data cost
## Additional Resources
- [Optimism Official Documentation](https://docs.optimism.io)
- [Optimism GitHub](https://github.com/ethereum-optimism)
- [Block Explorer](https://optimistic.etherscan.io)
- [Network Status](https://status.optimism.io)
- [Bridge Interface](https://app.optimism.io/bridge)
## Support
Need help with your Optimism integration?
- 📧 Email: support@dwellir.com
- 📖 Documentation: [Full API Reference](/docs/optimism)
- 🎯 Dashboard: [dashboard.dwellir.com](https://dashboard.dwellir.com)
---
Start building on Optimism with Dwellir's reliable RPC infrastructure. [Get your API key →](https://dashboard.dwellir.com/register) and join thousands of developers scaling Ethereum applications.
---
## net_listening - Optimism RPC Method
# net_listening
Returns `true` if client is actively listening for network connections on Optimism.
## 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-optimism-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-optimism-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 - Optimism RPC Method
# net_peerCount
Returns number of peers currently connected to Optimism 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-optimism-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-optimism-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 - Optimism RPC Method
# net_version
Returns the current network ID on Optimism.
## 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-optimism-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-optimism-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(Optimism)
# 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-optimism-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-optimism-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-optimism-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-optimism-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-optimism-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(Optimism)
# 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-optimism-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-optimism-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-optimism-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).*
---
## trace_block - Optimism RPC Method
# trace_block
Returns traces for all transactions in a block on Optimism.
:::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 cross-chain DeFi, Superchain-interoperable dApps, and public goods funding recipients
## 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-optimism-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-optimism-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-optimism-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 - Optimism RPC Method
# trace_call
Traces a call without creating a transaction on Optimism, 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 cross-chain DeFi, Superchain-interoperable dApps, and public goods funding recipients
## 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-optimism-mainnet-archive.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-optimism-mainnet-archive.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-optimism-mainnet-archive.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 - Optimism RPC Method
# trace_callMany
Traces multiple calls in sequence on Optimism, 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 cross-chain DeFi, Superchain-interoperable dApps, and public goods funding recipients
## 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-optimism-mainnet-archive.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-optimism-mainnet-archive.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-optimism-mainnet-archive.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 - Optimism RPC Method
# trace_filter
Returns traces matching a filter on Optimism.
:::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 cross-chain DeFi, Superchain-interoperable dApps, and public goods funding recipients
## 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-optimism-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": ["0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"],
"count": 10
}],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-optimism-mainnet-archive.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-optimism-mainnet-archive.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 - Optimism RPC Method
# trace_get
Returns a trace at a specific position within a transaction on Optimism.
:::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 cross-chain DeFi, Superchain-interoperable dApps, and public goods funding recipients
## 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": ["0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3", ["0x0"]],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "trace_get",
"params": ["0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3", ["0x0"]],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const trace = await provider.send('trace_get', [
'0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3',
['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-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
trace = w3.provider.make_request('trace_get', [
'0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3',
['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 - Optimism RPC Method
# trace_replayBlockTransactions
Replays all transactions in a block on Optimism 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 cross-chain DeFi, Superchain-interoperable dApps, and public goods funding recipients
## 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-optimism-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-optimism-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-optimism-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 - Optimism RPC Method
# trace_replayTransaction
Replays a transaction on Optimism 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 cross-chain DeFi, Superchain-interoperable dApps, and public goods funding recipients
## 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": ["0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3", ["trace"]],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "trace_replayTransaction",
"params": ["0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3", ["trace"]],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const result = await provider.send('trace_replayTransaction', [
'0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3',
['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-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
result = w3.provider.make_request('trace_replayTransaction', [
'0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3',
['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 - Optimism RPC Method
# trace_transaction
Returns all traces for a specific transaction on Optimism.
:::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 cross-chain DeFi, Superchain-interoperable dApps, and public goods funding recipients
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `txHash` | `DATA` | Yes | 32-byte transaction hash |
## Request
```json
{
"jsonrpc": "2.0",
"method": "trace_transaction",
"params": ["0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3"],
"id": 1
}
```
## Code Examples
```bash
curl -X POST https://api-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "trace_transaction",
"params": ["0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3"],
"id": 1
}'
```
```javascript
const provider = new JsonRpcProvider('https://api-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const traces = await provider.send('trace_transaction', [
'0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3'
]);
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-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY'))
traces = w3.provider.make_request('trace_transaction', [
'0x43ac31f47abf56b34e0903e390dd9a1820ee7f03a6359cf2ef08d7152eb26cf3'
])
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 - Optimism RPC Method
# web3_clientVersion
Returns the current client version on Optimism.
## 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-optimism-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-optimism-mainnet-archive.n.dwellir.com/YOUR_API_KEY');
const version = await provider.send('web3_clientVersion', []);
console.log('Client version:', version);
```
---
## web3_sha3 - Optimism RPC Method
# web3_sha3
Returns Keccak-256 (not standard SHA3-256) of the given data on Optimism.
## 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-optimism-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-optimism-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 - Polkadot RPC Method
# author_pendingExtrinsics
Returns all pending extrinsics in the transaction pool on Polkadot.
## Use Cases
- **Mempool monitoring** - Track pending transactions
- **Transaction status** - Check if your transaction is pending for cross-chain DeFi, parachain deployment, XCM interoperability, and DOT staking (8-10% APY)
- **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-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-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 - Polkadot RPC Method
# author_rotateKeys
Generate a new set of session keys on Polkadot. 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, parachain deployment, XCM interoperability, and DOT staking (8-10% APY)
- **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-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-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-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 - Polkadot 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, parachain deployment, XCM interoperability, and DOT staking (8-10% APY)
- **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-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-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 - Polkadot RPC Method
# author_submitExtrinsic
Submit a signed extrinsic to Polkadot for inclusion in a block.
## Use Cases
- **Transaction submission** - Broadcast signed transactions
- **dApp interactions** - Execute on-chain operations for cross-chain DeFi, parachain deployment, XCM interoperability, and DOT staking (8-10% APY)
- **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-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-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 - Polkadot RPC Method
# beefy_getFinalizedHead
Returns the block hash of the latest BEEFY-finalized block on Polkadot. 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, parachain deployment, XCM interoperability, and DOT staking (8-10% APY)
- **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-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-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-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 - Polkadot RPC Method
# chain_getBlock
Retrieves complete block information from Polkadot, including the block header, extrinsics, and justifications.
> **Why Polkadot?** Build on the heterogeneous multi-chain protocol with $300M+ DeFi TVL and JAM supercomputer upgrade incoming with shared relay chain security, XCM cross-chain messaging, JAM upgrade targeting 1M TPS, and 2.1B DOT supply cap.
## 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, parachain deployment, XCM interoperability, and DOT staking (8-10% APY)
- **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-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-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-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-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 - Polkadot RPC Method
# chain_getBlockHash
Returns the block hash for a given block number on Polkadot.
## Use Cases
- **Historical queries** - Convert block numbers to hashes
- **Block navigation** - Navigate blockchain history for cross-chain DeFi, parachain deployment, XCM interoperability, and DOT staking (8-10% APY)
- **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-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-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-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 - Polkadot RPC Method
# chain_getFinalizedHead
Returns the hash of the last finalized block on Polkadot.
## Use Cases
- **Confirmed state** - Query state that cannot be reverted
- **Transaction confirmation** - Verify transaction finality for cross-chain DeFi, parachain deployment, XCM interoperability, and DOT staking (8-10% APY)
- **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-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-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-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 - Polkadot RPC Method
# chain_getHeader
Returns the block header for a given hash on Polkadot.
## Use Cases
- **Lightweight queries** - Get header without full block data
- **Chain synchronization** - Track block production for cross-chain DeFi, parachain deployment, XCM interoperability, and DOT staking (8-10% APY)
- **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-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-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-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 - Polkadot RPC Method
# chain_subscribeFinalizedHeads
Subscribe to receive notifications when blocks are finalized on Polkadot. 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, parachain deployment, XCM interoperability, and DOT staking (8-10% APY)
- **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-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-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 - Polkadot RPC Method
# chain_subscribeNewHeads
Subscribe to receive notifications when new block headers are produced on Polkadot. 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, parachain deployment, XCM interoperability, and DOT staking (8-10% APY)
- **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-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-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 - Polkadot RPC Method
# grandpa_roundState
Returns the state of the current GRANDPA finality round on Polkadot. 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, parachain deployment, XCM interoperability, and DOT staking (8-10% APY)
- **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