使用Web3.js获取以太坊地址余额的方法

1,032 阅读1分钟

在Web3.js中,可以使用web3.eth.getBalance(address [, defaultBlock])方法来获取指定地址的余额。以下是一个示例:

const Web3 = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');

const address = '0x123456789...'; // 要查询余额的地址

web3.eth.getBalance(address)
  .then(balance => {
    const balanceInEther = web3.utils.fromWei(balance, 'ether');
    console.log(`Address ${address} balance: ${balanceInEther} Ether`);
  })
  .catch(error => {
    console.error('Error:', error);
  });

请确保将YOUR_INFURA_PROJECT_ID替换为您自己的Infura项目ID,并将address替换为要查询余额的地址。

上述代码中,我们通过web3.eth.getBalance方法获取指定地址的余额。返回的余额是以最小单位(Wei)表示的,我们可以使用web3.utils.fromWei方法将余额转换为以太币单位(Ether)。最后,我们将地址和余额打印到控制台。

请注意,web3.eth.getBalance方法返回一个Promise对象,因此我们使用.then.catch来处理异步结果和错误。

这样,您就可以使用Web3.js获取指定地址的余额并对其进行进一步的处理。