英文:
dynamic extend of subscribed topics of ethereum event log
问题
我正在使用go-ethereum来监听智能合约的某个主题的事件,代码如下:
import "github.com/ethereum/go-ethereum/ethclient"
logs := make(chan types.Log)
client, _ := ethclient.Dial("wss://rinkeby.infura.io/ws/v3/{projectid}")
var hashes []common.Hash
sub, _ := client.SubscribeFilterLogs(context.Background(), ethereum.FilterQuery{
Addresses: []common.Address{contractAddress},
Topics: [][]common.Hash{hashes},
}, logs)
然后,匹配的日志将被写入变量logs中。
在运行时,有没有一种方法可以扩展我订阅的主题列表?我想构建一个REST服务,可以接收包含新主题的订阅请求。
还是说我需要启动一个新的订阅?
英文:
I am using go-ethereum for listening to events of a certian topic of a smart contract like this:
import "github.com/ethereum/go-ethereum/ethclient"
logs := make(chan types.Log)
client, _ := ethclient.Dial("wss://rinkeby.infura.io/ws/v3/{projectid}")
var hashes []common.Hash
sub, _ := client.SubscribeFilterLogs(context.Background(), ethereum.FilterQuery{
Addresses: []common.Address{contractAddress},
Topics: [][]common.Hash{hashes},
}, logs)
then I get the matching logs written into the variable logs.
Is there a way to extend the list of topics I subscribed too at runtime?
I want to build a REST service which can get requests containing new topics to subscribe to.
Or do I need to start a new subscribtion then?
答案1
得分: 0
我一直在测试这个,因为我找不到一个好的答案。
你可以创建一些用于订阅管理的方法,其中一个方法用于向你的哈希数组中添加/删除哈希,该方法还将调用订阅的.Unsubscribe()方法,然后使用新列表重新初始化。可能看起来像这样:
var hashes []common.Hash
var subscription ethereum.Subscription
func createSubscription(){
if subscription != nil && len(hashes > 0){
subscription.Unsubscribe()
// 创建订阅的逻辑
// 重新赋值给subscription变量
} else if len(hashes > 0) {
// 正常创建订阅,赋值给subscription变量
}
}
func appendHash(common.Hash hash){
hashes = append(hashes, hash)
createSubscription()
}
英文:
I've been testing this as I couldn't find a good answer.
You could create a some methods for subscription management, having a method for appending / removing hashes from your hashes array, which would also call the .Unsubscribe() method of your subscription, and then reinitialize with the new list. Could look something like this:
var hashes []common.Hash
var subscription ethereum.Subscription
func createSubscription(){
if subscription != nil && len(hashes > 0){
subscription.Unsubscribe()
// your logic for creating a subscription
// re-assign to subscription variable
} else if len(hashes > 0) {
// create subscription as normal, assign to subscription variable
}
}
func appendHash(common.Hash hash){
hashes = append(hashes, hash)
createSubscription()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论