arnaucube
arnaucube/hermez-nodePublic Self-hosted repository
hermez-node/priceupdater/priceupdater.go
priceupdater/priceupdater.goRaw
 1package priceupdater
 2
 3import (
 4	"net/http"
 5	"strconv"
 6	"time"
 7
 8	"github.com/dghubble/sling"
 9	"github.com/hermeznetwork/hermez-node/db/historydb"
10	"github.com/hermeznetwork/hermez-node/log"
11	"github.com/hermeznetwork/tracerr"
12)
13
14const (
15	defaultMaxIdleConns    = 10
16	defaultIdleConnTimeout = 10
17)
18
19// PriceUpdater definition
20type PriceUpdater struct {
21	db           *historydb.HistoryDB
22	apiURL       string
23	tokenSymbols []string
24}
25
26// NewPriceUpdater is the constructor for the updater
27func NewPriceUpdater(apiURL string, db *historydb.HistoryDB) PriceUpdater {
28	tokenSymbols := []string{}
29	return PriceUpdater{
30		db:           db,
31		apiURL:       apiURL,
32		tokenSymbols: tokenSymbols,
33	}
34}
35
36// UpdatePrices is triggered by the Coordinator, and internally will update the token prices in the db
37func (p *PriceUpdater) UpdatePrices() {
38	tr := &http.Transport{
39		MaxIdleConns:       defaultMaxIdleConns,
40		IdleConnTimeout:    defaultIdleConnTimeout * time.Second,
41		DisableCompression: true,
42	}
43	httpClient := &http.Client{Transport: tr}
44	client := sling.New().Base(p.apiURL).Client(httpClient)
45
46	state := [10]float64{}
47
48	for _, tokenSymbol := range p.tokenSymbols {
49		resp, err := client.New().Get("ticker/t" + tokenSymbol + "USD").ReceiveSuccess(&state)
50		errString := tokenSymbol + " not updated, error: "
51		if err != nil {
52			log.Error(errString + err.Error())
53			continue
54		}
55		if resp.StatusCode != http.StatusOK {
56			log.Error(errString + "response is not 200, is " + strconv.Itoa(resp.StatusCode))
57			continue
58		}
59		err = p.db.UpdateTokenValue(tokenSymbol, state[6])
60		if err != nil {
61			log.Error(errString + err.Error())
62		}
63	}
64}
65
66// UpdateTokenList get the registered token symbols from HistoryDB
67func (p *PriceUpdater) UpdateTokenList() error {
68	tokenSymbols, err := p.db.GetTokenSymbols()
69	if err != nil {
70		return tracerr.Wrap(err)
71	}
72	p.tokenSymbols = tokenSymbols
73	return nil
74}