How to encode and decode ABI data?
Can someone show me an example with web3js library?
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.
Sign up to join this communityHow to encode and decode ABI data?
Can someone show me an example with web3js library?
If the question is about abi params, you can take a look at these two web3.js files:
https://github.com/ethereum/web3.js/blob/master/test/coder.encodeParam.js https://github.com/ethereum/web3.js/blob/master/test/coder.decodeParam.js
Although these functions are not a part of public web3.js
interface. Mostly because they need a proper refactor.
There is also a command line tool created especially for encoding function calls and retrieving output data.
In case you need an online tool to encode parameters to abi format you can use https://abi.hashex.org/. It has functionality to auto parse contract's abi to get function names and parameter types and provides convenient way to enter their values.
web3 1.0:
web3.eth.abi.decodeParameter('address', '0000000000000000000000001829d79cce6aa43d13e67216b355e81a7fffb220')
you should receive:
0x1829D79cCE6aA43D13E67216b355E81A7FfFB220
you can also try:
I modified web3 npm library by including the following line
Web3.SolidityCoder = require('./lib/solidity/coder');
after the Web3 object gets created.
In the client side, you can use it with following code.
web3 = require('web3'); // This will import the web3 library.
web3.SolidityCoder.encodeParams([types array], [values array])
web3.SolidityCoder.decodeParams([types array], encodedData)
This of course is a hack and is suitable for quick testing, if this would be a recommended approach, I could push changes to official web3 library. I'll check with them.
Update: There is a getData() method available in web3.js which you can use for this purpose. Here is the link to documentation: https://github.com/ethereum/wiki/wiki/JavaScript-API#contract-methods
The easiest way to to use "abi-decoder". I forked the repository and created index.html for easy usage.
You can download and use it from: https://github.com/Muhammad-Altabba/abi-decoder (you can later check it at https://github.com/ConsenSys/abi-decoder once they will accept my Pull-Request)
To download and run using NPM:
npm install abi-decoder
bower install abi-decoder
Then download https://github.com/Muhammad-Altabba/abi-decoder/index.html to the same directory. Then open the file "index.html" in browser.
You will get:
If you mean the data for sending a message, a simple way is to encode it like this:
contract = web3.eth.contract(abi).at(cAddr);
payload = contract['transfer'].getData(to, amont);
The payload
is just what you want.