当前位置:   article > 正文

【web3j】java通过web3j监听并解析合约中的事件(event/emit)_java web3j 上链数据

java web3j 上链数据

① 查询链上数据用的rpc(本示例是binance的,测试网可以使用:https://data-seed-prebsc-2-s2.binance.org:8545)

② 自己还要有一个测试链上部署好的合约,合约中要有一个方法emit了事件。

③ java依赖

  1. <dependency>
  2. <groupId>org.web3j</groupId>
  3. <artifactId>core</artifactId>
  4. <version>4.9.7</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.web3j</groupId>
  8. <artifactId>codegen</artifactId>
  9. <version>4.9.7</version>
  10. </dependency>

一、通过自己合约的abi和bin生成一个java文件,abi和bin可以在remix的compiler模块中获取,代码如下这一步懒得做的可以跳过,在第二步传合约地址的时候,直接传一个字符串也行。这里就是顺手存一下这个方法,其实实际使用也是直接传的字符串,具体可以看页面最下方的”三、“

  1. /**
  2. * 通过合约abi和bin获得java文件
  3. */
  4. public void getJavaFileBySolidity(){
  5. // 生成的java类名,同ABI文件同名,自动首字母大写
  6. String packageName = "";
  7. String outDirPath = "/Users/maomo/Desktop/";
  8. String binDirPath = "/Users/maomo/Desktop/xxxbin.txt";
  9. String abiDirPath = "/Users/maomo/Desktop/xxxabi.txt";
  10. String[] arr = Arrays.asList(
  11. "-b", binDirPath,
  12. "-a", abiDirPath,
  13. "-p", packageName,
  14. "-o", outDirPath
  15. ).toArray(new String[0]);
  16. SolidityFunctionWrapperGenerator.main(arr);
  17. }

二、通过web3j查询事件,通过eventethFilter增加过滤条件

  1. public void testSub() {
  2. Web3j web3j = Web3j.build(new HttpService("https://data-seed-prebsc-2-s2.binance.org:8545"));
  3. //第一步生成的合约实体
  4. Contract contract;
  5. Disposable subscribe = null;
  6. try {
  7. Web3ClientVersion web3ClientVersion = web3j.web3ClientVersion().send();
  8. String clientVersion = web3ClientVersion.getWeb3ClientVersion();
  9. log.info("wen3j subscribe --clientVersion-- :{} ", clientVersion);
  10. //设置谁调用合约
  11. TransactionManager transactionManager = new ClientTransactionManager(web3j, "这里可以输入自己的钱包地址");
  12. //加载智能合约(此处可以跳过,下面穿合约地址的地方 直接传字符串)
  13. contract = Contract.load("你要监听的合约地址", web3j, transactionManager, ManagedTransaction.GAS_PRICE, org.web3j.tx.Contract.GAS_LIMIT);
  14. //设置过滤条件 这个示例是监听最新的1000个块
  15. BigInteger blockNumber = web3j.ethBlockNumber().send().getBlockNumber()
  16. .subtract(new BigInteger("1000"));
  17. EthFilter ethFilter = new EthFilter(DefaultBlockParameter.valueOf(blockNumber),DefaultBlockParameterName.LATEST, contract.getContractAddress());
  18. //监听哪个事件,合约中的event写了几个参数,这里就写几个,类型对应好
  19. Event event = new Event("startEvent",
  20. Arrays.<TypeReference<?>>asList(
  21. new TypeReference<Address>(true) {},
  22. new TypeReference<Address>(true) {},
  23. new TypeReference<Uint256>(true) {},
  24. new TypeReference<Uint256>(false) {},
  25. new TypeReference<Uint256>(false) {},
  26. new TypeReference<Uint256>(false) {}));
  27. ethFilter.addSingleTopic(EventEncoder.encode(event));
  28. subscribe = web3j.ethLogFlowable(ethFilter).subscribe(tx -> {
  29. int newBlock = tx.getBlockNumber().intValue();
  30. log.info("wen3j subscribe --newBlock-- :{} ", newBlock);
  31. log.info("wen3j subscribe --tx-- :{} ", tx);
  32. EventValues eventValues = staticExtractEventParameters(event, tx);
  33. //定义接收参数(本示例使用的事件返回了6个,具体按自己合约来)
  34. String address1 = "";String address2 = "";int uint1 = 0;
  35. int uint2 = 0;int uint3 = 0;int uint4 = 0;
  36. List<Type> indexedValues = eventValues.getIndexedValues();
  37. if (ObjectUtils.isNotEmpty(indexedValues) && indexedValues.size() == 3) {
  38. Type type1 = indexedValues.get(0);
  39. address1 = type1.getValue().toString();
  40. Type type2 = indexedValues.get(1);
  41. address2 = type2.getValue().toString();
  42. Type type3 = indexedValues.get(2);
  43. uint1 = Integer.parseInt(type3.getValue().toString());
  44. }
  45. List<Type> nonIndexedValues = eventValues.getNonIndexedValues();
  46. if (ObjectUtils.isNotEmpty(nonIndexedValues) && nonIndexedValues.size() == 3) {
  47. Type type1 = nonIndexedValues.get(0);
  48. uint2 = Integer.parseInt(type1.getValue().toString());
  49. Type type2 = nonIndexedValues.get(1);
  50. uint3 = Integer.parseInt(type2.getValue().toString());
  51. Type type3 = nonIndexedValues.get(2);
  52. uint4 = Integer.parseInt(type3.getValue().toString());
  53. }
  54. log.info("address1:{};address2:{};uint1:{};uint2:{};uint3:{};uint4:{}",address1, address2, uint1, uint2, uint3, uint4);
  55. });
  56. }catch (Exception e) {
  57. e.printStackTrace();
  58. }finally {
  59. //关闭监听
  60. if(ObjectUtils.isNotEmpty(subscribe) && !subscribe.isDisposed()){
  61. subscribe.dispose();
  62. }
  63. }
  64. }
  1. /**
  2. * 解析log返回的data
  3. * @param event 合约中定义的事件
  4. * @param log 监听到的log
  5. * @return 解析后的数据
  6. */
  7. public EventValues staticExtractEventParameters(Event event, Log log) {
  8. final List<String> topics = log.getTopics();
  9. String encodedEventSignature = EventEncoder.encode(event);
  10. if (topics == null || topics.size() == 0 || !topics.get(0).equals(encodedEventSignature)) {
  11. return null;
  12. }
  13. List<Type> indexedValues = new ArrayList<>();
  14. List<Type> nonIndexedValues = FunctionReturnDecoder.decode(
  15. log.getData(), event.getNonIndexedParameters());
  16. List<TypeReference<Type>> indexedParameters = event.getIndexedParameters();
  17. for (int i = 0; i < indexedParameters.size(); i++) {
  18. Type value = FunctionReturnDecoder.decodeIndexedValue(
  19. topics.get(i + 1), indexedParameters.get(i));
  20. indexedValues.add(value);
  21. }
  22. return new EventValues(indexedValues, nonIndexedValues);
  23. }

三、为了方便以后复制粘贴(不是),最下面再传一个不生成合约的版本

  1. public void testSub() {
  2. Web3j web3j = Web3j.build(new HttpService("https://data-seed-prebsc-2-s2.binance.org:8545"));
  3. //第一步生成的合约实体
  4. Contract contract;
  5. Disposable subscribe = null;
  6. try {
  7. Web3ClientVersion web3ClientVersion = web3j.web3ClientVersion().send();
  8. String clientVersion = web3ClientVersion.getWeb3ClientVersion();
  9. log.info("wen3j subscribe --clientVersion-- :{} ", clientVersion);
  10. //设置过滤条件 这个示例是监听最新的1000个块
  11. BigInteger blockNumber = web3j.ethBlockNumber().send().getBlockNumber()
  12. .subtract(new BigInteger("1000"));
  13. EthFilter ethFilter = new EthFilter(DefaultBlockParameter.valueOf(blockNumber),DefaultBlockParameterName.LATEST, "输入合约地址");
  14. //监听哪个事件,合约中的event写了几个参数,这里就写几个,类型对应好
  15. Event event = new Event("startEvent",
  16. Arrays.<TypeReference<?>>asList(
  17. new TypeReference<Address>(true) {},
  18. new TypeReference<Address>(true) {},
  19. new TypeReference<Uint256>(true) {},
  20. new TypeReference<Uint256>(false) {},
  21. new TypeReference<Uint256>(false) {},
  22. new TypeReference<Uint256>(false) {}));
  23. ethFilter.addSingleTopic(EventEncoder.encode(event));
  24. subscribe = web3j.ethLogFlowable(ethFilter).subscribe(tx -> {
  25. int newBlock = tx.getBlockNumber().intValue();
  26. log.info("wen3j subscribe --newBlock-- :{} ", newBlock);
  27. log.info("wen3j subscribe --tx-- :{} ", tx);
  28. EventValues eventValues = staticExtractEventParameters(event, tx);
  29. //定义接收参数(本示例使用的事件返回了6个,具体按自己合约来)
  30. String address1 = "";String address2 = "";int uint1 = 0;
  31. int uint2 = 0;int uint3 = 0;int uint4 = 0;
  32. List<Type> indexedValues = eventValues.getIndexedValues();
  33. if (ObjectUtils.isNotEmpty(indexedValues) && indexedValues.size() == 3) {
  34. Type type1 = indexedValues.get(0);
  35. address1 = type1.getValue().toString();
  36. Type type2 = indexedValues.get(1);
  37. address2 = type2.getValue().toString();
  38. Type type3 = indexedValues.get(2);
  39. uint1 = Integer.parseInt(type3.getValue().toString());
  40. }
  41. List<Type> nonIndexedValues = eventValues.getNonIndexedValues();
  42. if (ObjectUtils.isNotEmpty(nonIndexedValues) && nonIndexedValues.size() == 3) {
  43. Type type1 = nonIndexedValues.get(0);
  44. uint2 = Integer.parseInt(type1.getValue().toString());
  45. Type type2 = nonIndexedValues.get(1);
  46. uint3 = Integer.parseInt(type2.getValue().toString());
  47. Type type3 = nonIndexedValues.get(2);
  48. uint4 = Integer.parseInt(type3.getValue().toString());
  49. }
  50. log.info("address1:{};address2:{};uint1:{};uint2:{};uint3:{};uint4:{}",address1, address2, uint1, uint2, uint3, uint4);
  51. });
  52. }catch (Exception e) {
  53. e.printStackTrace();
  54. }finally {
  55. //关闭监听
  56. if(ObjectUtils.isNotEmpty(subscribe) && !subscribe.isDisposed()){
  57. subscribe.dispose();
  58. }
  59. }
  60. }

=========================分割线=========================

还有一种把web3j.ethLogFlowable(ethFilter).subscribe换成查询的方法,做个记录

把这段代码

  1. subscribe = web3j.ethLogFlowable(ethFilter).subscribe(tx -> {
  2. //逻辑...
  3. }

换成

  1. List<EthLog.LogResult> resp = web3j.ethGetLogs(ethFilter).send().getLogs();
  2. for (EthLog.LogResult logItem : resp) {
  3. EthLog.LogObject tx = ObjectUtils.isNotEmpty(logItem.get()) ? (EthLog.LogObject) logItem.get() : null;
  4. if(ObjectUtils.isEmpty(tx)){
  5. return false;
  6. }
  7. //逻辑...
  8. }

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

闽ICP备14008679号