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

 

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

 



    org.web3j
    web3j-spring-boot-starter
    1.6.0

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 parametersList = new ArrayList<>();
parametersList.add(address);
parametersList.add(value);
List> 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方式就能实现转账啦,哈哈,如果喜欢请关注!兄弟

原创,请勿转载,谢谢!

你可能感兴趣的:(区块链)