You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.8 KiB

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