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