Filtering Event logs

By listening to solidity contract event logs, developers can obtain important contracts transactions information. In the store.go contract of the previous example, calling the setItem function will trigger the ItemSet event, which records the key and value parameters entered by the caller. To get the ItemSet event of the store.go contract, we need to get the topic of the ItemSet event:

itemSetTopic := crypto.Keccak256Hash([]byte("ItemSet(bytes32,bytes32)"))

Then we need to construct a event filter based on block range, contract address, and event topics:

contractAddress := common.HexToAddress("0x9aC8B849A8b6Fc14F8dEcfa6A22dB41671B38eFB")
query := phoenixchain.FilterQuery{
	FromBlock: big.NewInt(22108089),
	ToBlock:   big.NewInt(22108090),
	Addresses: []common.Address{
		contractAddress,
	},
	Topics: [][]common.Hash{{itemSetTopic}},
}

Now we can call the FilterLogs method to get events:

logs, err := client.FilterLogs(context.Background(), query)
if err != nil {
    log.Fatal(err)
}

In order to get readable logs, we need to use Store.go's StoreABI to parse the log data.

contractAbi, err := abi.JSON(strings.NewReader(string(store.StoreABI)))
if err != nil {
	log.Fatal(err)
}
for _, vLog := range logs {
	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[:]))   // storeKey
	fmt.Println(string(event.Value[:])) // storeValue
}

The complete code is as follows:

package main
import (
	store "...The path of the store.go file..."
	"context"
	"fmt"
	"log"
	"math/big"
	"strings"
	phoenixchain "github.com/PhoenixGlobal/Phoenix-Chain-SDK"
	"github.com/PhoenixGlobal/Phoenix-Chain-SDK/ethereum/accounts/abi"
	"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("https://dataseed1.phoenix.global/rpc")
	if err != nil {
		log.Fatal(err)
	}
	contractAddress := common.HexToAddress("0x9aC8B849A8b6Fc14F8dEcfa6A22dB41671B38eFB")
	itemSetTopic := crypto.Keccak256Hash([]byte("ItemSet(bytes32,bytes32)"))
	query := phoenixchain.FilterQuery{
		FromBlock: big.NewInt(22108089),
		ToBlock:   big.NewInt(22108090),
		Addresses: []common.Address{
			contractAddress,
		},
		Topics: [][]common.Hash{{itemSetTopic}},
	}
	logs, err := client.FilterLogs(context.Background(), query)
	if err != nil {
		log.Fatal(err)
	}
	contractAbi, err := abi.JSON(strings.NewReader(string(store.StoreABI)))
	if err != nil {
		log.Fatal(err)
	}
	for _, vLog := range logs {
		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[:]))   // storeKey
		fmt.Println(string(event.Value[:])) // storeValue
	}
}

Last updated