Parse ABI
Parse JSON ABIs into an ABI struct or into raw items in viem-go
Loading...
Parse JSON ABIs into an ABI struct or into raw items in viem-go
The abi package parses Ethereum JSON ABIs so you can encode/decode contract calls, events, and errors. Use Parse (or ParseFromString / MustParse) to get an *abi.ABI; use ParseItems to get a slice of raw items for inspection without the typed maps.
import ( "encoding/hex" "github.com/ChefBingbong/viem-go/abi" "github.com/ethereum/go-ethereum/common")Parse a JSON ABI (bytes) into an *abi.ABI that exposes Functions, Events, and Errors maps.
import "github.com/ChefBingbong/viem-go/abi"
jsonABI := []byte(`[ { "name": "transfer", "type": "function", "inputs": [ {"name": "to", "type": "address"}, {"name": "amount", "type": "uint256"} ], "outputs": [{"type": "bool"}] }, { "name": "Transfer", "type": "event", "inputs": [ {"name": "from", "type": "address", "indexed": true}, {"name": "to", "type": "address", "indexed": true}, {"name": "value", "type": "uint256", "indexed": false} ] }]`)
parsed, err := abi.Parse(jsonABI)if err != nil { log.Fatal(err)}
// Access by nametransferFn := parsed.Functions["transfer"]fmt.Println("Selector:", hex.EncodeToString(transferFn.Selector[:]))
transferEv := parsed.Events["Transfer"]fmt.Println("Topic:", transferEv.Topic.Hex())After parsing, you get an ABI struct:
| Field | Type | Description |
|---|---|---|
| Functions | map[string]Function | Function name → definition. |
| Events | map[string]Event | Event name → definition. |
| Errors | map[string]Error | Error name → definition. |
Helper methods:
Parse the JSON ABI into a slice of ABIItem structs for inspection. Each item has Type, Name, Inputs, Outputs, StateMutability, Anonymous. Does not build the typed Functions / Events / Errors maps.
items, err := abi.ParseItems(jsonABI)
if err != nil {
log.Fatal(err)
}
for _, item := range items {
fmt.Println(item.Type, item.Name)
}
"function", "event"), Name, Inputs ([]ABIInput), Outputs, StateMutability, Anonymous.parseAbi("function transfer(...)"); use Parse with JSON ABI bytes.