//转账
public void sendTx(String fromPrivateKey,String toAddress) throws IOException, ExecutionException, InterruptedException {
String contractAddress = "0xdac17f958d2ee523a2206206994597c13d831ec7";
ECKeyPair ecKeyPair = ECKeyPair.create(new BigInteger(fromPrivateKey, 16));
String from = "0x"+Keys.getAddress(ecKeyPair.getPublicKey());
log.info("from:\t\t{}",from);
log.info(" to:\t\t{}",toAddress);
BigDecimal amount = new BigDecimal("1");
BigInteger amountBigInteger = Convert.toWei(amount, Convert.Unit.MWEI).toBigInteger();
EthGetTransactionCount ethGetTransactionCount = web3j.ethGetTransactionCount(
from, DefaultBlockParameterName.LATEST).sendAsync().get();
BigInteger nonce = ethGetTransactionCount.getTransactionCount();
//离线签名 代币
Credentials credentials = Credentials.create(ecKeyPair);
byte[] signedMessage;
Function function = new Function(
"transfer",
Arrays.asList(new Address(toAddress), new Uint256(amountBigInteger)),
Arrays.asList(new TypeReference<Type>(){})
);
String data = FunctionEncoder.encode(function);
RawTransaction rawTransaction = RawTransaction.createTransaction(nonce, Convert.toWei("38", Convert.Unit.GWEI).toBigInteger(),
Convert.toWei("30000", Convert.Unit.WEI).toBigInteger(), contractAddress, data);
signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue = Numeric.toHexString(signedMessage);
log.info("signedData : " + hexValue);
//广播
EthSendTransaction send = web3j.ethSendRawTransaction(hexValue).send();
...
}
|
1
|
|
2
|
|
HconkSep 18, 2019 via iPhone
3
明显 gas limit 给少了,erc20 一般的转账给 5w 差不多够了。
|
|
HconkSep 18, 2019 via iPhone
7
@brust 你的 usd 不够了,你给的链接里面 decimal 是 18 的 token 举例的,你转账的这个 erc20 的 decimal 是 6,改一下金额转换时候的单位,把 18 改成 6。
|
|
8
|
|
10
@Hconk #9
Convert.toWei("38", Convert.Unit.GWEI )这是 gasPrice 这个不对吗? amount 和 gasprice 和 gaslimit 要怎么设置好 为什么我的 Gas Used by Transaction:都是 100% |
|
11
转账成功了,精度弄错了 还有一个疑问就是 手续费似乎有点高? https://etherscan.io/tx/0x43a0c50f4b0f46b71ade7ba3221b78f7de33c6b562127031fd1b7e383d8039d7 |
|
mutongsDec 20, 2019
12
erc20 代币,如果用户没有 eth,怎么转账?我们自己再往用户地址转 eth 进去吗?
|