Golang ethclient.Client – 如何进行RPC调用?

huangapple go评论98阅读模式
英文:

Golang ethclient.Client - how to make RPC calls?

问题

如何使用ethclient.Client(https://github.com/ethereum/go-ethereum)调用RPC端点?

有些方法没有包装器,据我所见,直接调用它是不可能的,例如:

client, err := ethclient.Dial(url)

// 正确
client.BalanceAt(...)

// 错误的代码,试图访问私有字段`c *rpc.Client`
client.c.Call("debug_traceTransaction", ...)

我唯一能想到的方法是启动完全独立的RPC客户端,并始终保持两者运行。这是唯一的方法吗?

英文:

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?

答案1

得分: 2

ethclient.Dial函数(你提到的)在底层使用了rpc.DialContext函数,该包还提供了一个ethclient.NewClient函数,用于使用现有的rpc连接创建一个新的ethclient.Client

一个可能的解决方案是创建一个新的rpc连接,然后将其传递给ethclient.Client,这样你就可以使用一个连接,同时可以使用RPC连接本身和eth客户端。

类似这样的代码:

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

ethClient := ethclient.NewClient(rpcClient)

// 使用ethClient
ethClient.BalanceAt(...)

// 访问rpc客户端
rpcClient.Call(...)
英文:

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(...)

huangapple
  • 本文由 发表于 2021年11月3日 22:19:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/69826510.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定