JavaScript ofrece varias bibliotecas potentes para el desarrollo en Ethereum, siendo web3.js y ethers.js las opciones más populares.
La API JavaScript de Ethereum original y más ampliamente utilizada.
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);
};
Biblioteca moderna, completa y compacta.
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();
};
Ambas bibliotecas proporcionan excelente soporte para TypeScript. Al usar TypeScript, obtienes:
import { BigNumber } from 'ethers';
interface TransactionData {
to: string;
value: BigNumber;
gasLimit?: BigNumber;
}
const createTransaction = async (data: TransactionData) => {
// Your implementation
};
Ambas bibliotecas funcionan perfectamente en entornos Node.js:
// 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');
Para entornos de navegador, puedes usar cualquiera de las bibliotecas con empaquetadores como webpack o vite:
// Using ES modules
import { Web3 } from 'web3';
// or
import { ethers } from 'ethers';
// Using window.ethereum (MetaMask)
const provider = new ethers.BrowserProvider(window.ethereum);