区块链智能合约--以太坊交易记录InputData数据解析

在开发以太坊的时候,我们会有个需求需要得到请求交互合约时的参数,那么这个时候我们应该如何获取呢

一.打开ETH浏览器:https://etherscan.io/

二.点击你要查询的交易详情,下拉到最下面就是你需要的inputData信息(这个信息是用户在调用合约方法的时候传入的参数)

那么在程序中如何获取呢,以下我以java为例.(一般有两种解法,第一种是调用web3j里面的方法进行解析, 第二种是使用字符串截取解析。我用字符串截取解析做示范)

第一步 创建个工具类util   里面是hex转码方法

/**
     *  功能描述:16进制转10进制整数。 
     */
    public static BigInteger hexToBigInteger(String strHex) {
        if (strHex.length() > 2) {
            if (strHex.charAt(0) == '0' && (strHex.charAt(1) == 'X' || strHex.charAt(1) == 'x')) {
                strHex = strHex.substring(2);
            }
            BigInteger bigInteger = new BigInteger(strHex, 16);
            return bigInteger;
        }
        return null;
    }
    

    /**
     *  功能描述:hex地址转地址。 
     */
    public static String hexToAddress(String strHex) {
        if (strHex.length() > 42) {
            if (strHex.charAt(0) == '0' && (strHex.charAt(1) == 'X' || strHex.charAt(1) == 'x')) {
                strHex = strHex.substring(2);
            }
            strHex = strHex.substring(24);
            return "0x" + strHex;
        }
        return null;
    }

第二步编写解析的代码:

@Test
    public void test() {
        String inputData = "0xa9059cbb00000000000000000000000035f5992e40facfcad742fcfcc1d94ee0581e9cb100000000000000000000000000000000000000000000003635c9adc5dea00000";  
        //前十位是methodID由于他是Keccak-256加密生成的无法逆只能通过库来判断是否你需要的
        String methodID= inputData.substring(0, 10);
        System.out.println(methodID);
        //截取前64位值
        String to = inputData.substring(10, 74);
        //将Hex转码Address 
        System.out.println(hexToAddress(to));
        String value = inputData.substring(74);
        BigInteger bigInteger = hexToBigInteger(value);
        System.out.println(bigInteger);
    }

最后输出结果如下

0xa9059cbb
0x35f5992e40facfcad742fcfcc1d94ee0581e9cb1
1000000000000000000000

完成

另外想在线解析inputData 可使用以下网址:https://lab.miguelmota.com/ethereum-input-data-decoder/example/

扫描二维码关注公众号,回复: 14214558 查看本文章

如果有遇到不懂得或者有疑问欢迎联系本人进行交流

WC:luo425116243

猜你喜欢

转载自blog.csdn.net/qq_33842966/article/details/123611038