智能合约 | GO语言调用合约实现订阅合约的event

本文介绍了如何在Go语言中订阅和监听Ethereum智能合约的Event,包括设置过滤原则和使用WebSocket连接Geth,以便于调试合约和获取状态变化。通过举例展示了部署合约、建立连接、设置过滤器和订阅事件的详细步骤。
摘要由CSDN通过智能技术生成

theme: channing-cyan

highlight: atelier-savanna-dark

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第21天,点击查看活动详情

订阅合约的event

当我们使用GO语言调用合约时,写一个Dapp中通常需要通过监听event事件来获得合约状态内的变化,下面我们就详细的讲一下如何实现。

event作用

  • 作用一:帮助开发者进行合约调试,实现日志功能。详情链接
  • 作用二:通过监听event事件来获得合约内的状态变化,实现订阅功能。

事件订阅的前提

  • 前提一:合约内必须写了event
  • 前提二:Geth在启动时需要加参数"- ws"

ws指的是websocket,只有geth添加了此参数才能提供订阅服务。

实现过程

部署合约

我们需要部署一个带有event的合约。 - 部分代码 ```solidity event setNum(address _owner,uint _num);

function setNum(uint256 num)public{ ···· emit setNum(msg.sender,num); } ```

导入go-ethereum包

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

用ws的方式连接到geth

```go func GetClient() (*ethclient.Client, error) { //使用ws的方式连接geth client, err := ethclient.Dial("ws://127.0.0.1:7545") //client, err := ethclient.Dial("ws://rinkeby.etherscan.io")

if err != nil { log.Fatal(err) } defer client.Close() return client, nil } ```

设置过滤原则

为了后面的订阅函数,我们需要借助ethereum.FilerQuery的结构设计原则 - 部分代码

```go //addressName为监控的合约地址 conAddr :=common.HexToAddress("addressName") //eventName为event的函数名称,也就是需要监控的话题,表示将该名称转换为hash值 topicHash:=crypto.Keccak256Hash([]byte("eventName"))

//过滤处理 query :=ethereum.FilerQuery{ Addresses: []common.Address(conAddr), Topics: [][]common.Hash({topicHash}), } ```

订阅事件

我们需要使用到Client结构体中的SubscribeFilterLogs方法 - 原型 // SubscribeFilterLogs subscribes to the results of a streaming filter query. // ctx:上下文信息 // q:我们自行构造的过滤条件 // ch:订阅消息的通道接受 func (ec *Client) SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) { arg, err := toFilterArg(q) if err != nil { return nil, err } return ec.c.EthSubscribe(ctx, ch, "logs", arg) }

代码示例

SubscribeFilterLogs函数订阅会有一个返回值,它的Err()也是一个channel也是一个类型元素。因此我们需要监控多个channel,我认为使用select关键字是最好的方式。 ```go //创建日志通道,订阅数据通过此通道写入 logs := make(chan types.Log) //订阅 sub,err := conn.SubscribeFilterLogs(context.Background(),query,logs)

if err!=nil{
     fmt.Println("失败",err)
     return
}

// 消息的接受以及处理 for{ //select阻塞监控多个channel //任意一个channel有消息则解除阻塞,并且执行case内的channel select{ case err:=<-subErr()" fmt.Println(err) case cLog:=<-logs: data,err:=cLog.,arshalJSON() fmt.Printlb(string(data),err) } } ```

执行

最后执行能够触发event的函数,然后观看打印的data信息,当我们将前两组的0去掉,剩下的就是合约调用者的地址。如果我们把后两组的的0去掉,再将其转换成10进制(需要分析数据格式),就能看到调用者输入的参数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值