# opBNB RPC with Dwellir

## opBNB RPC plans and rate limits

- **Free plan:** 20 responses per second, up to 100,000 responses a day.
- **Plans:** $49/mo, $299/mo, $999/mo with 25M, 150M, and 500M included responses. Overages billed at $5/$3/$2 per million responses respectively.
- **Paid rate limits:** 100 to 5,000 responses per second (bursts from 500 to 10,000), no daily limit.
- **Billing:** 1 response = 1 API credit on every shared plan, over HTTPS or WebSocket (WSS) where opBNB supports it.

Details: [Pricing](https://www.dwellir.com/docs/getting-started/pricing) · [Rate limits](https://www.dwellir.com/docs/getting-started/rate-limits) · [Authentication](https://www.dwellir.com/docs/getting-started/authentication) · [Archive nodes](https://www.dwellir.com/docs/getting-started/archive-nodes)

## 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

Ethers.js v6
Web3.js
Viem
Web3.py

```javascript
import { JsonRpcProvider } from 'ethers';

// 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
import { createPublicClient, http } from 'viem';
import { opBNB } from 'viem/chains';

// 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

| Parameter    | Value    | Details      |
| ------------ | -------- | ------------ |
| Chain ID     | 204      | Mainnet      |
| Gas Limit    | 150M     | Per block    |
| Gas Token    | BNB      | Native token |
| RPC Standard | Ethereum | JSON-RPC 2.0 |

## 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](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
import { JsonRpcProvider } from 'ethers';

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
// Note: Different chain ID (204 vs 56)
// Note: Separate block numbers
// Note: 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)*
