Skip to content

ethers.js Integration

Complete guide to using nodewell with ethers.js v6.

Installation

bash
npm install ethers

Quick Start

javascript
import { ethers } from 'ethers';

// HTTP Provider
const provider = new ethers.JsonRpcProvider(
  'https://eth.nodewell.io/v1/YOUR_API_KEY'
);

// Get current block
const blockNumber = await provider.getBlockNumber();
console.log('Current block:', blockNumber);

HTTP Provider

Basic Usage

javascript
import { ethers } from 'ethers';

const provider = new ethers.JsonRpcProvider(
  'https://eth.nodewell.io/v1/YOUR_API_KEY'
);

// Get block
const block = await provider.getBlock('latest');

// Get balance
const balance = await provider.getBalance('0x...');
console.log('Balance:', ethers.formatEther(balance), 'ETH');

// Get transaction
const tx = await provider.getTransaction('0x...');

// Get receipt
const receipt = await provider.getTransactionReceipt('0x...');

Reading Contracts

javascript
const abi = [
  'function balanceOf(address) view returns (uint256)',
  'function symbol() view returns (string)',
  'function decimals() view returns (uint8)'
];

const usdc = new ethers.Contract(
  '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
  abi,
  provider
);

const symbol = await usdc.symbol();
const balance = await usdc.balanceOf('0x...');
console.log(`${symbol} balance:`, balance.toString());

Sending Transactions

javascript
// Create wallet with provider
const wallet = new ethers.Wallet(privateKey, provider);

// Send ETH
const tx = await wallet.sendTransaction({
  to: '0x...',
  value: ethers.parseEther('0.1')
});

console.log('TX hash:', tx.hash);
await tx.wait();
console.log('Confirmed!');

Contract Events

javascript
const contract = new ethers.Contract(address, abi, provider);

// Query past events
const filter = contract.filters.Transfer();
const events = await contract.queryFilter(filter, -1000); // Last 1000 blocks

Historical Data

Archive node access for historical queries:

javascript
// Get balance at specific block
const pastBalance = await provider.getBalance('0x...', 15000000);

// Call contract at past block
const pastData = await contract.balanceOf('0x...', { blockTag: 15000000 });

// Get logs from range
const logs = await provider.getLogs({
  address: '0x...',
  topics: [...],
  fromBlock: 15000000,
  toBlock: 15001000
});

Error Handling

javascript
try {
  const balance = await provider.getBalance('0x...');
} catch (error) {
  if (error.code === 'NETWORK_ERROR') {
    console.error('Network issue');
  } else if (error.code === 'SERVER_ERROR') {
    console.error('RPC error:', error.message);
  } else {
    throw error;
  }
}

Best Practices

Rate Limit Handling

javascript
import { ethers } from 'ethers';

const provider = new ethers.JsonRpcProvider(
  'https://eth.nodewell.io/v1/YOUR_API_KEY',
  undefined,
  { staticNetwork: true }
);