【Web3项目案例】Ethers.js极简入门+实战案例:实现ERC20协议代币查询、交易
warning:
这篇文章距离上次修改已过235天,其中的内容可能已经有所变动。
// 引入Ethers.js库
const { ethers } = require('ethers');
// 假设已经有了Infura的URL和Project ID
const INFURA_URL = 'https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID';
// 创建Ethers.js的Provider实例
const provider = new ethers.providers.JsonRpcProvider(INFURA_URL);
// 地址
const address = '0x0000000000000000000000000000000000000000';
// 查询ERC20代币的总供应量
async function getTokenTotalSupply(address) {
const contract = new ethers.Contract(address, ['function totalSupply() view returns (uint256)'], provider);
const totalSupply = await contract.totalSupply();
console.log('Total supply:', totalSupply.toString());
}
// 查询特定地址的ERC20代币余额
async function getTokenBalance(address, tokenAddress) {
const contract = new ethers.Contract(tokenAddress, ['function balanceOf(address) view returns (uint256)'], provider);
const balance = await contract.balanceOf(address);
console.log('Balance:', balance.toString());
}
// 查询代币的名称
async function getTokenName(address, tokenAddress) {
const contract = new ethers.Contract(tokenAddress, ['function name() view returns (string)'], provider);
const name = await contract.name();
console.log('Name:', name);
}
// 查询代币的符号
async function getTokenSymbol(address, tokenAddress) {
const contract = new ethers.Contract(tokenAddress, ['function symbol() view returns (string)'], provider);
const symbol = await contract.symbol();
console.log('Symbol:', symbol);
}
// 查询代币的小数位数
async function getTokenDecimals(address, tokenAddress) {
const contract = new ethers.Contract(tokenAddress, ['function decimals() view returns (uint8)'], provider);
const decimals = await contract.decimals();
console.log('Decimals:', decimals.toString());
}
// 执行查询
getTokenTotalSupply('0x86fa049857e0209aa7d9e616f7eb3b3b78ecfdb0'); // 以DAI代币地址为例
getTokenBalance(address, '0x86fa049857e0209aa7d9e616f7eb3b3b78ecfdb0');
getTokenName(address, '0x86fa049857e0209aa7d9e616f7eb3b3b78ecfdb0');
getTokenSymbol(address, '0x86fa049857e0209aa7d9e616f7eb3b3b78ecfdb0');
getTokenDecimals(address, '0x86fa049857e0209aa7d9e616f7eb3b3b78ecfdb0');
这段代码使用Ethers.js库连接到以太坊的Infura节点,并展示了如何查询一个ERC20代币的总供应量、特定地址的余额、名称、符号和小数位数。这是一个简单的以太坊去中心化应用(dApp)的入门级例子,展示了如何在前端或服务器端使用Ethers.js进行基本的区块链和代币信息查询。
评论已关闭