ETH 签名
public static String signedEthTransactionData(
String privateKey, String to, BigInteger nonce, BigInteger gasPrice, BigInteger gasLimit, String value) {
// 把十进制的转换成ETH的Wei, 1ETH = 10^18 Wei
BigDecimal realValue = Convert.toWei(value, Convert.Unit.ETHER);
RawTransaction rawTransaction = RawTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, to, realValue.toBigIntegerExact());
// 手续费= (gasPrice * gasLimit ) / 10^18 ether
Credentials credentials = Credentials.create(privateKey);
// 使用TransactionEncoder对RawTransaction进行签名操作
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
// 转换成0x开头的字符串
return Numeric.toHexString(signedMessage);
}
ETH代币签名
public static String signedEthContractTransactionData(
String privateKey, String contractAddress, String to, BigInteger nonce, BigInteger gasPrice,
BigInteger gasLimit, Double value, Double decimal) {
// 因为每个代币可以规定自己的小数位, 所以实际的转账值 = 数值 * 10^小数位
BigDecimal realValue = BigDecimal.valueOf(value * Math.pow(10.0, decimal));
// 0xa9059cbb代表某个代币的转账方法hex(transfer) + 对方的转账地址hex + 转账的值的hex
String data = "0xa9059cbb" + Numeric.toHexStringNoPrefixZeroPadded(Numeric.toBigInt(to), 64)
+ Numeric.toHexStringNoPrefixZeroPadded(realValue.toBigInteger(), 64);
RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, gasPrice, gasLimit, contractAddress, data);
// 手续费= (gasPrice * gasLimit ) / 10^18 ether
Credentials credentials = Credentials.create(privateKey);
// 使用TransactionEncoder对RawTransaction进行签名操作
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
// 转换成0x开头的字符串
return Numeric.toHexString(signedMessage);
}
网友评论