Search code examples
ethereumgo-ethereum

How to use the go API provided by geth to call smart contracts?


    msg := ethereum.CallMsg{
        To:        &contractAddr,
        Gas:       uint64(21000),
        GasTipCap: tipCap,
        GasFeeCap: feeCap,
        Data:
    }
    client.CallContract(context.Background(), msg, nil)

I want to use this API to call smart contracts, but I don't know what to fill in the "Data" field. Can someone provide an example for my reference? Thans very much!


Solution

  • Here ethereum.CallMsg is struct this

    type CallMsg struct {
        From      common.Address  // the sender of the 'transaction'
        To        *common.Address // the destination contract (nil for contract creation)
        Gas       uint64          // if 0, the call executes with near-infinite gas
        GasPrice  *big.Int        // wei <-> gas exchange ratio
        GasFeeCap *big.Int        // EIP-1559 fee cap per gas.
        GasTipCap *big.Int        // EIP-1559 tip per gas.
        Value     *big.Int        // amount of wei sent along with the call
        Data      []byte          // input data, usually an ABI-encoded contract method invocation
    
        AccessList types.AccessList // EIP-2930 access list.
    }
    

    and here Data have a type of []byte

    but I don't know what to fill in the "Data" field

    in the Data field, you need to provide ABI-encoded contract method invocation

    To create ABI-encoded contract method you need to import "github.com/ethereum/go-ethereum/accounts/abi" and use abi.Pack method

    for your reference, you can look at test cases abi_test.go