Application Binary interface

To use the library import:

"github.com/cloudwalk/ethgo/abi"

Declare basic objects:

typ, err := abi.NewType("uint256")

or

typ = abi.MustNewType("uint256")

and use it to encode/decode the data:

num := big.NewInt(1)
encoded, err := typ.Encode(num)
if err != nil {
panic(err)
}
decoded, err := typ.Decode(encoded) // decoded as interface
if err != nil {
panic(err)
}
num2 := decoded.(*big.Int)
fmt.Println(num.Cmp(num2) == 0) // num == num2

You can also codify structs as Solidity tuples:

import (
"fmt"
"github.com/cloudwalk/ethgo"
"github.com/cloudwalk/ethgo/abi"
"math/big"
)
func main() {
typ := abi.MustNewType("tuple(address a, uint256 b)")
type Obj struct {
A ethgo.Address
B *big.Int
}
obj := &Obj{
A: ethgo.Address{0x1},
B: big.NewInt(1),
}
// Encode
encoded, err := typ.Encode(obj)
if err != nil {
panic(err)
}
// Decode output into a map
res, err := typ.Decode(encoded)
if err != nil {
panic(err)
}
// Decode into a struct
var obj2 Obj
if err := typ.DecodeStruct(encoded, &obj2); err != nil {
panic(err)
}
fmt.Println(res)
fmt.Println(obj)
}

Testing

The ABI codifier uses randomized tests with e2e integration tests with a real Geth client to ensure that the codification is correct and provides the same results as the AbiEncoder from Solidity.