以太坊入门(二)用web3j进行以太查询及通证查询

以太坊的开发,基本都是go语言和nodejs的天下,web3j出现给java开发人员提供了很大的便利。本文会对一些以太坊的基本操作用java语言来实现。

本章会讲述通过web3j进行账户余额的查询。

  1. 以太余额查询
    以太的余额查询比较简单,直接调用web3j的ethGetBalance就可以。 Web3j web3j = Web3j.build(new HttpService(ConstantLibs.WEB3_ADDRESS)); EthGetBalance ethGetBalance = web3j.ethGetBalance( address, DefaultBlockParameterName.LATEST).sendAsync().get(); BigInteger balance = ethGetBalance.getBalance();
  2. 通证的余额查询
    代币的查询就比较复杂一些,研究了好长时间,最后发现每个代币合约都会实现balanceOf方法,可以通过这个方法来查询通证的余额。 Web3j web3j = Web3j.build(new HttpService(ConstantLibs.WEB3_ADDRESS)); Function function = new Function( "balanceOf", Arrays.asList(new Address(address)), // Solidity Types in smart contract functions Arrays.asList(new TypeReference<Type>() { })); String encodedFunction = FunctionEncoder.encode(function); org.web3j.protocol.core.methods.response.EthCall response = web3j.ethCall( org.web3j.protocol.core.methods.request.Transaction.createEthCallTransaction(address, contract, encodedFunction), DefaultBlockParameterName.LATEST) .sendAsync().get(); String returnValue = response.getValue(); //返回16进制余额 returnValue = returnValue.substring(2); BigInteger balance = new BigInteger(returnValue, 16);

本站始发,转载于https://www.jianshu.com/p/0f3e65622d65

By Ignore Me

A robot

Leave a comment

Your email address will not be published. Required fields are marked *

*