Jay*_*ngh 4 ethereum smartcontracts erc20 web3-java
我想将 erc20 代币从一个账户转移到另一个账户。我知道我可以使用智能合约包装类的transfer或transferFrom函数。但就我而言,erc20 代币交易需要在客户端进行签名。并且无法在智能合约包装函数中传递signedTransaction。那么,我如何签署erc20令牌交易并使用java中的web3j执行交易。
我发现了这个类似的问题。但是,它的代码不是用java编写的。我不知道如何在 ABI 中编码传递函数。 使用 web3 发送 ERC20 代币
提前致谢。
有点晚了,但也许会对某人有所帮助:
你可以试试这个:
import org.web3j.abi.TypeReference;
import org.web3j.abi.datatypes.Address;
import org.web3j.abi.datatypes.Bool;
import org.web3j.abi.datatypes.generated.Uint256;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.RawTransaction;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.utils.Convert;
import org.web3j.utils.Numeric;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collections;
import java.util.function.Function;
Run Code Online (Sandbox Code Playgroud)
// create credentials
String privateKeyHexValue = Numeric.toHexString(privateKey.data());
Credentials credentials = Credentials.create(privateKeyHexValue);
// get the next available nonce
EthGetTransactionCount ethGetTransactionCount = web3.ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.LATEST).send();
BigInteger nonce = ethGetTransactionCount.getTransactionCount();
// Value to transfer (ERC20 token)
BigInteger balance = Convert.toWei("1", Convert.Unit.ETHER).toBigInteger();
// create transfer function
Function function = transfer(dstAddress, balance);
String encodedFunction = FunctionEncoder.encode(function);
// Gas Parameters
BigInteger gasLimit = BigInteger.valueOf(71000); // you should get this from api
BigInteger gasPrice = new BigInteger("d693a400", 16); // decimal 3600000000
// create the transaction
RawTransaction rawTransaction =
RawTransaction.createTransaction(
nonce, gasPrice, gasLimit, < ERC20_CONTRACT_ADDRESS >, encodedFunction);
// sign the transaction
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue = Numeric.toHexString(signedMessage);
// Send transaction
EthSendTransaction ethSendTransaction = web3.ethSendRawTransaction(hexValue).sendAsync().get();
String transactionHash = ethSendTransaction.getTransactionHash();
Run Code Online (Sandbox Code Playgroud)
传递函数可以是:
private Function transfer(String to, BigInteger value) {
return new Function(
"transfer",
Arrays.asList(new Address(to), new Uint256(value)),
Collections.singletonList(new TypeReference<Bool>() {
}));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1903 次 |
| 最近记录: |