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

2024-10-17 10:33:00

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

概览

  • 用于w3.Client连接到 RPC 端点。客户端支持批量请求,请求速度最高可提高 80 倍,并且易于扩展。了解更多
  • 用于w3vm.VM模拟 EVM 执行(可选跟踪和主网状态分叉),或测试智能合约。了解更多
  • 使用w3.Func和w3.Event从 Solidity 函数和事件签名创建 ABI 绑定。了解更多
  • 使用w3.A、w3.H和许多其他实用函数从字符串中解析地址、哈希值和其他常见类型。了解更多

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 实现的

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

当前页面是本站的「Baidu MIP」版。发表评论请点击:完整版 »