欢迎所有爱好区块链技术的人加入。

ARCHIVES / 1961.HTML

w3: 增强以太坊与 Go 的集成

Surou

w3是您使用 Go 与以太坊集成的工具带。go‑ethereum它与 紧密相关,为使用RPC、ABI和EVM提供了一个符合人体工程学的包装器。

概览

github: https://github.com/lmittmann/w3

代码解析

w3的批量请求,

// 1. Connect to an RPC endpoint
client, err := w3.Dial("https://rpc.ankr.com/eth")
if err != nil {
    // handle error
}
defer client.Close()

// 2. Make a batch request
var (
    balance *big.Int
    nonce   uint64
)
if err := client.Call(
    eth.Balance(addr, nil).Returns(&balance),
    eth.Nonce(addr, nil).Returns(&nonce),
); err != nil {
    // handle error
}

是通过使用CallCtx

func (c *Client) CallCtx(ctx context.Context, calls ...w3types.RPCCaller) error {
	// no requests = nothing to do
	if len(calls) <= 0 {
		return nil
	}

	// create requests
	batchElems := make([]rpc.BatchElem, len(calls))
	var err error
	for i, req := range calls {
		batchElems[i], err = req.CreateRequest()
		if err != nil {
			return err
		}
	}

	// invoke rate limiter
	if err := c.rateLimit(ctx, batchElems); err != nil {
		return err
	}

	// do requests
	if len(batchElems) > 1 {
		// batch requests if >1 request
		err = c.client.BatchCallContext(ctx, batchElems)
		if err != nil {
			return err
		}
	} else {

调用go-ethereum->BatchCallContext 实现的

对于我们常规代码实现中,也可以参考实现