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.

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