-
Notifications
You must be signed in to change notification settings - Fork 242
/
price.go
98 lines (80 loc) · 2.09 KB
/
price.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package wallet
import (
"context"
"database/sql"
"fmt"
"github.com/status-im/status-go/services/wallet/thirdparty"
)
type PricesPerTokenAndCurrency = map[string]map[string]float64
type PriceManager struct {
db *sql.DB
cryptoCompare *thirdparty.CryptoCompare
}
func NewPriceManager(db *sql.DB, cryptoCompare *thirdparty.CryptoCompare) *PriceManager {
return &PriceManager{db: db, cryptoCompare: cryptoCompare}
}
func (pm *PriceManager) FetchPrices(symbols []string, currencies []string) (PricesPerTokenAndCurrency, error) {
result, err := pm.cryptoCompare.FetchPrices(symbols, currencies)
if err != nil {
return nil, err
}
if err = pm.updatePriceCache(result); err != nil {
return nil, err
}
return result, nil
}
func (pm *PriceManager) updatePriceCache(prices PricesPerTokenAndCurrency) error {
tx, err := pm.db.BeginTx(context.Background(), &sql.TxOptions{})
if err != nil {
return err
}
defer func() {
if err == nil {
err = tx.Commit()
return
}
// don't shadow original error
_ = tx.Rollback()
}()
insert, err := tx.Prepare(`INSERT OR REPLACE INTO price_cache
(token, currency, price)
VALUES
(?, ?, ?)`)
if err != nil {
return err
}
for token, pricesPerCurrency := range prices {
for currency, price := range pricesPerCurrency {
_, err = insert.Exec(token, currency, fmt.Sprintf("%f", price))
if err != nil {
return err
}
}
}
return nil
}
func getCachedPricesFromDBRows(rows *sql.Rows) (PricesPerTokenAndCurrency, error) {
prices := make(PricesPerTokenAndCurrency)
for rows.Next() {
var token string
var currency string
var price float64
if err := rows.Scan(&token, ¤cy, &price); err != nil {
return nil, err
}
_, present := prices[token]
if !present {
prices[token] = map[string]float64{}
}
prices[token][currency] = price
}
return prices, nil
}
func (pm *PriceManager) GetCachedPrices() (PricesPerTokenAndCurrency, error) {
rows, err := pm.db.Query("SELECT token, currency, price FROM price_cache")
if err != nil {
return nil, err
}
defer rows.Close()
return getCachedPricesFromDBRows(rows)
}