feat: implement handler interface, add example emitter (stdout)

This commit is contained in:
2024-04-16 13:14:21 +08:00
parent 49feb5bd2e
commit 343f304eaf
8 changed files with 141 additions and 45 deletions

View File

@@ -0,0 +1,27 @@
package handler
import (
"context"
"github.com/celo-org/celo-blockchain/core/types"
"github.com/grassrootseconomics/w3-celo"
)
type (
EmitterEmitFunc func(context.Context, []byte) error
Handler interface {
Handle(context.Context, *types.Log, EmitterEmitFunc) error
}
)
func New() []Handler {
transferHandler := &TransferHandler{
topicHash: w3.H("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"),
event: w3.MustNewEvent("Transfer(address indexed _from, address indexed _to, uint256 _value)"),
}
return []Handler{
transferHandler,
}
}

View File

@@ -0,0 +1,55 @@
package handler
import (
"context"
"encoding/json"
"math/big"
"github.com/celo-org/celo-blockchain/common"
"github.com/celo-org/celo-blockchain/core/types"
"github.com/grassrootseconomics/w3-celo"
)
type (
TransferHandler struct {
topicHash common.Hash
event *w3.Event
}
TransferEvent struct {
Contract string
From string
To string
Value uint64
}
)
func (h *TransferHandler) Handle(ctx context.Context, log *types.Log, emitFn EmitterEmitFunc) error {
if log.Topics[0] == h.topicHash {
var (
from common.Address
to common.Address
value big.Int
)
if err := h.event.DecodeArgs(log, &from, &to, &value); err != nil {
return err
}
transferEvent := &TransferEvent{
Contract: log.Address.Hex(),
From: from.Hex(),
To: to.Hex(),
Value: value.Uint64(),
}
jsonData, err := json.Marshal(transferEvent)
if err != nil {
return err
}
return emitFn(ctx, jsonData)
}
return nil
}