第5节:订阅事件

小白入门:https://github.com/dukedaily/solidity-expert ,欢迎star转发,文末加V入群。

职场进阶: https://dukeweb3.com

  1. 更新地址contractAddr
  2. 启动程序
  3. 发起交易,产生事件
  4. 查看事件
package main

import (
    utils "code/main/utils"
    "context"
    "fmt"
    "log"

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

func main() {
  // 一定要是
    client, err := ethclient.Dial(utils.GoerliWSS)
    if err != nil {
        log.Fatal("Dial err:", err)
    }

    // 1. 准备合约地址
    contractAddr := "0xe4a220e0bd37673a90e2114abc98e4a22445c32e"
    address := common.HexToAddress(contractAddr)

    // 2. 构造监听请求
    query := ethereum.FilterQuery{
        Addresses: []common.Address{address},
        // FromBlock: new(big.Int).SetUint64(0),
        // ToBlock:   new(big.Int).SetUint64(1),
    }

    // 3. 订阅事件
    logs := make(chan types.Log)
    sub, err := client.SubscribeFilterLogs(context.Background(), query, logs)
    if err != nil {
        log.Fatal(err)
    }

  // 4. 监听事件
    for {
        fmt.Println("ready to listen...")
        select {
        case err := <-sub.Err():
            log.Fatal(err)
        case vLog := <-logs:
            fmt.Println(vLog)
        }
    }
}

执行结果,点击查看

image-20221202165200028