前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >web3j调用合约的两种方式以及eth转账

web3j调用合约的两种方式以及eth转账

作者头像
24-丰总
发布2018-08-03 10:10:00
2.1K0
发布2018-08-03 10:10:00
举报
文章被收录于专栏:24k24k

以ERC20转账为例

代码语言:javascript
复制
token转账参数即data字段
 String methodName = "transfer";
 List<Type> inputParameters = new ArrayList<>();
 List<TypeReference<?>> outputParameters = new ArrayList<>();
 Address tAddress = new Address(toAddress);
 Uint256 tokenValue = new Uint256(BigDecimal.valueOf(amount).multiply(BigDecimal.TEN.pow(decimals)).toBigInteger());
 inputParameters.add(tAddress);
 inputParameters.add(tokenValue);
 TypeReference<Bool> typeReference = new TypeReference<Bool>() {
 };
 outputParameters.add(typeReference);
 Function function = new Function(methodName, inputParameters, outputParameters);
 String data = FunctionEncoder.encode(function);

第二种 利用web3j生成的contract类去调用交易

代码语言:javascript
复制
TokenERC20 contract = TokenERC20.load(contractAddress, web3j, credentials,
 Convert.toWei("10", Convert.Unit.GWEI).toBigInteger(),
 BigInteger.valueOf(100000));
 String myAddress = null;
 String toAddress = null;
 BigInteger amount = BigInteger.ONE;
 try {
 TransactionReceipt receipt = contract.transfer(toAddress, amount).send();
 } catch (Exception e) {
 e.printStackTrace();
 }
代码语言:javascript
复制
eth转账及普通转账
 BigInteger nonce;
 EthGetTransactionCount ethGetTransactionCount = null;
 try {
 ethGetTransactionCount =
 getClient()
 .ethGetTransactionCount(fromAddress, DefaultBlockParameterName.LATEST).send();
 } catch (Exception e) {
 e.printStackTrace();
 }
 if (ethGetTransactionCount == null) return null;
 nonce = ethGetTransactionCount.getTransactionCount();
 BigInteger gasPrice = Convert.toWei(gas, Convert.Unit.GWEI).toBigInteger();
 BigInteger value = Convert.toWei(balance, Convert.Unit.ETHER).toBigInteger();
 String data = "";
 byte chainId = ChainId.NONE; // 测试网络

然后ERC20及eth使用 该data发送签名交易即可

代码语言:javascript
复制
RawTransaction rawTransaction = RawTransaction.createTransaction(
 nonce,
 gasPrice,
 gasLimit,
 to,
 value,
 data);
 ECKeyPair ecKeyPair = ECKeyPair.create(new BigInteger(privateKey, 16));
 Credentials credentials = Credentials.create(ecKeyPair);
 byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials;
 String hexValue = Numeric.toHexString(signedMessage);
 EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(signedData).send();
 System.out.println(ethSendTransaction.getTransactionHash());
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.07.30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档