以太坊常见问题和错误

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

我如何通过编程的方式查找以太坊区块链上给定帐户中有多少ETH以太币或者代币?

通过web查账户余额:

这种方式其实不是编程,如果你只想获得帐户或智能合约的余额,可以访问: http://etherchain.org 或者 http://etherscan.io

通过Geth,eth,pyeth命令行控制工具来查询以太坊账户余额:

使用JavaScript API,(通过Geth,eth,pyeth这类控制台使用),可以得到以太坊帐户的余额:

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

web3 是以太坊JavaScript类库,是一个可以用的以太坊接口,详情可以看web3.js1.0中文手册

eth实际上是Web3.eth的简写(因为在geth中可自动获得)。所以,实际上,上面查看以太坊账号余额的代码应该这么写:

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

web3.eth.coinbase是控制台会话的默认帐户。如果你愿意,你可以插入其他的值。所有账户余额在以太坊Ethereum中都是开放公开的。如果你有多个帐户话可以这样来获得代币余额:

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账户余额属性,它返回Wei中的值。智能合约示例代码:

contract ownerbalancereturner {

    address owner;

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

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