Moonbeam – Ethereum-Compatible Smart Contracts on Polkadot
Moonbeam RPC
With Dwellir, you get access to our global Moonbeam network which always routes your API requests to the nearest available location, ensuring low latency and the fastest speeds.
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:
🔗 RPC Endpoints
https://api-moonbeam.n.dwellir.com/YOUR_API_KEY
Quick Connect:
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}'
Installation & Setup
- Ethers.js v6
- Web3.js
- Viem
- Web3.py
import { JsonRpcProvider } from 'ethers';
// 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());
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);
import { createPublicClient, http } from 'viem';
import { moonbeam } from 'viem/chains';
// 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...'],
});
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
MainnetBlock Time
12 seconds
AverageGas Token
GLMR
Native tokenRPC Standard
Ethereum
EVM CompatibleJSON-RPC API Reference
Moonbeam supports the full Ethereum JSON-RPC API specification plus Substrate-specific methods.
Available JSON-RPC Methods
📊 Reading Blockchain Data
Query blocks, transactions, and account states
📤 Sending Transactions
Submit and manage transactions
📝 Smart Contract Interaction
Call and interact with smart contracts
🔧 Node & Network Info
Query node status and network information
Ready to build on Moonbeam?
Get your API key →Common Integration Patterns
🔄 Cross-Chain Messaging
Leverage Moonbeam's native cross-chain capabilities:
// Example: Send message to Ethereum via Axelar
import { AxelarGMPSDK } from '@axelar-network/axelarjs-sdk';
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:
// 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:
// 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:
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:
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:
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:
// 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:
// 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:
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
# 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
// 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
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:
// 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:
// 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
Cross-Chain Tools
Developer Tools
Need Help?
- 📧 Email: support@dwellir.com
- 📚 Docs: You're here!
- 🎯 Dashboard: dashboard.dwellir.com
Start building cross-chain applications on Moonbeam with Dwellir's enterprise-grade RPC infrastructure. Get your API key →