1.查询ETH钱包余额:
private static final String URL = “http://127.0.0.1:8545/”;
Web3j web3 = Web3j.build(new HttpService(URL));
EthGetBalance ethGetBalance = null;
try {
// 通过账户地址查询余额
ethGetBalance = web3j
.ethGetBalance(“0xac***f0261bc4b0*0d5e23d9f80d24bf89fe”, DefaultBlockParameterName.LATEST)
.sendAsync()
.get();
} catch (Exception e) {
throw new Exception(“查询钱包余额失败”);
}
1eth = 10e18 wei
单位转换:
BigDecimal banlance = Convert.fromWei(ethGetBalance.getBalance().toString(), Convert.Unit.ETHER);
- 通过钱包密码和助记词找回私钥公钥
通过密码与助记词获得钱包地址、公钥及私钥信息
Credentials credentials = WalletUtils.loadBip39Credentials(walletPwd, memorizingWords);
//公钥16进制字符串表示
String publicKey = credentials.getEcKeyPair().getPublicKey().toString(16);
//私钥16进制字符串表示
String privateKey = credentials.getEcKeyPair().getPrivateKey().toString(16);
3.获得当前区块高度
Web3j web3j = EthUtil.getConnection();
Request<?, EthBlockNumber> request = web3j.ethBlockNumber();
4.解锁账户,发送交易前需要对账户进行解锁
/**
* 通过http连接到geth节点
*
* @return
*/
private static HttpService getService() {
return new HttpService(URL);
}
public static Admin initAdmin() {
return Admin.build(getService());
}
Admin admin = EthUtil.initAdmin();
Request<?, PersonalUnlockAccount> request = admin.personalUnlockAccount(address, password, duration);
PersonalUnlockAccount account = request.send();
5.查询区块内容
Web3j web3j = EthUtil.getConnection();
DefaultBlockParameter defaultBlockParameter = new DefaultBlockParameterNumber(blockNumber);
Request<?, EthBlock> request = web3j.ethGetBlockByNumber(defaultBlockParameter, true);
EthBlock ethBlock = request.send();
本文介绍如何利用Java的web3j库查询ETH钱包余额,进行单位转换,找回私钥公钥,获取区块高度,以及解锁账户并查询区块内容。详细步骤包括:通过HttpService连接节点,使用ethGetBalance查询余额,使用WalletUtils从助记词恢复密钥,调用ethBlockNumber获取区块高度,使用personalUnlockAccount解锁账户,最后通过ethGetBlockByNumber查询指定区块详情。

246

被折叠的 条评论
为什么被折叠?



