Java地带 - Web3
type: channel
link: https://blog.apires.cn/tag/Web3/
items: 以太坊Web3J开发常用代码片段整理

以太坊Web3J开发常用代码片段整理
type: item
date: 2024-02-22T23:39:00+08:00
description: 获取账户的Noncepublic static BigInteger getNonce(Web3j web3j, String addr) { try { EthGetTransactionCount getNonce = web3j.ethGetTransactionCount(addr,DefaultBlockParameterName.PENDING).send(); if (getNonce == null){ throw new RuntimeException("net error"); } return getNonce.getTransactionCount(); } catch (IOException e) { throw new RuntimeException("net error"); } }获取ETH余额public static BigDecimal getBalance(Web3j web3j, String address) { try { EthGetBalance ethGetBalance = web3j.ethGetBalance(address, DefaultBlockParameterName.LATEST).send(); return Convert.fromWei(new BigDecimal(ethGetBalance.getBalance()),Convert.Unit.ETHER); } catch (IOException e) { e.printStackTrace(); return null; } }获取代币余额 方法一public static BigInteger getTokenBalance(Web3j web3j, String fromAddress, String contractAddress) { String methodName = "balanceOf"; List<Type> inputParameters = new ArrayList<>(); List<TypeReference<?>> outputParameters = new ArrayList<>(); Address address = new Address(fromAddress); inputParameters.add(address); TypeReference<Uint256> typeReference = new TypeReference<Uint256>() { }; outputParameters.add(typeReference); Function function = new Function(methodName, inputParameters, outputParameters); String data = FunctionEncoder.encode(function); Transaction transaction = Transaction.createEthCallTransaction(fromAddress, contractAddress, data); EthCall ethCall; BigInteger balanceValue = BigInteger.ZERO; try { ethCall = web3j.ethCall(transaction, DefaultBlockParameterName.LATEST).send(); List<Type> results = FunctionReturnDecoder.decode(ethCall.getValue(), function.getOutputParameters()); balanceValue = (BigInteger) results.get(0).getValue(); } catch (IOException e) { e.printStackTrace(); } return balanceValue; }获取代币余额 方法二 (仅支持主链上的代币)String tokenBanceUrl = "https://api.etherscan.io/api?module=account&action=tokenbalance" + "&contractaddress=0x5aA8D6dE8CBf23DAC734E6f904B93bD056B15b81"//Token合约地址 + "&address=0xd4279e30e27f52ca60fac3cc9670c7b9b1eeefdc"//要查询额的账户余地址 + "&tag=late…