Contract
The Contract struct represents a deployed Solidity contract.
To instantiate a Contract object use:
contract.NewContract(addr, abi)
with:
By default, it connects to the https://localhost:8545 JsonRPC endpoint.
Options
Besides addr and abi, you can use the option pattern to parametrize the contract, the available options are:
- WithJsonRPCEndpoint: JsonRPC url of the endpoint to connect with.
- WithJsonRPCClient:
JsonRPCobject to make rpc calls. It takes preference over an address fromWithAddress. - WithSigner:
Signerobject to send transactions or use a customfromaddress. - WithProvider: Custom NodeProvider implementation to resolve calls and transactions.
- WithEIP1559: Send transactions with EIP-1559 pricing.
Examples
Check examples for a list of examples on how to interact with a smart contract.
Call a contract
package main
import ( "fmt" "math/big"
"github.com/umbracle/ethgo" "github.com/umbracle/ethgo/abi" "github.com/umbracle/ethgo/contract" "github.com/umbracle/ethgo/jsonrpc")
func handleErr(err error) { if err != nil { panic(err) }}
// call a contractfunc main() { var functions = []string{ "function totalSupply() view returns (uint256)", }
abiContract, err := abi.NewABIFromList(functions) handleErr(err)
// Matic token addr := ethgo.HexToAddress("0x7d1afa7b718fb893db30a3abc0cfc608aacfebb0")
client, err := jsonrpc.NewClient("https://mainnet.infura.io") handleErr(err)
c := contract.NewContract(addr, abiContract, contract.WithJsonRPC(client.Eth())) res, err := c.Call("totalSupply", ethgo.Latest) handleErr(err)
fmt.Printf("TotalSupply: %s", res["totalSupply"].(*big.Int))}
Abigen
One small limitation of Contract is that works with interface objects since the input and outputs of a smart contract are arbitrary. As an alternative, you can use Abigen to generate Go bindings that wrap the Contract object and provide native and typed Go functions to interact with the contracts.
By default, ethgo includes builtin abigen contracts for ens and erc20 tokens.