Skip to content

Instantly share code, notes, and snippets.

@kallydev
Created February 5, 2022 09:54
Show Gist options
  • Save kallydev/f66c8825c125f2799cf74cdd52d6f817 to your computer and use it in GitHub Desktop.
Save kallydev/f66c8825c125f2799cf74cdd52d6f817 to your computer and use it in GitHub Desktop.
package subscriber
import (
"context"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/go-redis/redis/v8"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
type Subscriber struct {
Endpoint string
Chain string
RedisAddress string
RedisPassword string
ctx context.Context
redisClient *redis.Client
ethereumClient *ethclient.Client
}
func (s *Subscriber) InitializeRedisClient() error {
redisClient := redis.NewClient(&redis.Options{
Addr: s.RedisAddress,
Password: s.RedisPassword,
})
if _, err := redisClient.Ping(context.Background()).Result(); err != nil {
return err
}
s.redisClient = redisClient
logrus.Infoln("Connected to Redis")
return nil
}
func (s *Subscriber) InitializeEthereumClient() error {
ethereumClient, err := ethclient.Dial(s.Endpoint)
if err != nil {
return err
}
s.ethereumClient = ethereumClient
logrus.Infoln("Connected to Ethereum WebSocket provider")
return nil
}
func (s *Subscriber) Run() error {
headerCh := make(chan *types.Header)
subscription, err := s.ethereumClient.SubscribeNewHead(s.ctx, headerCh)
if err != nil {
return err
}
defer subscription.Unsubscribe()
for {
select {
case err := <-subscription.Err():
return err
case header := <-headerCh:
block, err := s.ethereumClient.BlockByHash(s.ctx, header.Hash())
if err != nil {
logrus.Errorln(err)
continue
}
logrus.Infoln(block.Number())
}
}
}
func NewSubscriberCommand(ctx context.Context) *cobra.Command {
subscriber := &Subscriber{
ctx: ctx,
}
command := &cobra.Command{
Use: "subscriber",
Run: func(cmd *cobra.Command, args []string) {
if err := subscriber.InitializeRedisClient(); err != nil {
logrus.Fatalln(err)
}
if err := subscriber.InitializeEthereumClient(); err != nil {
logrus.Fatalln(err)
}
if err := subscriber.Run(); err != nil {
logrus.Fatalln(err)
}
},
}
command.Flags().StringVar(&subscriber.Chain, "chain", "ethereum-main", "")
command.Flags().StringVar(&subscriber.Endpoint, "endpoint", "", "")
command.Flags().StringVar(&subscriber.RedisAddress, "redis-address", "127.0.0.1:6379", "")
command.Flags().StringVar(&subscriber.RedisPassword, "redis-password", "", "")
return command
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment