我如何获得以太坊账户的余额?

How do I get the balance of an account in Ethereum?

我如何以编程方式发现以太坊区块链上给定帐户中有多少 ETH?

网络上:

(不是程序化的,但为了完整性...)如果你只是想获得账户或合约的余额,你可以访问http://etherchain.org or http://etherscan.io

来自 geth、eth、pyeth 控制台:

使用 Javascript API(geth、eth 和 pyeth 控制台使用的),您可以通过以下方式获取帐户余额:

web3.fromWei(eth.getBalance(eth.coinbase)); 

"web3"就是Ethereum-compatible Javascript library web3.js

"eth" 实际上是 "web3.eth" 的 shorthand(在 geth 中自动可用)。所以,真的,上面应该写成:

web3.fromWei(web3.eth.getBalance(web3.eth.coinbase));

"web3.eth.coinbase" 是您控制台会话的默认帐户。如果愿意,您可以为其插入其他值。所有账户余额都在以太坊中开放。例如,如果您有多个帐户:

web3.fromWei(web3.eth.getBalance(web3.eth.accounts[0]));
web3.fromWei(web3.eth.getBalance(web3.eth.accounts[1]));
web3.fromWei(web3.eth.getBalance(web3.eth.accounts[2]));

web3.fromWei(web3.eth.getBalance('0x2910543af39aba0cd09dbb2d50200b3e800a63d2'));

编辑:这是一个方便的脚本,用于列出您所有帐户的余额:

function checkAllBalances() { var i =0; eth.accounts.forEach( function(e){ console.log("  eth.accounts["+i+"]: " +  e + " \tbalance: " + web3.fromWei(eth.getBalance(e), "ether") + " ether"); i++; })}; checkAllBalances();

内部合约:

在合约内部,Solidity 提供了一种获取余额的简单方法。每个地址都有一个 .balance 属性,其中 returns wei 中的值。合同样本:

contract ownerbalancereturner {

    address owner;

    function ownerbalancereturner() public {
        owner = msg.sender; 
    }

    function getOwnerBalance() constant returns (uint) {
        return owner.balance;
    }
}

对于新版本的web3 API:

最新版本的 web3 API(vers. beta 1.xx)使用 promises(异步,像回调)。 文档:web3 beta 1.xx

因此它是一个 Promise 和 returns 给定地址的字符串。

我在 Linux (openSUSE), geth 1.7.3, Rinkeby 以太坊测试网,使用 Meteor 1.6.1,并通过 IPC Provider 通过以下方式连接到我的 geth 节点:

// serverside js file

import Web3 from 'web3';

if (typeof web3 !== 'undefined') {
  web3 = new Web3(web3.currentProvider);
} else {
  var net = require('net');
  var web3 = new Web3('/home/xxYourHomeFolderxx/.ethereum/geth.ipc', net);
};

  // set the default account
  web3.eth.defaultAccount = '0x123..............';

  web3.eth.coinbase = '0x123..............';

  web3.eth.getAccounts(function(err, acc) {
    _.each(acc, function(e) {
      web3.eth.getBalance(e, function (error, result) {
        if (!error) {
          console.log(e + ': ' + result);
        };
      });
    });
  });

'for-each' 循环有效,但获得平衡的一种非常简短的方法是简单地为函数添加 await

var bal = await web3.eth.getBalance(accounts[0]);

或者如果你想直接显示它:

console.log('balance = : ', await web3.eth.getBalance(accounts[0]));

来自 docs,(查看 link 的变体)

web3.eth.getBalance("0x407d73d8a49eeb85d32cf465507dd71d507100c1")
.then(console.log);
> "1000000000000"

Ethers.js

使用 Ethers.js JavaScript 库,您可以获得 provider.getBalance() 的帐户余额。

这是一个简单的例子(使用 Infura 节点或类似节点):

const provider =
    new ethers.providers.WebSocketProvider('wss://mainnet.infura.io/ws/v3/<your_id>');

async function checkBalance() {
    balance = await provider.getBalance('0x2910543af39aba0cd09dbb2d50200b3e800a63d2');
    console.log(ethers.utils.formatEther(balance));
}

checkBalance();