-
Notifications
You must be signed in to change notification settings - Fork 248
/
reader.go
286 lines (252 loc) · 8.18 KB
/
reader.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package wallet
import (
"context"
"math"
"math/big"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/event"
"github.com/status-im/status-go/multiaccounts/accounts"
"github.com/status-im/status-go/rpc"
"github.com/status-im/status-go/services/wallet/async"
"github.com/status-im/status-go/services/wallet/chain"
"github.com/status-im/status-go/services/wallet/thirdparty"
"github.com/status-im/status-go/services/wallet/token"
"github.com/status-im/status-go/services/wallet/walletevent"
)
// WalletTickReload emitted every 15mn to reload the wallet balance and history
const EventWalletTickReload walletevent.EventType = "wallet-tick-reload"
const EventWalletTickCheckConnected walletevent.EventType = "wallet-tick-check-connected"
func getFixedCurrencies() []string {
return []string{"USD"}
}
func NewReader(rpcClient *rpc.Client, tokenManager *token.Manager, priceManager *PriceManager, cryptoCompare *thirdparty.CryptoCompare, accountsDB *accounts.Database, walletFeed *event.Feed) *Reader {
return &Reader{rpcClient, tokenManager, priceManager, cryptoCompare, accountsDB, walletFeed, nil}
}
type Reader struct {
rpcClient *rpc.Client
tokenManager *token.Manager
priceManager *PriceManager
cryptoCompare *thirdparty.CryptoCompare
accountsDB *accounts.Database
walletFeed *event.Feed
cancel context.CancelFunc
}
type TokenMarketValues struct {
MarketCap float64 `json:"marketCap"`
HighDay float64 `json:"highDay"`
LowDay float64 `json:"lowDay"`
ChangePctHour float64 `json:"changePctHour"`
ChangePctDay float64 `json:"changePctDay"`
ChangePct24hour float64 `json:"changePct24hour"`
Change24hour float64 `json:"change24hour"`
Price float64 `json:"price"`
}
type ChainBalance struct {
Balance *big.Float `json:"balance"`
Address common.Address `json:"address"`
ChainID uint64 `json:"chainId"`
}
type Token struct {
Name string `json:"name"`
Symbol string `json:"symbol"`
Color string `json:"color"`
Decimals uint `json:"decimals"`
BalancesPerChain map[uint64]ChainBalance `json:"balancesPerChain"`
Description string `json:"description"`
AssetWebsiteURL string `json:"assetWebsiteUrl"`
BuiltOn string `json:"builtOn"`
MarketValuesPerCurrency map[string]TokenMarketValues `json:"marketValuesPerCurrency"`
PegSymbol string `json:"pegSymbol"`
}
func getTokenBySymbols(tokens []*token.Token) map[string][]*token.Token {
res := make(map[string][]*token.Token)
for _, t := range tokens {
if _, ok := res[t.Symbol]; !ok {
res[t.Symbol] = make([]*token.Token, 0)
}
res[t.Symbol] = append(res[t.Symbol], t)
}
return res
}
func getTokenSymbols(tokens []*token.Token) []string {
tokensBySymbols := getTokenBySymbols(tokens)
res := make([]string, 0)
for symbol := range tokensBySymbols {
res = append(res, symbol)
}
return res
}
func getTokenAddresses(tokens []*token.Token) []common.Address {
set := make(map[common.Address]bool)
for _, token := range tokens {
set[token.Address] = true
}
res := make([]common.Address, 0)
for address := range set {
res = append(res, address)
}
return res
}
func (r *Reader) Start() error {
ctx, cancel := context.WithCancel(context.Background())
r.cancel = cancel
go func() {
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
r.walletFeed.Send(walletevent.Event{
Type: EventWalletTickCheckConnected,
})
}
}
}()
go func() {
ticker := time.NewTicker(10 * time.Minute)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
r.walletFeed.Send(walletevent.Event{
Type: EventWalletTickReload,
})
}
}
}()
return nil
}
func (r *Reader) Stop() {
if r.cancel != nil {
r.cancel()
}
}
func (r *Reader) GetWalletToken(ctx context.Context, addresses []common.Address) (map[common.Address][]Token, error) {
networks, err := r.rpcClient.NetworkManager.Get(false)
if err != nil {
return nil, err
}
chainIDs := make([]uint64, 0)
for _, network := range networks {
chainIDs = append(chainIDs, network.ChainID)
}
currencies := make([]string, 0)
currency, err := r.accountsDB.GetCurrency()
if err != nil {
return nil, err
}
currencies = append(currencies, currency)
currencies = append(currencies, getFixedCurrencies()...)
allTokens, err := r.tokenManager.GetAllTokens()
if err != nil {
return nil, err
}
for _, network := range networks {
allTokens = append(allTokens, r.tokenManager.ToToken(network))
}
tokenSymbols := getTokenSymbols(allTokens)
tokenAddresses := getTokenAddresses(allTokens)
var (
group = async.NewAtomicGroup(ctx)
prices = map[string]map[string]float64{}
tokenDetails = map[string]thirdparty.Coin{}
tokenMarketValues = map[string]map[string]thirdparty.MarketCoinValues{}
balances = map[uint64]map[common.Address]map[common.Address]*hexutil.Big{}
)
group.Add(func(parent context.Context) error {
prices, err = r.priceManager.FetchPrices(tokenSymbols, currencies)
if err != nil {
return err
}
return nil
})
group.Add(func(parent context.Context) error {
tokenDetails, err = r.cryptoCompare.FetchTokenDetails(tokenSymbols)
if err != nil {
return err
}
return nil
})
group.Add(func(parent context.Context) error {
tokenMarketValues, err = r.cryptoCompare.FetchTokenMarketValues(tokenSymbols, currencies)
if err != nil {
return err
}
return nil
})
group.Add(func(parent context.Context) error {
clients, err := chain.NewClients(r.rpcClient, chainIDs)
if err != nil {
return err
}
balances, err = r.tokenManager.GetBalancesByChain(ctx, clients, addresses, tokenAddresses)
if err != nil {
return err
}
return nil
})
select {
case <-group.WaitAsync():
case <-ctx.Done():
return nil, ctx.Err()
}
err = group.Error()
if err != nil {
return nil, err
}
result := make(map[common.Address][]Token)
for _, address := range addresses {
for symbol, tokens := range getTokenBySymbols(allTokens) {
balancesPerChain := make(map[uint64]ChainBalance)
decimals := tokens[0].Decimals
for _, token := range tokens {
hexBalance := balances[token.ChainID][address][token.Address]
balance := big.NewFloat(0.0)
if hexBalance != nil {
balance = new(big.Float).Quo(
new(big.Float).SetInt(hexBalance.ToInt()),
big.NewFloat(math.Pow(10, float64(decimals))),
)
}
balancesPerChain[token.ChainID] = ChainBalance{
Balance: balance,
Address: token.Address,
ChainID: token.ChainID,
}
}
marketValuesPerCurrency := make(map[string]TokenMarketValues)
for _, currency := range currencies {
marketValuesPerCurrency[currency] = TokenMarketValues{
MarketCap: tokenMarketValues[symbol][currency].MKTCAP,
HighDay: tokenMarketValues[symbol][currency].HIGHDAY,
LowDay: tokenMarketValues[symbol][currency].LOWDAY,
ChangePctHour: tokenMarketValues[symbol][currency].CHANGEPCTHOUR,
ChangePctDay: tokenMarketValues[symbol][currency].CHANGEPCTDAY,
ChangePct24hour: tokenMarketValues[symbol][currency].CHANGEPCT24HOUR,
Change24hour: tokenMarketValues[symbol][currency].CHANGE24HOUR,
Price: prices[symbol][currency],
}
}
walletToken := Token{
Name: tokens[0].Name,
Color: tokens[0].Color,
Symbol: symbol,
BalancesPerChain: balancesPerChain,
Decimals: decimals,
Description: tokenDetails[symbol].Description,
AssetWebsiteURL: tokenDetails[symbol].AssetWebsiteURL,
BuiltOn: tokenDetails[symbol].BuiltOn,
MarketValuesPerCurrency: marketValuesPerCurrency,
PegSymbol: tokens[0].PegSymbol,
}
result[address] = append(result[address], walletToken)
}
}
return result, nil
}