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

Ethers.js v6
Web3.js
Viem
Web3.py

```javascript
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());
```

```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
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...'],
});
```

```python
from web3 import Web3

# Moonbeam RPC with Dwellir
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

| Parameter    | Value      | Details        |
| ------------ | ---------- | -------------- |
| Chain ID     | 1284       | Mainnet        |
| Block Time   | 12 seconds | Average        |
| Gas Token    | GLMR       | Native token   |
| RPC Standard | Ethereum   | EVM Compatible |

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

```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
// Note: Update your API endpoint URL
// Note: 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)*
