4

我想将 erc20 代币从一个账户转移到另一个账户。我知道我可以使用智能合约包装类的 transfer 或 transferFrom 函数。但就我而言,erc20 令牌交易需要在客户端进行签名。并且没有办法在智能合约包装函数中传递 signedTransaction。那么,如何签署 erc20 令牌交易并在 java 中使用 web3j 执行交易。

我发现了这个类似的问题。但是,它的代码不是用java编写的。而且我不知道如何在 ABI 中编码传递函数。 使用 web3 发送 ERC20 令牌

提前致谢。

4

1 回答 1

4

有点晚了,但也许会帮助某人:

你可以试试这个:

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

传递函数可以是:

        private Function transfer(String to, BigInteger value) {
            return new Function(
                    "transfer",
                    Arrays.asList(new Address(to), new Uint256(value)),
                    Collections.singletonList(new TypeReference<Bool>() {
                    }));
        }
于 2020-04-08T11:27:04.137 回答