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

以ERC20转账为例

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类去调用交易

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();
}

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发送签名交易即可

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());

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,259评论 19 139
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,553评论 0 13
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,839评论 18 399
  • “如果你长时间凝视深渊,那么深渊也凝视着你。”今天看到一句话是这样的。我用两个小时看完了金星写的《掷地有声》,脑子...
    南国雪阅读 228评论 2 1
  • 1、在这节课最重要印象最深刻的三个部分/知识点? (1)上课那个组报告课程 (2)睡眠和梦的知识点 (3)想象的知...
    跨越地球去睡你阅读 188评论 0 1