AI编程助手
AI免费问答

`go-ethereum` client.BlockByHash() 给出错误“未找到”

PHPz   2024-02-09 08:00   893浏览 转载

`go-ethereum` client.blockbyhash() 给出错误“未找到”

php小编香蕉近日收到了一位读者的问题,他在使用`go-ethereum`的`client.BlockByHash()`函数时遇到了一个错误提示:“未找到”。这个问题困扰了他很久,因此他希望能够得到一些解决方案。在这篇文章中,我们将探讨可能导致这个错误的原因,并提供一些可能的解决方法。

问题内容

我有以下代码用于订阅出现的新块:

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/ethereum/go-ethereum/core/types"
    "github.com/ethereum/go-ethereum/ethclient"
)

func main() {
    client, err := ethclient.dial("wss://mainnet.infura.io/ws/v3/apikey")
    if err != nil {
        log.fatal(err)
    }

    headers := make(chan *types.header)
    sub, err := client.subscribenewhead(context.background(), headers)
    if err != nil {
        log.fatal(err)
    }

    for {
        select {
        case err := 
<p>但在队伍中</p>
<pre class="brush:php;toolbar:false;">block, err := client.blockbyhash(context.background(), header.hash())

我收到错误:

2023/04/19 17:31:14 not found
exit status 1

它仍然在 fmt.println(header.hash().hex()) 中打印哈希值,所以我知道 infura 连接正在工作。

解决方法

使用区块号而不是哈希值。

block, err := client.BlockByNumber(context.Background(), header.Number)

函数 header.hash() 不返回块哈希,而是返回 header 的哈希。

声明:本文转载于:stackoverflow,如有侵犯,请联系admin@php.cn删除