Springboot整合web3j调用以太坊智能合约转账 + 创建eth地址钱包

1、创建springboot项目并引入web3j的jar包

<!-- web3j -->
<dependency>
    <groupId>org.web3j</groupId>
    <artifactId>web3j-spring-boot-starter</artifactId>
    <version>1.6.0</version>
</dependency>

2、yml配置

client-address 可自己创建个节点,也可去 https://infura.io/ 注册得到,下面填写的是测试链节点客户端地址

web3j:
  client-address: https://rinkeby.infura.io/key  
  admin-client: true
  httpTimeoutSeconds: 600

3、代码干货

首先说下web3j创建钱包地址

File file = new File(“/home/wallet”); //指定一个目录

WalletUtils.generateNewWalletFile("指定好钱包的密码", file, true); //方法返回创建的钱包文件名
至于地址,哈哈,在文件名内可以看到,或者用方法去认证钱包,如下
Credentials credentials = WalletUtils.loadCredentials(“密码”,钱包文件 );
returnAddress = credentials.getAddress();

再说下两个eth地址之间转某种代币的程序代码吧:

Credentials credentials = WalletUtils.loadCredentials(“转出地址密码”, 钱包文件);
String fromAddress = credentials.getAddress();
EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
        fromAddress, DefaultBlockParameterName.LATEST).sendAsync().get();
BigInteger nonce = ethGetTransactionCount.getTransactionCount();
Address address = new Address(toAddress);
Uint256 value = new Uint256(amount);
List<Type> parametersList = new ArrayList<>();
parametersList.add(address);
parametersList.add(value);
List<TypeReference<?>> outList = new ArrayList<>();
Function function = new Function("transfer", parametersList, outList);
String encodedFunction = FunctionEncoder.encode(function);
RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, Gas单价,
        Gas最大数量, 合约地址, encodedFunction);
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue = Numeric.toHexString(signedMessage);

EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
transactionHash = ethSendTransaction.getTransactionHash();

最后拿到的就是这比转账的txHash了,可通过Json-rpc去查看转账状态(very easy),

Json-rpc说明文档地址:https://github.com/ethereum/wiki/wiki/JSON-RPC

提供了好多方法,去试试吧,骚年!

4、如果你入职了某个公司有自己的ERC20虚拟货币,就用这种java方式就能实现转账啦,哈哈,如果喜欢请关注!兄弟

原创,请勿转载,谢谢!

猜你喜欢

转载自blog.csdn.net/qq_33285478/article/details/80215815
今日推荐