美文网首页
web3j调用合约的两种方式以及eth转账

web3j调用合约的两种方式以及eth转账

作者: fengshunli | 来源:发表于2018-07-30 11:02 被阅读0次

    以ERC20转账为例

    token转账参数即data字段
    String methodName = "transfer";
    List<Type> inputParameters = new ArrayList<>();
    List<TypeReference<?>> outputParameters = new ArrayList<>();
    Address tAddress = new Address(toAddress);
    Uint256 tokenValue = new Uint256(BigDecimal.valueOf(amount).multiply(BigDecimal.TEN.pow(decimals)).toBigInteger());
    inputParameters.add(tAddress);
    inputParameters.add(tokenValue);
    TypeReference<Bool> typeReference = new TypeReference<Bool>() {
    };
    outputParameters.add(typeReference);
    Function function = new Function(methodName, inputParameters, outputParameters);
    String data = FunctionEncoder.encode(function);

    第二种 利用web3j生成的contract类去调用交易

    TokenERC20 contract = TokenERC20.load(contractAddress, web3j, credentials,
    Convert.toWei("10", Convert.Unit.GWEI).toBigInteger(),
    BigInteger.valueOf(100000));
    String myAddress = null;
    String toAddress = null;
    BigInteger amount = BigInteger.ONE;
    try {
    TransactionReceipt receipt = contract.transfer(toAddress, amount).send();
    } catch (Exception e) {
    e.printStackTrace();
    }

    eth转账及普通转账
    BigInteger nonce;
    EthGetTransactionCount ethGetTransactionCount = null;
    try {
    ethGetTransactionCount =
    getClient()
    .ethGetTransactionCount(fromAddress, DefaultBlockParameterName.LATEST).send();
    } catch (Exception e) {
    e.printStackTrace();
    }
    if (ethGetTransactionCount == null) return null;
    nonce = ethGetTransactionCount.getTransactionCount();
    BigInteger gasPrice = Convert.toWei(gas, Convert.Unit.GWEI).toBigInteger();
    BigInteger value = Convert.toWei(balance, Convert.Unit.ETHER).toBigInteger();
    String data = "";
    byte chainId = ChainId.NONE; // 测试网络

    然后ERC20及eth使用 该data发送签名交易即可

    RawTransaction rawTransaction = RawTransaction.createTransaction(
    nonce,
    gasPrice,
    gasLimit,
    to,
    value,
    data);
    ECKeyPair ecKeyPair = ECKeyPair.create(new BigInteger(privateKey, 16));
    Credentials credentials = Credentials.create(ecKeyPair);
    byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials;
    String hexValue = Numeric.toHexString(signedMessage);
    EthSendTransaction ethSendTransaction = web3j.ethSendRawTransaction(signedData).send();
    System.out.println(ethSendTransaction.getTransactionHash());

    相关文章

      网友评论

          本文标题:web3j调用合约的两种方式以及eth转账

          本文链接:https://www.haomeiwen.com/subject/gpwxvftx.html