java wrapper怎么运行_如何从智能合约中生成Java Wrapper

在本文中,我们将了解如何直接从智能合约生成Java Wrapper类以与Java中的智能合约进行交互。

从智能合约生成Java Wrapper类有不同的方法:

1. Web3j命令行工具和solc

2. Web3j命令行工具和Truffle构建生成的工件

3. web3j-maven-plugin

4. web3j-gradle-plugin

为了演示如何使用上述方法,本教程使用以下智能合约将文档公证到以太坊区块链上的注册表中。

DocumentRegistry.sol

pragma solidity ^0.5.6;

/**

* @dev Smart Contract responsible to notarize documents on the Ethereum Blockchain

*/

contract DocumentRegistry {

struct Document {

address signer; // Notary

uint date; // Date of notarization

bytes32 hash; // Document Hash

}

/**

* @dev Storage space used to record all documents notarized with metadata

*/

mapping(bytes32 =》 Document) registry;

/**

* @dev Notarize a document identified by its 32 bytes hash by recording the hash, the sender and date in the registry

* @dev Emit an event Notarized in case of success

* @param _documentHash Document hash

*/

funcTIon notarizeDocument(bytes32 _documentHash) external returns (bool) {

registry[_documentHash].signer = msg.sender;

registry[_documentHash].date = now;

registry[_documentHash].hash = _documentHash;

emit Notarized(msg.sender, _documentHash);

return true;

}

/**

* @dev Verify a document idenTIfied by its hash was noterized in the registry.

* @param _documentHash Document hash

* @return bool if document was noterized previsouly in the registry

*/

funcTIon isNotarized(bytes32 _documentHash) external view returns (bool) {

return registry[_documentHash].hash == _documentHash;

}

/**

* @dev DefiniTIon of the event triggered when a document is successfully notarized in the registry

*/

event Notarized(address indexed _signer, bytes32 _documentHash);

}

web3j命令行工具和solc

第一种方法使用solc生成Smart合约ABI和bytecode,并将这两个文件作为输入提供给web3j-cli以生成Wrapper。

1、安装solc并验证版本

安装solc并运行以下命令以确保solc版本大于或等于0.5.6(智能合约中指定的版本)。

$ solc --version

solc, the solidity compiler commandline interface

Version: 0.5.9+commit.c68bc34e.Linux.g++

2、安装Web3J CLI

要安装web3j cli,请从项目存储库的“发布”页面的“下载”部分下下载zipfile/tarball,或通过homebrew为MacOS用户或通过aur为Arch Linux用户下载zipfile/tarball。

brew tap web3j/web3j

brew install web3j

web3j

要通过zipfile运行,解压缩并运行二进制文件,您可能还需要将二进制文件添加到PATH中:

$ unzip web3j-4.3.0.zip

creating: web3j-4.3.0/lib/

inflating: web3j-4.3.0/lib/core-1.0.2-all.jar

creating: web3j-4.3.0/bin/

inflating: web3j-4.3.0/bin/web3j

inflating: web3j-4.3.0/bin/web3j.bat

$ 。/web3j-《version》/bin/web3j

_ _____ _ _

| | |____ (_) (_)

__ _____| |__ / /_ _ ___

\ \ /\ / / _ \ ‘_ \ \ \ | | | / _ \

\ V V / __/ |_) |.___/ / | _ | || (_) |

\_/\_/ \___|_.__/ \____/| |(_)|_| \___/

_/ |

|__/

Usage: web3j version|wallet|solidity 。..

3、使用solc编译智能合约

给定我们的Solidity文件DocumentRegistry.sol,solc 《sol》 --bin --abi --optimize -o 《output》命令编译智能合约并在同一目录中生成两个新文件:

$ solc DocumentRegistry.sol --bin --abi --optimize -o 。/

Compiler run successful. Artifact(s) can be found in directory 。/.

$ ls -l

total 12

-rw-rw-r-- 1 gjeanmart gjeanmart 565 Jun 24 13:42 DocumentRegistry.abi

-rw-rw-r-- 1 gjeanmart gjeanmart 676 Jun 24 13:42 DocumentRegistry.bin

-rw-rw-r-- 1 gjeanmart gjeanmart 1488 Jun 24 13:40 DocumentRegistry.sol

DocumentRegistry.bin:二进制文件,智能合约的字节码

DocumentRegistry.abi:智能合约的ABI(应用程序二进制接口),它以JSON格式定义接口。

4、使用web3j-cli生成包装器

使用ABI和bytecode(在步骤3中生成)和web3j-cli(在步骤2中安装),我们现在可以使用以下命令生成我们的智能合约的Java Wrapper:

web3j solidity generate -a=《abiFile》 -b=《binFile》 -o=《destinationFileDir》 -p=《packageName》

示例:

$ web3j solidity generate -a DocumentRegistry.abi

-b DocumentRegistry.bin -o 。

-p me.gjeanmart.tutorials.javaethereum.wrapper

_ _____ _ _

| | |____ (_) (_)

__ _____| |__ / /_ _ ___

\ \ /\ / / _ \ ’_ \ \ \ | | | / _ \

\ V V / __/ |_) |.___/ / | _ | || (_) |

\_/\_/ \___|_.__/ \____/| |(_)|_| \___/

_/ |

|__/

Generating me.gjeanmart.tutorials.javaethereum.wrapper.DocumentRegistry 。.. File written to 。

因此,您应该看到生成到文件夹/.java中的Java Wrapper文件,您可以将其复制到项目的src / main / java /文件夹中。

。/me/gjeanmart/tutorials/javaethereum/wrapper/DocumentRegistry.java

Web3j命令行工具和Truffle artefacts

Truffle是最著名的框架之一,可帮助您使用以太坊开发、测试和部署。 我们可以使用Truffle使用Web3j命令行工具生成的artefacts来创建wrapper类。

1、安装Truffle

Truffle可作为npm wrapper提供。

$ npm install truffle -g

- Fetching solc version list from solc-bin. Attempt #1

+ truffle@5.0.24

added 27 packages from 439 contributors in 11.636s

$ truffle version

Truffle v5.0.24 (core: 5.0.24)

Solidity v0.5.0 (solc-js)

Node v10.15.3

Web3.js v1.0.0-beta.37

2、初始化新的Truffle项目

要初始化Truffle项目,请在新文件夹中使用truffle init命令。该命令创建文件夹contract /,migration /和test /,以及文件truffle-config.js。

$ mkdir truffle

$ cd truffle

$ truffle init

? Preparing to download

? Downloading

? Cleaning up temporary files

? Setting up box

Unbox successful. Sweet!

Commands:

Compile: truffle compile

Migrate: truffle migrate

Test contracts: truffle test

$ ls -l

total 20

drwxrwxr-x 2 gjeanmart gjeanmart 4096 Jun 24 14:25 contracts

drwxrwxr-x 2 gjeanmart gjeanmart 4096 Jun 24 14:25 migrations

drwxrwxr-x 2 gjeanmart gjeanmart 4096 Jun 24 14:25 test

-rw-rw-r-- 1 gjeanmart gjeanmart 4233 Jun 24 14:25 truffle-config.js

3、将合同添加到文件夹合约中

将智能合约源documentregistry.sol复制到文件夹contracts中。

4、编译合约

使用命令truffle compile编译智能合约,此命令生成一个新的文件夹build/contracts/,其中包含每个编译的智能合约的truffle artefact。

$ truffle compile

Compiling your contracts.。.

===========================

》 Compiling 。/contracts/DocumentRegistry.sol

》 Compiling 。/contracts/Migrations.sol

》 Artifacts written to /home/gjeanmart/workspace/tutorials/java-ethereum-wrapper/truffle/build/contracts

》 Compiled successfully using:

- solc: 0.5.8+commit.23d335f2.Emscripten.clang

$ ls -l build/contracts/

total 136

-rw-rw-r-- 1 gjeanmart gjeanmart 79721 Jun 24 14:33 DocumentRegistry.json

-rw-rw-r-- 1 gjeanmart gjeanmart 54043 Jun 24 14:33 Migrations.json

5、从Truffle Artefact生成智能合约Java Wrapper

最后,web3j-cli提供了一种方法,可以使用以下命令直接从truffle编译的Truffle artefact结果生成Wrapper:

$ web3j truffle generate 。/build/contracts/DocumentRegistry.json -o 。 -p me.gjeanmart.tutorials.javaethereum.wrapper

_ _____ _ _

| | |____ (_) (_)

__ _____| |__ / /_ _ ___

\ \ /\ / / _ \ ‘_ \ \ \ | | | / _ \

\ V V / __/ |_) |.___/ / | _ | || (_) |

\_/\_/ \___|_.__/ \____/| |(_)|_| \___/

_/ |

|__/

Generating me.gjeanmart.tutorials.javaethereum.wrapper.DocumentRegistry 。.. File written to 。

因此,您应该看到生成到《packagefolders》 /。java_文件夹中的Java Wrapper文件,您可以将其复制到项目的src / main / java /文件夹中。

。/me/gjeanmart/tutorials/javaethereum/wrapper/DocumentRegistry.java

注意:使用Truffle,您可以做的比本文中显示的更多,例如部署脚本(迁移)、多网络配置、测试、调试。

web3j-maven-plugin

下一个解决方案比前两个解决方案更优雅,因为我们不必安装webj-cli并将文件复制到源文件夹。我们可以使用Maven和web3j-maven-plugin直接在Java项目中使用此方法。以下步骤假定您已创建Maven项目。

1、先决条件

安装solc并运行以下命令以确保solc版本大于或等于0.5.6(智能合约中指定的版本)。

$ solc --version

solc, the solidity compiler commandline interface

Version: 0.5.9+commit.c68bc34e.Linux.g++

2、将智能合约复制到文件夹src / main / resources中

将Smart Contract源DocumentRegistry.sol复制到Maven项目的src / main / resources文件夹中。

3、配置Maven以在generate-sources阶段生成Wrapper

在此步骤中,我们配置两个Maven插件:

web3j - Maven的插件

第一个插件与前两个方法相同,但与Maven集成。首先,我们将插件配置为在进入项目的generate-sources阶段时自动执行。

其次我们配置插件参数:

· packageName:要应用于生成的Wrapper类的包名称

· sourceDestination:目标文件夹,用于移动生成的Wrapper类

· soliditySourceFiles:在何处查找Smart Contract源文件

建立辅助性Maven的插件

第二个插件将sourceDestination文件夹添加到类路径中,以便我们可以导入生成的Wrapper类

pom.xml

《build》

《plugins》

《plugin》

《groupId》org.web3j《/groupId》

《artifactId》web3j-maven-plugin《/artifactId》

《version》4.2.0《/version》

《executions》

《execution》

《id》generate-sources-web3j《/id》

《phase》generate-sources《/phase》

《goals》

《goal》generate-sources《/goal》

《/goals》

《configuration》

《packageName》me.gjeanmart.tutorials.javaethereum.contracts.generated《/packageName》

《sourceDestination》${basedir}/target/generated-sources/contracts《/sourceDestination》

《soliditySourceFiles》

《directory》${basedir}/src/main/resources《/directory》

《includes》

《include》**/*.sol《/include》

《/includes》

《/soliditySourceFiles》

《/configuration》

《/execution》

《/executions》

《/plugin》

《plugin》

《groupId》org.codehaus.mojo《/groupId》

《artifactId》build-helper-maven-plugin《/artifactId》

《executions》

《execution》

《id》add-source《/id》

《phase》generate-sources《/phase》

《goals》

《goal》add-source《/goal》

《/goals》

《configuration》

《sources》

《source》${basedir}/target/generated-sources/contracts《/source》

《/sources》

《/configuration》

《/execution》

《/executions》

《/plugin》

《/plugins》

《/build》

4、运行Maven生成源

最后,使用mvn clean package(包括generate-sources阶段)构建Maven项目。因此,我们可以看到Java Wrapper已生成到/target/generated-sources/contracts/me/gjeanmart/tutorials/javaethereum/contracts/generated/DocumentRegistry.java并自动添加到类路径中。

037dd34e0d83abbce833340b0e26291b.png

Web3J Gradle插件

最后一个方法与之前使用Maven的方法类似,但使用的是Gradle。

1、先决条件

安装solc并运行以下命令以确保solc版本大于或等于0.5.6(智能合约中指定的版本)。

$ solc --version

solc, the solidity compiler commandline interface

Version: 0.5.9+commit.c68bc34e.Linux.g++

2、将智能合约放入文件夹src / main / solidity

将Smart Contract源DocumentRegistry.sol复制到Gradle项目的src / main / solidity文件夹中。

3、配置Gradle以在构建期间生成Wrapper首先将web3j-gradle插件导入build.gradle文件。

plugins {

id ’org.web3j‘ version ’4.3.0‘

}

然后我们可以配置插件来为生成的wrapper类指定包名称和目标文件夹:

web3j {

generatedPackageName = ’me.gjeanmart.tutorials.javaethereum.contracts.generated‘

generatedFilesBaseDir = “$buildDir/contracts”

}

要使用系统安装的solc版本而不是与插件捆绑的版本,请将以下行添加到build.gradle:

solidity {

executable = “solc”

}

build.gradle

/*

* This file was generated by the Gradle ’init‘ task.

*

* This generated file contains a sample Java Library project to get you started.

* For more details take a look at the Java Libraries chapter in the Gradle

* user guide available at https://docs.gradle.org/5.0/userguide/java_library_plugin.html

*/

plugins {

// Apply the java-library plugin to add support for Java Library

id ’java-library‘

id ’org.web3j‘ version ’4.3.0‘

}

repositories {

// Use jcenter for resolving your dependencies.

// You can declare any Maven/Ivy/file repository here.

jcenter()

}

dependencies {

// This dependency is exported to consumers, that is to say found on their compile classpath.

api ’org.apache.commons:commons-math3:3.6.1‘

// This dependency is used internally, and not exposed to consumers on their own compile classpath.

implementation ’com.google.guava:guava:26.0-jre‘

implementation ’org.web3j:core:4.3.0‘

// Use JUnit test framework

testImplementation ’junit:junit:4.12‘

}

web3j {

generatedPackageName = ’me.gjeanmart.tutorials.javaethereum.contracts.generated‘

generatedFilesBaseDir = “$buildDir/contracts”

}

solidity {

executable = “solc”

}

4、执行gradle构建

在最后一步中,我们使用。/gradlew tasks执行构建--all并验证我们生成的wrapper类是否已生成。

49ab59302608a4477cc817efae472e4c.png

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/459143.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Hive 1.2.1SparkSqoop安装指南

目录 目录 1 1. 前言 1 2. 约定 2 3. 服务端口 2 4. 安装MySQL 2 4.1. 安装MySQL 2 4.2. 创建Hive元数据库 4 5. 安装步骤 5 5.1. 下载Hive 1.2.1二进制安装包 5 5.2. 安装Hive 5 5.3. 安装MySQL-Connector 5 5.4. 修改配置 5 5.4.1. 修改/etc/profile或~/.profile 5 5.4.2. 修…

Matlab与C/C++混合编程调用OpenCV

*************************************************** 更多精彩,欢迎进入:http://shop115376623.taobao.com http://item.taobao.com/item.htm?spma1z10.5-c.w4002-9510581626.24.ZO6sko&id43401674106 精通MATLAB混合编程视频讲解 MATLAB各类函数…

STL--排序与检索

题目 现有N个大理石,每个大理石上写了一个非负整数。首先把各数从小到大排序,然后回答Q个问题。每个问题是否有一个大理石写着某个整数x,如果是,还要回答哪个大理石写着x。排序后的大理石从左到右编写为1-N。(样例中,…

体验LESS CSS 框架

LESS基于NODE.JS的一种框架性语言,它可以更好更快捷的来搭建网站框架结构; 而后LESS 将 CSS 赋予了动态语言的特性,如 变量, 继承,运算, 函数. LESS 既可以在 客户端 上运行 (支持IE 6, Webkit, Firefox)&a…

java添加按钮点击事件_如何为odoo 10中的按钮点击事件添加一个java脚本处理程序?...

我想使用java脚本为header中的按钮创建一个处理程序。下面我视图模型给出:如何为odoo 10中的按钮点击事件添加一个java脚本处理程序?inherit_id"web.assets_backend">rel"stylesheet">my_pet_store_formpetstore.messageformc…

LeetCode(53):Maximum Subarray

Maximum Subarray: Find the contiguous subarray within an array (containing at least one number) which has the largest sum.For example, given the array [−2,1,−3,4,−1,2,1,−5,4],the contiguous subarray [4,−1,2,1] has the largest sum 6. 题意:找…

孩子教育

看了一圈学区房,基本上把浦东各个一流二流学校全看一遍了,大体下来觉得未必非要到一流学校附近买学区房,主要是家庭经济条件不允许,再者我和老公希望孩子在小学培养读书的习惯,而不是天天做试卷。所以一流学校和二流学…

python 程序打包 vscode_使用VScode编写python程序并打包成.exe文件

听说Visual Studio Code(VS Code)的诸多好处,了解了一下果真很喜欢,我喜欢它的缘由主要有3个,一是VS Code开源且跨平台,二是由于其界面很是酷,三是能够知足个人大所属代码需求,除此以外固然还有强大的好奇心…

使用命名空间、头文件和实现文件

*************************************************** 更多精彩,欢迎进入:http://shop115376623.taobao.com *************************************************** 2.3 使用命名空间、头文件和实现文件 使新的throttle类满足程序的需求将是非常…

Permissions for id_rsa are too open

为什么80%的码农都做不了架构师?>>> Last week I was lucky enough to have my laptop upgraded (yay SSD) which meant I needed to configure a new install of OSX Lion. Most of my files are stored online (email, documents, code, etc) but I m…

java看图_看图吧,Java

package salary;import java.awt.*;import javax.swing.*;import java.awt.event.*;import java.text.NumberFormat;public class Salary extends JFrame{//声明标签private JLabel numl;private JLabel basel;private JLabel salel;//声明文本框private JTextField numf;priva…

解决端口占用

tomcat启动时报错: 这说明8080端口已被其他程序占用,先用命令提示符 "netstat -ano" 显示端口,再在结果中找到端口,然后根据其PID再输入"tasklist"命令,在结果中查找其对应程序,就可知…

Python笔记-第一天

1。Python的输出print函数要把输出的字符串用单引号或者双引号括起来,但是不能混用。比如print(hello,world)和print("hello,world")是相同的。2.大小写敏感。3.由于缩进使用空格,复制代码不再那么方便。4.我在notepad中设置了Tab自动转化为4个…

Saltstack 报错 python-crypto randomPool_DeprecationWarning:

执行saltstack 报错一下信息根据报错信息修改python文件#若遇报错1#Starting salt-master daemon: /usr/lib64/python2.6/site-packages/Crypto/Util/number.py:57: PowmInsecureWarning: Not using mpz_powm_sec. You should rebuild using libgmp > 5 to avoid timing at…

java接口源码_java collection接口源码

package java.util;/** 1.Collection接口是集合继承关系中的根接口(root interface),有些集合允许重复元素,* 有些集合有序,JDK不提供本接口的实现,只提供子接口的实现(例如Set,List)* 2.所有实现Collection(或者其子接口)的类都必须包含两个…

结构体的嵌套问题

*************************************************** 更多精彩,欢迎进入:http://shop115376623.taobao.com *************************************************** 结构体的自引用(self reference),就是在结构体内部,包含指向自…

cocos2dx 3.x Value、Vector和Map意识

1. Value cocos2d::Value 这包括一个非常大的数字原生类型&#xff08;int,float,double,bool,unsigned char,char* 和 std::string&#xff09;外 加std::vector<Value>, std::unordered_map<std::string,Value> 和 std::unordered_map<int,Value> 的类。 你…

【MPI学习3】MPI并行程序设计模式:不同通信模式MPI并行程序的设计

学习了MPI四种通信模式 及其函数用法&#xff1a; &#xff08;1&#xff09;标准通信模式&#xff1a;MPI_SEND &#xff08;2&#xff09;缓存通信模式&#xff1a;MPI_BSEND &#xff08;3&#xff09;同步通信模式&#xff1a;MPI_SSEND &#xff08;4&#xff09;就绪通信…

java 日期 年数_java 日期加减天数、月数、年数的计算方式

因为某个项目需要统计 近1周、近1个月、近6个月 等数据&#xff0c;所以在时间的加减上面想了很多方式&#xff0c;最后决定用java.util.Calendarjava.util.Calendar &#xff0c;提供了计算时间的方式&#xff0c;Calendar.DATE : 代表天数Calendar.WEDNESDAY: 代表周数Calend…

学习笔记——C语言实现单链表的基本操作:创建、输出、插入结点、删除结点、逆序链表

*************************************************** 更多精彩&#xff0c;欢迎进入&#xff1a;http://shop115376623.taobao.com *************************************************** 链表是最简单的一种数据结构&#xff0c;是每个软件开发者必须掌握的&#xff0c;也是…