Subscribing to Event Logs

We can call the SubscribeFilterLogs method to listen contract event logs in real time. To subscribe to event logs, we need to use the websocket URL.

package main
import (
	store "...The path of the store.go file..."
	"context"
	"fmt"
	"log"
	"strings"
	phoenixchain "github.com/PhoenixGlobal/Phoenix-Chain-SDK"
	"github.com/PhoenixGlobal/Phoenix-Chain-SDK/ethereum/accounts/abi"
	"github.com/PhoenixGlobal/Phoenix-Chain-SDK/ethereum/core/types"
	"github.com/PhoenixGlobal/Phoenix-Chain-SDK/ethereum/ethclient"
	"github.com/PhoenixGlobal/Phoenix-Chain-SDK/libs/common"
	"github.com/PhoenixGlobal/Phoenix-Chain-SDK/libs/crypto"
)
func main() {
	client, err := ethclient.Dial("ws://dataseed1.phoenix.global/wss")
	if err != nil {
		log.Fatal(err)
	}
	contractAddress := common.HexToAddress("0x9aC8B849A8b6Fc14F8dEcfa6A22dB41671B38eFB")
	itemSetTopic := crypto.Keccak256Hash([]byte("ItemSet(bytes32,bytes32)"))
	query := phoenixchain.FilterQuery{
		Addresses: []common.Address{
			contractAddress,
		},
		Topics: [][]common.Hash{{itemSetTopic}},
	}
	logs := make(chan types.Log)
	sub, err := client.SubscribeFilterLogs(context.Background(), query, logs)
	if err != nil {
		log.Fatal(err)
	}
	for {
		select {
		case err := <-sub.Err():
			log.Fatal(err)
		case vLog := <-logs:
			contractAbi, err := abi.JSON(strings.NewReader(string(store.StoreABI)))
			if err != nil {
				log.Fatal(err)
			}
			event := struct {
				Key   [32]byte
				Value [32]byte
			}{}
			err = contractAbi.Unpack(&event, "ItemSet", vLog.Data)
			if err != nil {
				log.Fatal(err)
			}
			fmt.Println(string(event.Key[:]))  
			fmt.Println(string(event.Value[:])) 
		}
	}
}

Last updated