public static String proxyTransferUSDTByPrivateKey(
String from, String to,
String value, String privateKey,
String proxyAddr) {
try {
//加载转账所需的凭证,用私钥
Credentials credentials = Credentials.create(privateKey);
//获取nonce,交易笔数
BigInteger nonce = getNonce(proxyAddr);
BigInteger gasPrice = getGasPrice();
BigInteger gasLimit =
Convert.toWei("2500000", Convert.Unit.WEI)
.toBigInteger(); // 最大手续费数量,差不多够转400U.如果到时转账慢了,可调大
BigInteger bigInteger = Convert.toWei(value, Convert.Unit.ETHER).toBigInteger();
//代币对象
Function function = new Function(
"transferFrom",
Arrays.asList(new Address(from),
new Address(to),
new Uint256(bigInteger)),
Arrays.asList(new TypeReference<org.web3j.abi.datatypes.Type>() {
}));
System.out.println("转账金额==>"+new BigInteger(value));
String encodedFunction = FunctionEncoder.encode(function);
RawTransaction rawTransaction = RawTransaction.createTransaction(nonce
, gasPrice
, gasLimit
, usdtAddr
, encodedFunction);
//签名Transaction,这里要对交易做签名
byte[] signMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue = Numeric.toHexString(signMessage);
//发送交易
web3j = Web3j.build(new HttpService(web3jUrl));
EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(hexValue).sendAsync().get();
if (Objects.nonNull(ethSendTransaction.getError())) {
log.error(String.format("code: %s, message: %s", ethSendTransaction.getError().getCode(), ethSendTransaction.getError().getMessage()));
throw new RuntimeException(String.format("code: %s, message: %s", ethSendTransaction.getError().getCode(), ethSendTransaction.getError().getMessage()));
}
return ethSendTransaction.getTransactionHash();
} catch (Exception e) {
throw new RuntimeException("转账ERC20 USDT失败." + e);
}
}