当前位置:   article > 正文

java web3j4.8.4版本的使用记录_org.web3j.protocol.core.methods.response.log canno

org.web3j.protocol.core.methods.response.log cannot be cast to org.web3j.pro

最近公司做NFT市场开发,特记录一下自己在使用web3j组件测试调用区块链合约的时使用的方法和踩过的坑,便于自己以后查看。

主要用到工具有4个

idea,谷歌浏览,小狐狸钱包(metamask)插件,remix在线智能合约平台

1、准备工作

1.1、java项目

 在pom.xml中添加引用仓库地址,添加web3j的引入

  1. <repositories>
  2. <repository>
  3. <id>jitpack.io</id>
  4. <url>https://jitpack.io</url>
  5. </repository>
  6. </repositories>
  7. <dependencies>
  8. <!--web3j-->
  9. <dependency>
  10. <groupId>org.web3j</groupId>
  11. <artifactId>core</artifactId>
  12. <version>4.8.4</version>
  13. <exclusions>
  14. <exclusion>
  15. <groupId>org.jetbrains.kotlin</groupId>
  16. <artifactId>kotlin-stdlib</artifactId>
  17. </exclusion>
  18. <exclusion>
  19. <groupId>com.squareup.okhttp3</groupId>
  20. <artifactId>okhttp</artifactId>
  21. </exclusion>
  22. </exclusions>
  23. </dependency>
  24. </dependencies>

1.2、智能合约

        开始前,必须有一个用于测试的区块链智能合约,进入以太坊官网提供的在线平台,地址为:https://remix.ethereum.org/,编写测试合约。

        编写完成,编译测试无误后,部署合约,方法选择如下

        因为选择通过web3的方式来发布合约,所以同步会要求登录小狐狸(MetaMask),我这里事先就已经添加好了币安测试链,如果各位没有添加的话,自己自行添加哈

1.3 合约转化

         合约发布成功后,测试一下合约内的方法是否可以正常使用,一切OK了以后,在remix中的编译模块内,将abi和bin保存放入本地文件中用于生成java文件。

说明一下哦,在生成java文件时,本地要有web3j的资源文件,我事先已经做好了准备工作了,如果你们没有的话,就自己查下哈。

进入cmd命令窗口

命令如下

web3j solidity generate --abiFile=abi文件地址 -o 文件生成地址 -p 文件包名

 

 以下是我的合约生成的java文件

  1. package com.XX.XXX.contracts.constants;
  2. import io.reactivex.Flowable;
  3. import io.reactivex.functions.Function;
  4. import java.math.BigInteger;
  5. import java.util.ArrayList;
  6. import java.util.Arrays;
  7. import java.util.Collections;
  8. import java.util.List;
  9. import org.web3j.abi.EventEncoder;
  10. import org.web3j.abi.TypeReference;
  11. import org.web3j.abi.datatypes.Address;
  12. import org.web3j.abi.datatypes.Event;
  13. import org.web3j.abi.datatypes.Type;
  14. import org.web3j.abi.datatypes.Utf8String;
  15. import org.web3j.abi.datatypes.generated.Uint256;
  16. import org.web3j.crypto.Credentials;
  17. import org.web3j.protocol.Web3j;
  18. import org.web3j.protocol.core.DefaultBlockParameter;
  19. import org.web3j.protocol.core.RemoteFunctionCall;
  20. import org.web3j.protocol.core.methods.request.EthFilter;
  21. import org.web3j.protocol.core.methods.response.BaseEventResponse;
  22. import org.web3j.protocol.core.methods.response.Log;
  23. import org.web3j.protocol.core.methods.response.TransactionReceipt;
  24. import org.web3j.tx.Contract;
  25. import org.web3j.tx.TransactionManager;
  26. import org.web3j.tx.gas.ContractGasProvider;
  27. /**
  28. * <p>Auto generated code.
  29. * <p><strong>Do not modify!</strong>
  30. * <p>Please use the <a href="https://docs.web3j.io/command_line.html">web3j command line tools</a>,
  31. * or the org.web3j.codegen.SolidityFunctionWrapperGenerator in the
  32. * <a href="https://github.com/web3j/web3j/tree/master/codegen">codegen module</a> to update.
  33. *
  34. * <p>Generated with web3j version 4.5.5.
  35. */
  36. @SuppressWarnings("rawtypes")
  37. public class EventTest extends Contract {
  38. private static final String BINARY = "Bin file was not provided";
  39. public static final String FUNC_CHANGENAME = "changeName";
  40. public static final String FUNC_COUNTS = "counts";
  41. public static final String FUNC_INCREMENT = "increment";
  42. public static final String FUNC_NAME = "name";
  43. public static final Event INCREMENT_EVENT = new Event("Increment",
  44. Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>(true) {}, new TypeReference<Address>() {}));
  45. ;
  46. public static final Event CHANGENAMEEVENT_EVENT = new Event("changeNameEvent",
  47. Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {}, new TypeReference<Address>() {}));
  48. ;
  49. @Deprecated
  50. protected EventTest(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
  51. super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit);
  52. }
  53. protected EventTest(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) {
  54. super(BINARY, contractAddress, web3j, credentials, contractGasProvider);
  55. }
  56. @Deprecated
  57. protected EventTest(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
  58. super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit);
  59. }
  60. protected EventTest(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) {
  61. super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider);
  62. }
  63. public List<IncrementEventResponse> getIncrementEvents(TransactionReceipt transactionReceipt) {
  64. List<Contract.EventValuesWithLog> valueList = extractEventParametersWithLog(INCREMENT_EVENT, transactionReceipt);
  65. ArrayList<IncrementEventResponse> responses = new ArrayList<IncrementEventResponse>(valueList.size());
  66. for (Contract.EventValuesWithLog eventValues : valueList) {
  67. IncrementEventResponse typedResponse = new IncrementEventResponse();
  68. typedResponse.log = eventValues.getLog();
  69. typedResponse.which = (BigInteger) eventValues.getIndexedValues().get(0).getValue();
  70. typedResponse.who = (String) eventValues.getNonIndexedValues().get(0).getValue();
  71. responses.add(typedResponse);
  72. }
  73. return responses;
  74. }
  75. public Flowable<IncrementEventResponse> incrementEventFlowable(EthFilter filter) {
  76. return web3j.ethLogFlowable(filter).map(new Function<Log, IncrementEventResponse>() {
  77. @Override
  78. public IncrementEventResponse apply(Log log) {
  79. Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(INCREMENT_EVENT, log);
  80. IncrementEventResponse typedResponse = new IncrementEventResponse();
  81. typedResponse.log = log;
  82. typedResponse.which = (BigInteger) eventValues.getIndexedValues().get(0).getValue();
  83. typedResponse.who = (String) eventValues.getNonIndexedValues().get(0).getValue();
  84. return typedResponse;
  85. }
  86. });
  87. }
  88. public Flowable<IncrementEventResponse> incrementEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {
  89. EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());
  90. filter.addSingleTopic(EventEncoder.encode(INCREMENT_EVENT));
  91. return incrementEventFlowable(filter);
  92. }
  93. public List<ChangeNameEventEventResponse> getChangeNameEventEvents(TransactionReceipt transactionReceipt) {
  94. List<Contract.EventValuesWithLog> valueList = extractEventParametersWithLog(CHANGENAMEEVENT_EVENT, transactionReceipt);
  95. ArrayList<ChangeNameEventEventResponse> responses = new ArrayList<ChangeNameEventEventResponse>(valueList.size());
  96. for (Contract.EventValuesWithLog eventValues : valueList) {
  97. ChangeNameEventEventResponse typedResponse = new ChangeNameEventEventResponse();
  98. typedResponse.log = eventValues.getLog();
  99. typedResponse.str = (String) eventValues.getNonIndexedValues().get(0).getValue();
  100. typedResponse.who = (String) eventValues.getNonIndexedValues().get(1).getValue();
  101. responses.add(typedResponse);
  102. }
  103. return responses;
  104. }
  105. public Flowable<ChangeNameEventEventResponse> changeNameEventEventFlowable(EthFilter filter) {
  106. return web3j.ethLogFlowable(filter).map(new Function<Log, ChangeNameEventEventResponse>() {
  107. @Override
  108. public ChangeNameEventEventResponse apply(Log log) {
  109. Contract.EventValuesWithLog eventValues = extractEventParametersWithLog(CHANGENAMEEVENT_EVENT, log);
  110. ChangeNameEventEventResponse typedResponse = new ChangeNameEventEventResponse();
  111. typedResponse.log = log;
  112. typedResponse.str = (String) eventValues.getNonIndexedValues().get(0).getValue();
  113. typedResponse.who = (String) eventValues.getNonIndexedValues().get(1).getValue();
  114. return typedResponse;
  115. }
  116. });
  117. }
  118. public Flowable<ChangeNameEventEventResponse> changeNameEventEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {
  119. EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());
  120. filter.addSingleTopic(EventEncoder.encode(CHANGENAMEEVENT_EVENT));
  121. return changeNameEventEventFlowable(filter);
  122. }
  123. public RemoteFunctionCall<TransactionReceipt> changeName(String str) {
  124. final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(
  125. FUNC_CHANGENAME,
  126. Arrays.<Type>asList(new org.web3j.abi.datatypes.Utf8String(str)),
  127. Collections.<TypeReference<?>>emptyList());
  128. return executeRemoteCallTransaction(function);
  129. }
  130. public RemoteFunctionCall<TransactionReceipt> counts(BigInteger param0) {
  131. final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(
  132. FUNC_COUNTS,
  133. Arrays.<Type>asList(new org.web3j.abi.datatypes.generated.Uint256(param0)),
  134. Collections.<TypeReference<?>>emptyList());
  135. return executeRemoteCallTransaction(function);
  136. }
  137. public RemoteFunctionCall<TransactionReceipt> increment(BigInteger which) {
  138. final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(
  139. FUNC_INCREMENT,
  140. Arrays.<Type>asList(new org.web3j.abi.datatypes.generated.Uint256(which)),
  141. Collections.<TypeReference<?>>emptyList());
  142. return executeRemoteCallTransaction(function);
  143. }
  144. public RemoteFunctionCall<TransactionReceipt> name() {
  145. final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(
  146. FUNC_NAME,
  147. Arrays.<Type>asList(),
  148. Collections.<TypeReference<?>>emptyList());
  149. return executeRemoteCallTransaction(function);
  150. }
  151. @Deprecated
  152. public static EventTest load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {
  153. return new EventTest(contractAddress, web3j, credentials, gasPrice, gasLimit);
  154. }
  155. @Deprecated
  156. public static EventTest load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {
  157. return new EventTest(contractAddress, web3j, transactionManager, gasPrice, gasLimit);
  158. }
  159. public static EventTest load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) {
  160. return new EventTest(contractAddress, web3j, credentials, contractGasProvider);
  161. }
  162. public static EventTest load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) {
  163. return new EventTest(contractAddress, web3j, transactionManager, contractGasProvider);
  164. }
  165. public static class IncrementEventResponse extends BaseEventResponse {
  166. public BigInteger which;
  167. public String who;
  168. }
  169. public static class ChangeNameEventEventResponse extends BaseEventResponse {
  170. public String str;
  171. public String who;
  172. }
  173. }

 2、测试合约方法的调用和合约事件监听

   说明:

        web3j通过rpc的方式建立连接,连接方式我测试时,用了两种方式,一种是http的方式调用合约的方法,websocket的方式调用的事件监听,两种方式测试都是OK的

  1. package com.xx.xxx.contracts.util;
  2. import com.nft.service.contracts.constants.ContractConstants;
  3. import com.nft.service.contracts.constants.EventTest;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.web3j.abi.EventValues;
  7. import org.web3j.abi.datatypes.Type;
  8. import org.web3j.crypto.Credentials;
  9. import org.web3j.protocol.Web3j;
  10. import org.web3j.protocol.core.DefaultBlockParameterName;
  11. import org.web3j.protocol.core.RemoteFunctionCall;
  12. import org.web3j.protocol.core.methods.request.Transaction;
  13. import org.web3j.protocol.core.methods.response.EthEstimateGas;
  14. import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
  15. import org.web3j.protocol.core.methods.response.Log;
  16. import org.web3j.protocol.core.methods.response.TransactionReceipt;
  17. import org.web3j.protocol.http.HttpService;
  18. import org.web3j.protocol.websocket.WebSocketService;
  19. import org.web3j.tx.Contract;
  20. import org.web3j.tx.ReadonlyTransactionManager;
  21. import org.web3j.tx.TransactionManager;
  22. import org.web3j.tx.gas.DefaultGasProvider;
  23. import java.io.IOException;
  24. import java.math.BigInteger;
  25. import java.net.ConnectException;
  26. import java.util.concurrent.ExecutionException;
  27. /**
  28. * @author viowio
  29. * @version v1.0
  30. * @date 17:52 2022/4/9
  31. * @description ERC20工具类
  32. */
  33. public class TestUtil {
  34. private static Web3j web3j = Web3j.build(new HttpService("https://data-seed-prebsc-2-s1.binance.org:8545/"));
  35. private static final Logger logger = LoggerFactory.getLogger(TestUtil.class);
  36. public static void changeName(){
  37. String token = "合约地址";
  38. try {
  39. Credentials credentials = Credentials.create("换成自己的测试钱包地址私钥");
  40. BigInteger currentGasPrice = web3j.ethGasPrice().sendAsync().get().getGasPrice();
  41. EventTest eventTest = EventTest.load(token, web3j, credentials, new DefaultGasProvider() {
  42. /**
  43. * 使用动态获取的 Gas Price
  44. * @return
  45. */
  46. @Override
  47. public BigInteger getGasPrice() {
  48. return currentGasPrice;
  49. }
  50. });
  51. RemoteFunctionCall<TransactionReceipt> changeNames = eventTest.changeName("0x7503D2667a3Af2a5f5268B9628F7Bb0A3E6282B4");
  52. TransactionReceipt transactionReceipt = changeNames.sendAsync().get();
  53. String transactionHash = transactionReceipt.getTransactionHash();
  54. logger.info("changeName hash: {}",transactionHash);
  55. }catch (ExecutionException | InterruptedException ex){
  56. logger.info(ex.getMessage());
  57. } catch (Exception e) {
  58. e.printStackTrace();
  59. }
  60. }
  61. public static void changeNameEvent() throws ConnectException {
  62. String token = "合约地址";
  63. String wsurl = ContractConstants.WEBSOCKET_RPC;
  64. //实例化websocket
  65. WebSocketService webSocketService = new WebSocketService(wsurl,true);
  66. //建立连接
  67. webSocketService.connect();
  68. //实例化web3j
  69. Web3j client = Web3j.build(webSocketService);
  70. TransactionManager transactionManager = new ReadonlyTransactionManager(web3j, token);
  71. try {
  72. //方式一
  73. /* client.ethLogFlowable(
  74. new EthFilter(
  75. DefaultBlockParameterName.EARLIEST,
  76. DefaultBlockParameterName.LATEST,
  77. // 合约地址
  78. token
  79. )
  80. ).subscribe(event -> {
  81. System.out.println(event);
  82. // => Log{removed=false, logIndex='0x39', transactionIndex='0x13', transactionHash='0x9c3653c27946cb39c3a256229634cfedbca54f146a740f46b661b986590f8358', blockHash='0x1e674b9d111601519f977b75f9a1865ba359b474550ff5d0d87daec1f543d64d', blockNumber='0xb83ccd', address='0x7b52aae43e962ce6a9a1b7e79f549582ae8bcff9', data='0x', type='null', topics=[0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x0000000000000000000000000000000000000000000000000000000000000000, 0x0000000000000000000000006ab3d0bd875f8667026d2a9bb3060ec44380bcc2, 0x0000000000000000000000000000000000000000000000000000000000000017]}
  83. }, Throwable::printStackTrace);*/
  84. //方式二
  85. /*Credentials credentials = Credentials.create("换成自己的测试钱包地址私钥");
  86. BigInteger currentGasPrice = web3j.ethGasPrice().sendAsync().get().getGasPrice();
  87. EventTest eventTest = EventTest.load(token, web3j, credentials, new DefaultGasProvider() {
  88. *//**
  89. * 使用动态获取的 Gas Price
  90. * @return
  91. *//*
  92. @Override
  93. public BigInteger getGasPrice() {
  94. return currentGasPrice;
  95. }
  96. });
  97. eventTest
  98. .changeNameEventEventFlowable(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST)
  99. .subscribe(event -> {
  100. Log log = event.log;
  101. EventValues eventValues = Contract.staticExtractEventParameters(EventTest.CHANGENAMEEVENT_EVENT, log);
  102. for (Type nonIndexedValue : eventValues.getNonIndexedValues()) {
  103. System.out.println(nonIndexedValue.getValue());
  104. }
  105. });*/
  106. //方式3
  107. Credentials credentials = Credentials.create("换成自己的测试钱包地址私钥");
  108. BigInteger currentGasPrice = client.ethGasPrice().sendAsync().get().getGasPrice();
  109. EventTest eventTest = EventTest.load(token, client, credentials, new DefaultGasProvider() {
  110. /**
  111. * 使用动态获取的 Gas Price
  112. * @return
  113. */
  114. @Override
  115. public BigInteger getGasPrice() {
  116. return currentGasPrice;
  117. }
  118. });
  119. eventTest
  120. .changeNameEventEventFlowable(DefaultBlockParameterName.EARLIEST, DefaultBlockParameterName.LATEST)
  121. .subscribe(event -> {
  122. Log log = event.log;
  123. logger.info("transactionHash: {}",log.getTransactionHash());
  124. //解析时间返回的参数
  125. EventValues eventValues = Contract.staticExtractEventParameters(EventTest.CHANGENAMEEVENT_EVENT, log);
  126. for (Type nonIndexedValue : eventValues.getNonIndexedValues()) {
  127. System.out.println(nonIndexedValue.getValue());
  128. }
  129. });
  130. }catch (Exception e) {
  131. e.printStackTrace();
  132. }
  133. }
  134. }

事件测试结果

  1. 16:32:05.978 [restartedMain] INFO c.n.s.c.u.TestUtil - [lambda$changeNameEvent$0,146] - transactionHash: 0xd4fac21ba08d7496d8025281c37e932b914ea3bb9dce48e73bd3c08ac934fdd3
  2. test
  3. 0x5ae241178c67689ead468bf5170b3105011a5766
  4. 16:32:05.979 [restartedMain] INFO c.n.s.c.u.TestUtil - [lambda$changeNameEvent$0,146] - transactionHash: 0x42aff4ead062feb340a2fa68c73b5024a0d58029287a2f0acc62156c60780d97
  5. test
  6. 0x5ae241178c67689ead468bf5170b3105011a5766
  7. 16:32:05.980 [restartedMain] INFO c.n.s.c.u.TestUtil - [lambda$changeNameEvent$0,146] - transactionHash: 0x1050583b9e907378fb61289ab5b373f195f4d332c5fd7d273e2c817554c90f7b
  8. 123
  9. 0x5ae241178c67689ead468bf5170b3105011a5766
  10. 16:32:05.980 [restartedMain] INFO c.n.s.c.u.TestUtil - [lambda$changeNameEvent$0,146] - transactionHash: 0xc86374d895f83bfef380a9a1f4cc5a15ddfcc78090305cff5e4367460d423af4
  11. 1237
  12. 0x5ae241178c67689ead468bf5170b3105011a5766
  13. 16:32:05.981 [restartedMain] INFO c.n.s.c.u.TestUtil - [lambda$changeNameEvent$0,146] - transactionHash: 0xf76fbd23e603109752215c5455e3920a08583de8728c2a42699f61aa45959d29
  14. 12374
  15. 0x5ae241178c67689ead468bf5170b3105011a5766
  16. 16:32:05.981 [restartedMain] INFO c.n.s.c.u.TestUtil - [lambda$changeNameEvent$0,146] - transactionHash: 0x0d751916f7ae66162959138c0a700feb136153fabee8d8b25a10e410fe74f904
  17. 1237455
  18. 0x5ae241178c67689ead468bf5170b3105011a5766
  19. 16:32:05.981 [restartedMain] INFO c.n.s.c.u.TestUtil - [lambda$changeNameEvent$0,146] - transactionHash: 0xe03249489b93e287e9d033f547c2a36a741c7b3ae49e5c95542315816f4af572
  20. 12374556
  21. 0x5ae241178c67689ead468bf5170b3105011a5766

OK,暂时完事了。

最后补充一下

如果没有的rpc地址的,可以搜一下,也可以使用我上面的那个地址,不过仅限于测试用哦。

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

闽ICP备14008679号