tracker

package
v0.0.0-...-01e1646 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 1, 2023 License: MPL-2.0 Imports: 19 Imported by: 0

README

Tracker

package main

import (
	"context"
	"encoding/binary"
	"flag"
	"fmt"
	"os"
	"os/signal"
	"syscall"

	"github.com/umbracle/ethgo"
	"github.com/umbracle/ethgo/abi"
	"github.com/umbracle/ethgo/jsonrpc"
	"github.com/umbracle/ethgo/tracker"

	boltdbStore "github.com/umbracle/ethgo/tracker/store/boltdb"
)

var depositEvent = abi.MustNewEvent(`DepositEvent(
	bytes pubkey,
	bytes whitdrawalcred,
	bytes amount,
	bytes signature,
	bytes index
)`)

func main() {
	var endpoint string
	var target string

	flag.StringVar(&endpoint, "endpoint", "", "")
	flag.StringVar(&target, "target", "", "")

	flag.Parse()

	provider, err := jsonrpc.NewClient(endpoint)
	if err != nil {
		fmt.Printf("[ERR]: %v", err)
		os.Exit(1)
	}

	store, err := boltdbStore.New("deposit.db")
	if err != nil {
		fmt.Printf("[ERR]: failted to start store %v", err)
		os.Exit(1)
	}

	tt, err := tracker.NewTracker(provider.Eth(),
		tracker.WithBatchSize(20000),
		tracker.WithStore(store),
		tracker.WithEtherscan(os.Getenv("ETHERSCAN_APIKEY")),
		tracker.WithFilter(&tracker.FilterConfig{
			Async: true,
			Address: []ethgo.Address{
				ethgo.HexToAddress(target),
			},
		}),
	)
	if err != nil {
		fmt.Printf("[ERR]: failed to create the tracker %v", err)
		os.Exit(1)
	}

	lastBlock, err := tt.GetLastBlock()
	if err != nil {
		fmt.Printf("[ERR]: failed to get last block %v", err)
		os.Exit(1)
	}
	if lastBlock != nil {
		fmt.Printf("Last block processed: %d\n", lastBlock.Number)
	}

	ctx, cancelFn := context.WithCancel(context.Background())
	go func() {
		go func() {
			if err := tt.Sync(ctx); err != nil {
				fmt.Printf("[ERR]: %v", err)
			}
		}()

		go func() {
			for {
				select {
				case evnt := <-tt.EventCh:
					for _, log := range evnt.Added {
						if depositEvent.Match(log) {
							vals, err := depositEvent.ParseLog(log)
							if err != nil {
								panic(err)
							}

							index := binary.LittleEndian.Uint64(vals["index"].([]byte))
							amount := binary.LittleEndian.Uint64(vals["amount"].([]byte))

							fmt.Printf("Deposit: Block %d Index %d Amount %d\n", log.BlockNumber, index, amount)
						}
					}
				case <-tt.DoneCh:
					fmt.Println("historical sync done")
				}
			}
		}()

	}()

	handleSignals(cancelFn)
}

func handleSignals(cancelFn context.CancelFunc) int {
	signalCh := make(chan os.Signal, 4)
	signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)

	<-signalCh

	gracefulCh := make(chan struct{})
	go func() {
		cancelFn()
		close(gracefulCh)
	}()

	select {
	case <-signalCh:
		return 1
	case <-gracefulCh:
		return 0
	}
}

You can query the ETH2.0 Deposit contract like so:

go run main.go --endpoint https://mainnet.infura.io/v3/... --target 0x00000000219ab540356cbb839cbe05303d7705fa

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BlockEvent

type BlockEvent struct {
	Type    EventType
	Added   []*core.Block
	Removed []*core.Block
}

BlockEvent is an event emitted when a new block is included

type Config

type Config struct {
	BatchSize       uint64
	BlockTracker    *blocktracker.BlockTracker // move to interface
	EtherscanAPIKey string
	Filter          *FilterConfig
	Store           store.Store
}

Config is the configuration of the tracker

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns the default tracker config

type ConfigOption

type ConfigOption func(*Config)

func WithBatchSize

func WithBatchSize(b uint64) ConfigOption

func WithBlockTracker

func WithBlockTracker(b *blocktracker.BlockTracker) ConfigOption

func WithEtherscan

func WithEtherscan(k string) ConfigOption

func WithFilter

func WithFilter(f *FilterConfig) ConfigOption

func WithStore

func WithStore(s store.Store) ConfigOption

type Event

type Event struct {
	Type    EventType
	Added   []*core.Log
	Removed []*core.Log
}

Event is an event emitted when a new log is included

type EventType

type EventType int

EventType is the type of the event

const (
	// EventAdd happens when a new event is included in the chain
	EventAdd EventType = iota
	// EventDel may happen when there is a reorg and a past event is deleted
	EventDel
)

type FilterConfig

type FilterConfig struct {
	Address []core.Address `json:"address"`
	Topics  [][]*core.Hash `json:"topics"`
	Start   uint64
	Hash    string
	Async   bool
}

FilterConfig is a tracker filter configuration

type Provider

type Provider interface {
	BlockNumber() (uint64, error)
	GetBlockByHash(hash core.Hash, full bool) (*core.Block, error)
	GetBlockByNumber(i core.BlockNumber, full bool) (*core.Block, error)
	GetLogs(filter *core.LogFilter) ([]*core.Log, error)
	ChainID() (*big.Int, error)
}

Provider are the eth1x methods required by the tracker

type Tracker

type Tracker struct {
	BlockCh chan *blocktracker.BlockEvent
	ReadyCh chan struct{}
	SyncCh  chan uint64
	EventCh chan *Event
	DoneCh  chan struct{}
	// contains filtered or unexported fields
}

Tracker is a contract event tracker

func NewTracker

func NewTracker(provider Provider, opts ...ConfigOption) (*Tracker, error)

NewTracker creates a new tracker

func (*Tracker) BatchSync

func (t *Tracker) BatchSync(ctx context.Context) error

func (*Tracker) Entry

func (t *Tracker) Entry() store.Entry

func (*Tracker) GetLastBlock

func (t *Tracker) GetLastBlock() (*core.Block, error)

GetLastBlock returns the last block processed for this filter

func (*Tracker) IsSynced

func (t *Tracker) IsSynced() bool

IsSynced returns true if the filter is synced to head

func (*Tracker) Sync

func (t *Tracker) Sync(ctx context.Context) error

Sync syncs a specific filter

func (*Tracker) Wait

func (t *Tracker) Wait()

Wait waits the filter to finish

func (*Tracker) WaitDuration

func (t *Tracker) WaitDuration(dur time.Duration) error

WaitDuration waits for the filter to finish up to duration

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL