Ethers.js: How do I decode transaction calldata?

Created on 5 Dec 2018  路  6Comments  路  Source: ethers-io/ethers.js

e.g.,

> x = new ethers.utils.Interface(["foo(bytes bar)"]).functions.foo.encode(["0x"])
'0x30c8d1da00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000'
> new ethers.utils.Interface(["foo(bytes bar)"]).functions.foo.decode(x)
[]

[] should be {0: "0x", bar: "0x"} I think

discussion

Most helpful comment

Encode creates the data required for the request call. Decode is for decoding the result from a call.

In v5, there is now a encodeFunctionData() and a decodeFunctionResult(). Thanks for reminding me to add the decodeFunctionData and encodeFunctionResult, which I鈥檒l do tomorrow. :)

All 6 comments

That isn't what the decode is for. :)

let iface = new ethers.utils.Interface(["foo(bytes bar)"]);
let foo = iface.functions.foo;

// Prepare encoded data to be used in a function call
let x = foo.encode([ "0x" ]);
console.log(x);
// "0x30c8d1da00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000"

// This is ONLY for decoding the RETURN data from an eth_call
// Since "foo(bytes)" does not have a return type, there is no decoder
// So this doesn't do anything useful
//let y = foo.decode(ethers.utils.hexDataSlice(x, 4)));

// What you probable want is:
let tx = {
    data: x
};
let y = iface.parseTransaction(tx);
console.log(y);
// _TransactionDescription {
//  args: [ '0x' ],
//  decode: [Function],
//  name: 'foo(bytes)',
//  signature: 'foo(bytes)',
//  sighash: '0x30c8d1da',
//  value: BigNumber { _hex: '0x00' } }

// The "y.args" is what you are expecting

Or, if you want to parse it more directly:

console.log(ethers.utils.defaultAbiCoder.decode([ 'bytes' ], ethers.utils.hexDataSlice(x, 4)));
// [ '0x' ]

Makes sense after the explanation. I suppose this should be documented slightly more clearly to avoid confusion? It seems natural in most cases that something.decode(something.encode(x)) => x

I don't necessarily disagree with you, but I couldn't think of a better naming convention at the time... I'll make a note to consider renaming them in the next major version. :)

What is decode for, if not to decode?

I'm having the same problem.

Encode creates the data required for the request call. Decode is for decoding the result from a call.

In v5, there is now a encodeFunctionData() and a decodeFunctionResult(). Thanks for reminding me to add the decodeFunctionData and encodeFunctionResult, which I鈥檒l do tomorrow. :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

PhABC picture PhABC  路  3Comments

crazyrabbitLTC picture crazyrabbitLTC  路  3Comments

GFJHogue picture GFJHogue  路  3Comments

jochenonline picture jochenonline  路  3Comments

thegostep picture thegostep  路  3Comments