What is ethereumjs-abi?
The ethereumjs-abi package is a JavaScript library for encoding and decoding data according to the Ethereum ABI (Application Binary Interface) specifications. It is commonly used for interacting with smart contracts on the Ethereum blockchain, allowing developers to encode function calls and decode responses.
What are ethereumjs-abi's main functionalities?
Encoding Function Calls
This feature allows you to encode function calls to be sent to a smart contract. The example encodes a call to the 'transfer' function with an address and a value.
const abi = require('ethereumjs-abi');
const methodSignature = 'transfer(address,uint256)';
const params = ['0xRecipientAddress', 1000];
const encodedData = abi.simpleEncode(methodSignature, ...params);
console.log(encodedData.toString('hex'));
Decoding Function Responses
This feature allows you to decode the response from a smart contract function call. The example decodes the response from a 'balanceOf' function call.
const abi = require('ethereumjs-abi');
const methodSignature = 'balanceOf(address)';
const encodedData = '0xEncodedData';
const decodedData = abi.simpleDecode(methodSignature, Buffer.from(encodedData, 'hex'));
console.log(decodedData);
Encoding Event Logs
This feature allows you to encode event logs for smart contract events. The example encodes a 'Transfer' event log with from and to addresses and a value.
const abi = require('ethereumjs-abi');
const eventSignature = 'Transfer(address,address,uint256)';
const params = ['0xFromAddress', '0xToAddress', 1000];
const encodedLog = abi.simpleEncode(eventSignature, ...params);
console.log(encodedLog.toString('hex'));
Decoding Event Logs
This feature allows you to decode event logs from smart contract events. The example decodes a 'Transfer' event log.
const abi = require('ethereumjs-abi');
const eventSignature = 'Transfer(address,address,uint256)';
const encodedLog = '0xEncodedLog';
const decodedLog = abi.simpleDecode(eventSignature, Buffer.from(encodedLog, 'hex'));
console.log(decodedLog);
Other packages similar to ethereumjs-abi
web3-eth-abi
The web3-eth-abi package is part of the Web3.js library and provides similar functionality for encoding and decoding Ethereum ABI data. It is more integrated with the Web3.js ecosystem, making it a good choice if you are already using Web3.js for other Ethereum interactions.
ethers
The ethers package is a complete Ethereum library that includes ABI encoding and decoding among many other features. It is known for its simplicity and ease of use, and it provides a more modern and modular approach compared to ethereumjs-abi.
abi-decoder
The abi-decoder package focuses specifically on decoding Ethereum ABI data, particularly for transaction input data and logs. It is simpler and more focused compared to ethereumjs-abi, making it a good choice if you only need decoding functionality.
ethereumjs-abi
Module implementing the Ethereum ABI in Javascript. Can be used with RPC libraries for communication or with ethereumjs-vm to implement a fully fledged simulator.
Usage
Manual encoding and decoding
There are two methods of interest, rawEncode
to encode a call (name plus arguments) and rawDecode
to decode a response for a specific encoded query.
Example code:
var ABI = require('ethereumjs-abi')
var abi = new ABI()
var encoded = abi.rawEncode("balanceOf", [ "address" ], [ "0x0000000000000000000000000000000000000000" ])
var decoded = abi.rawDecode("balanceOf", [ "address" ], [ "uint256" ], data)
For preparing encoded blocks without the signature, use rawEncodeResponse
. This can be useful when interfacing with contracts as a data provider.
Encoding and decoding aided by the JSON ABI definition
Planned for the future is supporting the JSON ABI definition:
var ABI = require('ethereumjs-abi')
var abi = new ABI()
var tokenAbi = [{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"type":"function"},{"inputs":[],"type":"constructor"}]
var encoded = ABI.encode(tokenAbi, "balanceOf(uint256 address)", [ "0x0000000000000000000000000000000000000000" ])
var decoded = ABI.decode(tokenAbi, "balanceOf(uint256 address)", data)
Solidity tightly packed formats
This library also supports creating Solidity's tightly packed data constructs, which are used together with sha3
, sha256
and ripemd160
to create hashes.
Solidity code:
contract HashTest {
function testSha3() returns (bytes32) {
address addr1 = 0x43989fb883ba8111221e89123897538475893837;
address addr2 = 0;
uint val = 10000;
uint timestamp = 1448075779;
return sha3(addr1, addr2, val, timestamp);
}
}
Creating the same hash using this library:
var ABI = require('ethereumjs-abi')
var abi = new ABI()
var BN = require('bn.js')
abi.soliditySHA3(
[ "address", "address", "uint", "uint" ],
[ new BN("43989fb883ba8111221e89123897538475893837", 16), 0, 10000, 1448075779 ]
).toString('hex')
For the same data structure:
- sha3 will return
0xc3ab5ca31a013757f26a88561f0ff5057a97dfcc33f43d6b479abc3ac2d1d595
- sha256 will return
0x344d8cb0711672efbdfe991f35943847c1058e1ecf515ff63ad936b91fd16231
- ripemd160 will return
0x000000000000000000000000a398cc72490f72048efa52c4e92067e8499672e7
(NOTE: it is 160bits, left padded to 256bits)
Note that ripemd160()
in Solidity returns bytes20 and if you cast it to bytes32, it will be right padded with zeroes.
Contributing
I am more than happy to receive improvements. Please send me a pull request or reach out on email or twitter.
There is a lot missing, grep for FIXME in the source code to find inspiration.
License
Copyright (C) 2015 Alex Beregszaszi
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.