2022-05-03 17:54:51 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"github.com/georgysavva/scany/pgxscan"
|
|
|
|
"github.com/hibiken/asynq"
|
|
|
|
"github.com/jackc/pgx/v4"
|
|
|
|
"github.com/lmittmann/w3"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
|
|
"math/big"
|
|
|
|
"strconv"
|
|
|
|
)
|
|
|
|
|
|
|
|
type tokenCursor struct {
|
|
|
|
CursorPos string `db:"cursor_pos"`
|
|
|
|
}
|
|
|
|
|
2022-05-05 14:01:34 +02:00
|
|
|
func tokenSyncer(ctx context.Context, t *asynq.Task) error {
|
2022-05-03 17:54:51 +02:00
|
|
|
var lastCursor tokenCursor
|
|
|
|
|
2022-05-05 14:01:34 +02:00
|
|
|
if err := pgxscan.Get(ctx, db, &lastCursor, queries["cursor-pos"], 3); err != nil {
|
2022-05-03 17:54:51 +02:00
|
|
|
return err
|
|
|
|
}
|
2022-05-05 14:01:34 +02:00
|
|
|
latestChainIdx, err := cicnetClient.EntryCount(ctx)
|
2022-05-03 17:54:51 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
lastCursorPos, err := strconv.ParseInt(lastCursor.CursorPos, 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
latestChainPos := latestChainIdx.Int64() - 1
|
2022-05-03 20:37:48 +02:00
|
|
|
log.Info().Msgf("=> %d tokens synced", lastCursorPos)
|
2022-05-03 17:54:51 +02:00
|
|
|
if latestChainPos >= lastCursorPos {
|
|
|
|
batch := &pgx.Batch{}
|
|
|
|
|
|
|
|
for i := lastCursorPos; i <= latestChainPos; i++ {
|
2022-05-05 14:01:34 +02:00
|
|
|
nextTokenAddress, err := cicnetClient.AddressAtIndex(ctx, big.NewInt(i))
|
2022-05-03 17:54:51 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-05-05 14:01:34 +02:00
|
|
|
tokenInfo, err := cicnetClient.TokenInfo(ctx, w3.A(nextTokenAddress))
|
2022-05-03 17:54:51 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-05-05 14:01:34 +02:00
|
|
|
batch.Queue(queries["insert-token-data"], nextTokenAddress[2:], tokenInfo.Name, tokenInfo.Symbol, tokenInfo.Decimals.Int64())
|
2022-05-03 17:54:51 +02:00
|
|
|
}
|
|
|
|
|
2022-05-05 14:01:34 +02:00
|
|
|
res := db.SendBatch(ctx, batch)
|
2022-05-03 17:54:51 +02:00
|
|
|
for i := 0; i < batch.Len(); i++ {
|
|
|
|
_, err := res.Exec()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
err := res.Close()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-05-05 14:01:34 +02:00
|
|
|
_, err = db.Exec(ctx, queries["update-cursor"], strconv.FormatInt(latestChainIdx.Int64(), 10), 3)
|
2022-05-03 17:54:51 +02:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|