Home > OS >  Golang ethclient.Client - how to make RPC calls?
Golang ethclient.Client - how to make RPC calls?

Time:11-04

How to call RPC endpoints using ethclient.Client ( https://github.com/ethereum/go-ethereum )?

Some methods don't have wrappers, and, as far as i can see, calling it directly is impossible e.g.

client, err := ethclient.Dial(url)

// ok
client.BalanceAt(...)

// incorrect code, trying to access private field `c *rpc.Client`
client.c.Call("debug_traceTransaction", ...)

The only way i can think of is spinning up totally separate rpc client and keep both running at all times. Is this the only way?

CodePudding user response:

The ethclient.Dial function (which you mentioned) uses the rpc.DialContext function underneath, and the package also provides an ethclient.NewClient function to create a new ethclient.Client with an existing rpc connection.

A possible solution could be to create a new rpc connection, then pass it to the ethclient.Client, so you're using one connection, but can use the RPC connection itself and the eth client as well.

Something like this:

rpcClient, err := rpc.DialContext(ctx, url)

ethClient := ethclient.NewClient(rpcClient)

// use the ethClient
ethClient.BalanceAt(...)

// access to rpc client
rpcClient.Call(...)
  • Related