当前位置:   article > 正文

java使用web3J进行代币转账、余额查询_java 使用web3j查询地址余额

java 使用web3j查询地址余额
  1. <!-- io常用工具类 -->
  2. <dependency>
  3. <groupId>commons-io</groupId>
  4. <artifactId>commons-io</artifactId>
  5. <version>2.5</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.web3j</groupId>
  9. <artifactId>core</artifactId>
  10. <version>3.2.0</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.web3j</groupId>
  14. <artifactId>geth</artifactId>
  15. <version>3.2.0</version>
  16. </dependency>
  17. <!-- web3j -->
  18. <dependency>
  19. <groupId>org.web3j</groupId>
  20. <artifactId>web3j-spring-boot-starter</artifactId>
  21. <version>1.6.0</version>
  22. </dependency>
  1. public static void main(String[] args) {
  2. /*SpringApplication.run(LongApplication.class, args);
  3. System.out.printf("启动成功");*/
  4. // 转出地址
  5. String from = "0x9175F9EcBbddC078e40C5e037AD31F4abf36628a";
  6. //转入地址
  7. String to = "0xa7B049d3A19796B195B0e976ec43EB7a12f07Bf9";
  8. //转入数量
  9. String value = "5";
  10. //转出地址私钥
  11. String privateKey ="";
  12. //合约地址
  13. String contractAddress="0x57E0297510fA155eF165646c208C495E563B3342";
  14. //位数,根据合约里面的来
  15. int decimal=4;
  16. tokenDeal(from,to,value,privateKey,contractAddress,decimal);
  17. }
  18. public static String tokenDeal(String from, String to, String value, String privateKey, String contractAddress, int decimal) {
  19. Web3j web3j = Web3j.build(new HttpService("https://ropsten.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161"));
  20. try {
  21. //转账的凭证,需要传入私钥
  22. Credentials credentials = Credentials.create(privateKey);
  23. //获取交易笔数
  24. BigInteger nonce;
  25. EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(from, DefaultBlockParameterName.PENDING).send();
  26. if (ethGetTransactionCount == null) {
  27. return null;
  28. }
  29. nonce = ethGetTransactionCount.getTransactionCount();
  30. //手续费
  31. BigInteger gasPrice;
  32. EthGasPrice ethGasPrice = web3j.ethGasPrice().sendAsync().get();
  33. if (ethGasPrice == null) {
  34. return null;
  35. }
  36. gasPrice = ethGasPrice.getGasPrice();
  37. //注意手续费的设置,这块很容易遇到问题
  38. BigInteger gasLimit = BigInteger.valueOf(60000L);
  39. BigInteger val = new BigDecimal(value).multiply(new BigDecimal("10").pow(decimal)).toBigInteger();// 单位换算
  40. Function function = new Function(
  41. "transfer",
  42. Arrays.asList(new Address(to), new Uint256(val)),
  43. Collections.singletonList(new TypeReference<Type>() {
  44. }));
  45. //创建交易对象
  46. String encodedFunction = FunctionEncoder.encode(function);
  47. RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit,
  48. contractAddress, encodedFunction);
  49. //进行签名操作
  50. byte[] signMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
  51. String hexValue = Numeric.toHexString(signMessage);
  52. //发起交易
  53. EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
  54. String hash = ethSendTransaction.getTransactionHash();
  55. if (hash != null) {
  56. //执行业务
  57. System.out.printf("执行成功:"+hash);
  58. return hash;
  59. }
  60. } catch (Exception ex) {
  61. //报错应进行错误处理
  62. ex.printStackTrace();
  63. }
  64. return null;
  65. }

 查询余额

  1. public static void main(String[] args) {
  2. //查询的钱包地址
  3. String from = "0x9175F9EcBbddC078e40C5e037AD31F4abf36628a";
  4. //合约地址
  5. String contractAddress="0x57E0297510fA155eF165646c208C495E563B3342";
  6. //合约部署节点
  7. Web3j web3j = Web3j.build(new HttpService("https://ropsten.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161"));
  8. try {
  9. String code = getERC20Balance(web3j,from,contractAddress);
  10. System.out.printf("查询出来的余额:"+code);
  11. } catch (ExecutionException e) {
  12. e.printStackTrace();
  13. } catch (InterruptedException e) {
  14. e.printStackTrace();
  15. }
  16. }
  17. private static final BigDecimal WEI = new BigDecimal(10000);
  18. /**
  19. * 获取ERC-20 token指定地址余额
  20. *
  21. * @param address 查询地址
  22. * @param contractAddress 合约地址
  23. * @return
  24. * @throws ExecutionException
  25. * @throws InterruptedException
  26. */
  27. public static String getERC20Balance(Web3j web3j, String address, String contractAddress) throws ExecutionException, InterruptedException {
  28. String methodName = "balanceOf";
  29. List<Type> inputParameters = new ArrayList<>();
  30. List<TypeReference<?>> outputParameters = new ArrayList<>();
  31. Address fromAddress = new Address(address);
  32. inputParameters.add(fromAddress);
  33. TypeReference<Uint256> typeReference = new TypeReference<Uint256>() {
  34. };
  35. outputParameters.add(typeReference);
  36. Function function = new Function(methodName, inputParameters, outputParameters);
  37. String data = FunctionEncoder.encode(function);
  38. Transaction transaction = Transaction.createEthCallTransaction(address, contractAddress, data);
  39. EthCall ethCall;
  40. BigDecimal balanceValue = BigDecimal.ZERO;
  41. try {
  42. ethCall = web3j.ethCall(transaction, DefaultBlockParameterName.LATEST).send();
  43. List<Type> results = FunctionReturnDecoder.decode(ethCall.getValue(), function.getOutputParameters());
  44. Integer value = 0;
  45. if(results != null && results.size()>0){
  46. value = Integer.parseInt(String.valueOf(results.get(0).getValue()));
  47. }
  48. balanceValue = new BigDecimal(value).divide(WEI, 6, RoundingMode.HALF_DOWN);
  49. } catch (IOException e) {
  50. e.printStackTrace();
  51. }
  52. return balanceValue.toString();
  53. }

如果这篇文章在你一筹莫展的时候帮助到了你,可以请作者吃个棒棒糖

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/574665
推荐阅读
相关标签