如何使用Web3J Java签署ERC20令牌交易

时间:2019-10-07 23:26:23

标签: ethereum smartcontracts erc20 web3-java

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

我发现了类似的问题。但是,它的代码不是用Java编写的。而且我不知道如何在ABI中编码传递函数。 Send ERC20 token with web3

谢谢。

1 个答案:

答案 0 :(得分:1)

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

您可以尝试以下方法:

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