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?
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()
}