Skip to content

Commit

Permalink
chore: init cosmos-notifyer
Browse files Browse the repository at this point in the history
  • Loading branch information
albttx committed Nov 10, 2022
0 parents commit ce16145
Show file tree
Hide file tree
Showing 16 changed files with 1,705 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
config.yml
15 changes: 15 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
FROM golang:1.19-alpine as builder

COPY . /go/src/app

WORKDIR /go/src/app

RUN go build ./cmd/cosmos-notifyer


FROM alpine

COPY --from=builder /go/src/app/cosmos-notifyer /bin/cosmos-notifyer

ENTRYPOINT [ "/bin/cosmos-notifyer" ]
CMD [ "start" ]
11 changes: 11 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@

build:
go build ./cmd/cosmos-notifyer

docker-deploy: docker-build docker-push

docker-build:
docker build -t nysanetwork/cosmos-notifyer .

docker-push:
docker push nysanetwork/cosmos-notifyer
140 changes: 140 additions & 0 deletions cmd/cosmos-notifyer/cli_start.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
package main

import (
"context"
"sync"
"time"

"nysa-network/internal/ctxlogger"
"nysa-network/pkg/cosmosblocks"
"nysa-network/pkg/notifyer"

"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
)

func (s *service) Start(cctx *cli.Context) error {
s.notify = notifyer.NewClient(notifyer.Config{
DiscordWebhook: s.cfg.Notifications.Discord.Webhook,
})

wg := sync.WaitGroup{}

for _, chain := range s.cfg.Chains {
wg.Add(1)

go func(chain Chain) {
defer wg.Done()

s.startWatcher(chain)
}(chain)
}
wg.Wait()
return nil
}

func (s *service) startWatcher(chain Chain) {
for {
for _, rpc := range chain.RPC {
ctx, cancelFunc := context.WithCancel(context.Background())

ctx = ctxlogger.WithValue(ctx, "chain", chain.Name)
ctx = ctxlogger.WithValue(ctx, "rpc", rpc)

l := ctxlogger.Logger(ctx)

c := cosmosblocks.NewClient(cosmosblocks.Config{
RPCEndpoint: rpc,
Logger: l,
})

go s.blockHandler(ctx, c, chain)

if err := c.Start(ctx); err != nil {
l.WithError(err).Error()
}
cancelFunc()
}
}

}

func (s *service) blockHandler(ctx context.Context, c *cosmosblocks.Client, chain Chain) {
l := ctxlogger.Logger(ctx)

latestBlockTime := time.Now()
var latestBlockHeight int64 = 0

go func(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
default:
if len(c.BlockCh) == cap(c.BlockCh) {
l.Error("Block channel is full !!")
}
if time.Since(latestBlockTime) > time.Second*30 {
l.Error("no block received since 30s")
}
time.Sleep(time.Second * 10)
}
}
}(ctx)

for {
select {
case <-ctx.Done():
return
case block, ok := <-c.BlockCh:
if !ok {
continue
}
latestBlockTime = time.Now()
if latestBlockHeight != 0 && (block.GetHeight()-latestBlockHeight) > 1 {
l.Errorf("missed block from %d to %d", latestBlockHeight, block.GetHeight())
}
latestBlockHeight = block.GetHeight()

// Check delegations messages
for _, msg := range block.GetMsgDelegate() {
if chain.ValidatorAddr == msg.ValoperAddr {
amount := msg.GetAmount() / float64(chain.GetTokenCoefficient())
if amount > chain.Notification.MinimumDelegation {
err := s.notify.Delegation(notifyer.DelegationMsg{
Amount: amount,
Token: chain.Token.Label,
})
if err != nil {
l.WithError(err).WithFields(logrus.Fields{
"msg": msg,
"amount": amount,
"token": chain.Token.Label,
}).Error("Failed to send delegation message")
}
}
}
}

// Check for undelegations
for _, msg := range block.GetMsgUndelegate() {
if chain.ValidatorAddr == msg.ValoperAddr {
amount := msg.GetAmount() / float64(chain.GetTokenCoefficient())
if amount > chain.Notification.MinimumDelegation {
err := s.notify.UnDelegation(notifyer.UnDelegationMsg{
Amount: amount,
Token: chain.Token.Label,
})
if err != nil {
l.WithError(err).WithFields(logrus.Fields{
"msg": msg,
"amount": amount,
"token": chain.Token.Label,
}).Error("Failed to send undelegation message")
}
}
}
}
}
}
}
33 changes: 33 additions & 0 deletions cmd/cosmos-notifyer/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package main

type Config struct {
Chains []Chain `yaml:"chains"`

Notifications struct {
Discord *struct {
Webhook string `yaml:"webhook"`
} `yaml:"discord"`
} `yaml:"notifications"`
}

type Chain struct {
Name string `yaml:"name"`
ValidatorAddr string `yaml:"validator_address"`
RPC []string `yaml:"rpc"`

Token struct {
Label string `yaml:"label"`
Coefficient int `yaml:"coefficient"`
} `yaml:"token"`

Notification struct {
MinimumDelegation float64 `yaml:"minimum_delegation"`
} `yaml:"notification"`
}

func (c Chain) GetTokenCoefficient() int {
if c.Token.Coefficient == 0 {
return 1000000
}
return c.Token.Coefficient
}
65 changes: 65 additions & 0 deletions cmd/cosmos-notifyer/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package main

import (
"fmt"
"log"
"net/http"
_ "net/http/pprof"
"os"

"nysa-network/pkg/notifyer"

"github.com/urfave/cli/v2"
"gopkg.in/yaml.v3"
)

type service struct {
cfg *Config

notify *notifyer.Client
}

func (s *service) parseConfig(c *cli.Context) error {
data, err := os.ReadFile(c.String("config"))
if err != nil {
return err
}

if err := yaml.Unmarshal(data, &s.cfg); err != nil {
return err
}
return nil
}

func main() {
go func() {
fmt.Println(http.ListenAndServe("localhost:6060", nil))
}()
s := service{}

globalFlags := []cli.Flag{
&cli.StringFlag{
Name: "config",
Aliases: []string{"c"},
Value: "config.yml",
Usage: "Application config file `PATH`",
},
}

app := &cli.App{
Commands: []*cli.Command{
{
Name: "start",
Usage: "start cosmos-notifyer server",
Action: s.Start,
Flags: globalFlags,
Before: s.parseConfig,
},
},
}
app.Flags = globalFlags

if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
18 changes: 18 additions & 0 deletions cmd/cosmos-notifyer/types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package main

type (
Event struct {
Type string `bson:"type"`
Attributes []KvPair `bson:"attributes"`
}

KvPair struct {
Key string `bson:"key"`
Value string `bson:"value"`
}

EventNew struct {
MsgIndex int `bson:"msg_index" json:"msg_index"`
Events []Event `bson:"events"`
}
)
5 changes: 5 additions & 0 deletions config.example.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
chains:
- name: juno
rpc:
- http://localhost:26657
89 changes: 89 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
module nysa-network

go 1.19

require (
github.com/cosmos/cosmos-sdk v0.45.9
github.com/gtuk/discordwebhook v1.0.2
github.com/juju/errors v1.0.0
github.com/sirupsen/logrus v1.9.0
github.com/tendermint/tendermint v0.34.22
github.com/urfave/cli/v2 v2.23.0
gopkg.in/yaml.v3 v3.0.1
)

require (
github.com/99designs/keyring v1.2.1 // indirect
github.com/armon/go-metrics v0.4.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/btcsuite/btcd v0.22.1 // indirect
github.com/cespare/xxhash v1.1.0 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/confio/ics23/go v0.7.0 // indirect
github.com/cosmos/btcutil v1.0.4 // indirect
github.com/cosmos/gorocksdb v1.2.0 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dgraph-io/badger/v2 v2.2007.4 // indirect
github.com/dgraph-io/ristretto v0.1.0 // indirect
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect
github.com/dustin/go-humanize v1.0.0 // indirect
github.com/fsnotify/fsnotify v1.5.4 // indirect
github.com/go-kit/kit v0.12.0 // indirect
github.com/go-kit/log v0.2.1 // indirect
github.com/go-logfmt/logfmt v0.5.1 // indirect
github.com/gogo/protobuf v1.3.3 // indirect
github.com/golang/glog v1.0.0 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/btree v1.0.0 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/gtank/merlin v0.1.1 // indirect
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
github.com/hashicorp/golang-lru v0.5.5-0.20210104140557-80c98217689d // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hdevalence/ed25519consensus v0.0.0-20220222234857-c00d1f31bab3 // indirect
github.com/inconshreveable/mousetrap v1.0.1 // indirect
github.com/jmhodges/levigo v1.0.0 // indirect
github.com/klauspost/compress v1.15.9 // indirect
github.com/libp2p/go-buffer-pool v0.1.0 // indirect
github.com/magiconair/properties v1.8.6 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect
github.com/mimoo/StrobeGo v0.0.0-20210601165009-122bf33a46e0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pelletier/go-toml v1.9.5 // indirect
github.com/pelletier/go-toml/v2 v2.0.5 // indirect
github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/prometheus/client_golang v1.12.2 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.34.0 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/sasha-s/go-deadlock v0.3.1 // indirect
github.com/spf13/afero v1.8.2 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/cobra v1.5.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.13.0 // indirect
github.com/subosito/gotenv v1.4.1 // indirect
github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7 // indirect
github.com/tendermint/go-amino v0.16.0 // indirect
github.com/tendermint/tm-db v0.6.7 // indirect
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
go.etcd.io/bbolt v1.3.6 // indirect
golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa // indirect
golang.org/x/exp v0.0.0-20221028150844-83b7d23a625f // indirect
golang.org/x/net v0.0.0-20220812174116-3211cb980234 // indirect
golang.org/x/sys v0.1.0 // indirect
golang.org/x/text v0.3.7 // indirect
google.golang.org/genproto v0.0.0-20220815135757-37a418bb8959 // indirect
google.golang.org/grpc v1.50.0 // indirect
google.golang.org/protobuf v1.28.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)

replace github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1
Loading

0 comments on commit ce16145

Please sign in to comment.