无法从Nethereum解码的输入数据中获得可读的整数

时间:2019-03-22 08:23:29

标签: c# .net-core ethereum solidity

将实体的uint256转换为可读的c#对象时遇到麻烦。

public Transaction DecodeInputData(Transaction tx)
    {

        EthApiContractService ethApi = new EthApiContractService(null);
        var contract = ethApi.GetContract(Abi.Replace(@"\", string.Empty), Address);

        var transfer = contract.GetFunction("transfer");
        var decodedTx = transfer.DecodeInput(tx.input);

        tx.to = (string)decodedTx[0].Result;
        tx.value = "0x" + ((BigInteger)decodedTx[1].Result).ToString("x");

        return tx;
    }

示例Tx:https://etherscan.io/tx/0x622760ad1a0ead8d16641d5888b8c36cb67be5369556f8887499f4ad3e3d1c3d

我们必须能够将decodedTx [1] .Result变量(其:{53809663494440740791636285293469688360281260987263635605451211260198698423701})转换为83218945020000000000。

我们将此值转换为十六进制表示兼容性。但是我得到的是“ 0x76f730b400000000000000000000000000000000000000000000000000000482e51595”

我正在将Nethereum库与.net core 2.1一起使用

1 个答案:

答案 0 :(得分:1)

您正在尝试解码交易的智能合约功能参数。智能合约是ERC20智能合约,功能是“转移”方法。

为此,您需要执行以下操作。

  • 在这种情况下,创建转移功能。
  • 检索交易
  • 使用FunctionMessage扩展方法DecodeTransaction,对原始Transaction输入的值进行解码。
using Nethereum.Web3;
using Nethereum.ABI.FunctionEncoding.Attributes;
using Nethereum.Contracts.CQS;
using Nethereum.Util;
using Nethereum.Web3.Accounts;
using Nethereum.Hex.HexConvertors.Extensions;
using Nethereum.Contracts;
using Nethereum.Contracts.Extensions;
using System;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;


public class GetStartedSmartContracts
{

    [Function("transfer", "bool")]
    public class TransferFunction : FunctionMessage
    {
        [Parameter("address", "_to", 1)]
        public string To { get; set; }

        [Parameter("uint256", "_value", 2)]
        public BigInteger TokenAmount { get; set; }
    }

    public static async Task Main()
    {

        var url = "https://mainnet.infura.io";
        var web3 = new Web3(url);
                var txn = await web3.Eth.Transactions.GetTransactionByHash.SendRequestAsync("0x622760ad1a0ead8d16641d5888b8c36cb67be5369556f8887499f4ad3e3d1c3d");

        var transfer = new TransferFunction().DecodeTransaction(txn);
                Console.WriteLine(transfer.TokenAmount);
                //BAT has 18 decimal places the same as Wei
                Console.WriteLine(Web3.Convert.FromWei(transfer.TokenAmount));
    }
}

您可以在http://playground.nethereum.com

中对此进行测试