JavaScript offers several powerful libraries for Ethereum development, with web3.js and ethers.js being the most popular choices.
The original and most widely used Ethereum JavaScript API.
import Web3 from 'web3';
const web3 = new Web3('YOUR_ETHEREUM_NODE_URL');
// Get balance
const getBalance = async (address) => {
const balance = await web3.eth.getBalance(address);
const balanceInEth = web3.utils.fromWei(balance, 'ether');
return balanceInEth;
};
// Send transaction
const sendTransaction = async (from, to, value) => {
const tx = {
from,
to,
value: web3.utils.toWei(value, 'ether'),
};
return await web3.eth.sendTransaction(tx);
};
Modern, complete and compact library.
import { ethers } from 'ethers';
const provider = new ethers.JsonRpcProvider('YOUR_ETHEREUM_NODE_URL');
// Get balance
const getBalance = async (address) => {
const balance = await provider.getBalance(address);
return ethers.formatEther(balance);
};
// Send transaction
const sendTransaction = async (wallet, to, value) => {
const tx = await wallet.sendTransaction({
to,
value: ethers.parseEther(value),
});
return await tx.wait();
};
Both libraries provide excellent TypeScript support. When using TypeScript, you get:
import { BigNumber } from 'ethers';
interface TransactionData {
to: string;
value: BigNumber;
gasLimit?: BigNumber;
}
const createTransaction = async (data: TransactionData) => {
// Your implementation
};
Both libraries work seamlessly in Node.js environments:
// Web3.js in Node.js
const Web3 = require('web3');
const web3 = new Web3('YOUR_ETHEREUM_NODE_URL');
// Ethers.js in Node.js
const { ethers } = require('ethers');
const provider = new ethers.JsonRpcProvider('YOUR_ETHEREUM_NODE_URL');
For browser environments, you can use either library with bundlers like webpack or vite:
// Using ES modules
import { Web3 } from 'web3';
// or
import { ethers } from 'ethers';
// Using window.ethereum (MetaMask)
const provider = new ethers.BrowserProvider(window.ethereum);