# MegaETH - The First Real-Time Blockchain

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

Ethers.js v6
Web3.js
Viem

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

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

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

| Parameter    | Value        | Details      |
| ------------ | ------------ | ------------ |
| Chain ID     | 4326         | Mainnet      |
| Block Time   | 0.01 seconds | Real-time    |
| Gas Token    | ETH          | Native token |
| RPC Standard | Ethereum     | JSON-RPC 2.0 |

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

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](https://www.dwellir.com/docs/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
// Note: Different chain ID (4326)
// Note: Some debug methods unavailable
// Note: Gas limits apply (10M for call/estimateGas)
// Note: 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)*
