@metamask/assets-controllers 26.0.0 → 27.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -1
- package/dist/AccountTrackerController.js +9 -236
- package/dist/AccountTrackerController.js.map +1 -1
- package/dist/AccountTrackerController.mjs +10 -0
- package/dist/AccountTrackerController.mjs.map +1 -0
- package/dist/AssetsContractController.js +17 -384
- package/dist/AssetsContractController.js.map +1 -1
- package/dist/AssetsContractController.mjs +18 -0
- package/dist/AssetsContractController.mjs.map +1 -0
- package/dist/CurrencyRateController.js +10 -157
- package/dist/CurrencyRateController.js.map +1 -1
- package/dist/CurrencyRateController.mjs +11 -0
- package/dist/CurrencyRateController.mjs.map +1 -0
- package/dist/NftController.js +15 -1041
- package/dist/NftController.js.map +1 -1
- package/dist/NftController.mjs +16 -0
- package/dist/NftController.mjs.map +1 -0
- package/dist/NftDetectionController.js +12 -213
- package/dist/NftDetectionController.js.map +1 -1
- package/dist/NftDetectionController.mjs +13 -0
- package/dist/NftDetectionController.mjs.map +1 -0
- package/dist/Standards/ERC20Standard.js +8 -142
- package/dist/Standards/ERC20Standard.js.map +1 -1
- package/dist/Standards/ERC20Standard.mjs +9 -0
- package/dist/Standards/ERC20Standard.mjs.map +1 -0
- package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js +8 -217
- package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js.map +1 -1
- package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.mjs +9 -0
- package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.mjs.map +1 -0
- package/dist/Standards/NftStandards/ERC721/ERC721Standard.js +8 -174
- package/dist/Standards/NftStandards/ERC721/ERC721Standard.js.map +1 -1
- package/dist/Standards/NftStandards/ERC721/ERC721Standard.mjs +9 -0
- package/dist/Standards/NftStandards/ERC721/ERC721Standard.mjs.map +1 -0
- package/dist/TokenBalancesController.js +11 -141
- package/dist/TokenBalancesController.js.map +1 -1
- package/dist/TokenBalancesController.mjs +12 -0
- package/dist/TokenBalancesController.mjs.map +1 -0
- package/dist/TokenDetectionController.js +16 -362
- package/dist/TokenDetectionController.js.map +1 -1
- package/dist/TokenDetectionController.mjs +17 -0
- package/dist/TokenDetectionController.mjs.map +1 -0
- package/dist/TokenListController.js +13 -250
- package/dist/TokenListController.js.map +1 -1
- package/dist/TokenListController.mjs +14 -0
- package/dist/TokenListController.mjs.map +1 -0
- package/dist/TokenRatesController.js +11 -328
- package/dist/TokenRatesController.js.map +1 -1
- package/dist/TokenRatesController.mjs +12 -0
- package/dist/TokenRatesController.mjs.map +1 -0
- package/dist/TokensController.js +15 -629
- package/dist/TokensController.js.map +1 -1
- package/dist/TokensController.mjs +16 -0
- package/dist/TokensController.mjs.map +1 -0
- package/dist/assetsUtil.js +41 -384
- package/dist/assetsUtil.js.map +1 -1
- package/dist/assetsUtil.mjs +42 -0
- package/dist/assetsUtil.mjs.map +1 -0
- package/dist/chunk-23F5W3A2.mjs +157 -0
- package/dist/chunk-23F5W3A2.mjs.map +1 -0
- package/dist/chunk-27KOXCQK.mjs +1 -0
- package/dist/chunk-27KOXCQK.mjs.map +1 -0
- package/dist/chunk-3FMWI46J.mjs +361 -0
- package/dist/chunk-3FMWI46J.mjs.map +1 -0
- package/dist/chunk-3FOTFZIL.mjs +411 -0
- package/dist/chunk-3FOTFZIL.mjs.map +1 -0
- package/dist/chunk-4LY47RPI.mjs +139 -0
- package/dist/chunk-4LY47RPI.mjs.map +1 -0
- package/dist/chunk-5C7ZVZNM.mjs +267 -0
- package/dist/chunk-5C7ZVZNM.mjs.map +1 -0
- package/dist/chunk-64EHFYLM.mjs +245 -0
- package/dist/chunk-64EHFYLM.mjs.map +1 -0
- package/dist/chunk-6C2ZIK7A.js +245 -0
- package/dist/chunk-6C2ZIK7A.js.map +1 -0
- package/dist/chunk-6DTCHPBB.mjs +178 -0
- package/dist/chunk-6DTCHPBB.mjs.map +1 -0
- package/dist/chunk-74IP34EL.js +1177 -0
- package/dist/chunk-74IP34EL.js.map +1 -0
- package/dist/chunk-BZI7P3TD.js +115 -0
- package/dist/chunk-BZI7P3TD.js.map +1 -0
- package/dist/chunk-C4PQK53K.js +32 -0
- package/dist/chunk-C4PQK53K.js.map +1 -0
- package/dist/chunk-CP3HC7AQ.mjs +12 -0
- package/dist/chunk-CP3HC7AQ.mjs.map +1 -0
- package/dist/chunk-GHZX5DE4.js +215 -0
- package/dist/chunk-GHZX5DE4.js.map +1 -0
- package/dist/chunk-GMKIOYCB.js +361 -0
- package/dist/chunk-GMKIOYCB.js.map +1 -0
- package/dist/chunk-H6TOSWUM.js +157 -0
- package/dist/chunk-H6TOSWUM.js.map +1 -0
- package/dist/chunk-HWFBJFHS.js +284 -0
- package/dist/chunk-HWFBJFHS.js.map +1 -0
- package/dist/chunk-J2JQQNHN.mjs +115 -0
- package/dist/chunk-J2JQQNHN.mjs.map +1 -0
- package/dist/chunk-J6HPEQL3.mjs +704 -0
- package/dist/chunk-J6HPEQL3.mjs.map +1 -0
- package/dist/chunk-JC4WAN2J.mjs +1177 -0
- package/dist/chunk-JC4WAN2J.mjs.map +1 -0
- package/dist/chunk-LD4GC7OR.js +139 -0
- package/dist/chunk-LD4GC7OR.js.map +1 -0
- package/dist/chunk-NG2UOKDD.js +178 -0
- package/dist/chunk-NG2UOKDD.js.map +1 -0
- package/dist/chunk-NGIXA5M5.mjs +418 -0
- package/dist/chunk-NGIXA5M5.mjs.map +1 -0
- package/dist/chunk-NLNXQHAU.js +704 -0
- package/dist/chunk-NLNXQHAU.js.map +1 -0
- package/dist/chunk-OBUR4TXH.js +1 -0
- package/dist/chunk-OBUR4TXH.js.map +1 -0
- package/dist/chunk-PAJTKWEC.mjs +246 -0
- package/dist/chunk-PAJTKWEC.mjs.map +1 -0
- package/dist/chunk-PRIXT2R6.js +411 -0
- package/dist/chunk-PRIXT2R6.js.map +1 -0
- package/dist/chunk-PUFSYRJZ.js +74 -0
- package/dist/chunk-PUFSYRJZ.js.map +1 -0
- package/dist/chunk-QHRPRO5U.mjs +74 -0
- package/dist/chunk-QHRPRO5U.mjs.map +1 -0
- package/dist/chunk-QR4CX2JT.mjs +284 -0
- package/dist/chunk-QR4CX2JT.mjs.map +1 -0
- package/dist/chunk-RGHTNZQ6.js +12 -0
- package/dist/chunk-RGHTNZQ6.js.map +1 -0
- package/dist/chunk-TCO22VIO.mjs +32 -0
- package/dist/chunk-TCO22VIO.mjs.map +1 -0
- package/dist/chunk-TDKCVCGP.mjs +215 -0
- package/dist/chunk-TDKCVCGP.mjs.map +1 -0
- package/dist/chunk-UAH5YURZ.js +343 -0
- package/dist/chunk-UAH5YURZ.js.map +1 -0
- package/dist/chunk-V4ZO3F2S.js +246 -0
- package/dist/chunk-V4ZO3F2S.js.map +1 -0
- package/dist/chunk-VDJBJAUB.js +418 -0
- package/dist/chunk-VDJBJAUB.js.map +1 -0
- package/dist/chunk-WRQ7POD7.mjs +343 -0
- package/dist/chunk-WRQ7POD7.mjs.map +1 -0
- package/dist/chunk-XUI43LEZ.mjs +30 -0
- package/dist/chunk-XUI43LEZ.mjs.map +1 -0
- package/dist/chunk-YD3NRMFC.js +267 -0
- package/dist/chunk-YD3NRMFC.js.map +1 -0
- package/dist/chunk-Z4BLTVTB.js +30 -0
- package/dist/chunk-Z4BLTVTB.js.map +1 -0
- package/dist/constants.js +7 -9
- package/dist/constants.js.map +1 -1
- package/dist/constants.mjs +8 -0
- package/dist/constants.mjs.map +1 -0
- package/dist/crypto-compare.js +7 -66
- package/dist/crypto-compare.js.map +1 -1
- package/dist/crypto-compare.mjs +8 -0
- package/dist/crypto-compare.mjs.map +1 -0
- package/dist/index.js +72 -39
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +73 -0
- package/dist/index.mjs.map +1 -0
- package/dist/token-prices-service/abstract-token-prices-service.js +1 -3
- package/dist/token-prices-service/abstract-token-prices-service.js.map +1 -1
- package/dist/token-prices-service/abstract-token-prices-service.mjs +1 -0
- package/dist/token-prices-service/abstract-token-prices-service.mjs.map +1 -0
- package/dist/token-prices-service/codefi-v2.js +11 -353
- package/dist/token-prices-service/codefi-v2.js.map +1 -1
- package/dist/token-prices-service/codefi-v2.mjs +12 -0
- package/dist/token-prices-service/codefi-v2.mjs.map +1 -0
- package/dist/token-prices-service/index.js +8 -5
- package/dist/token-prices-service/index.js.map +1 -1
- package/dist/token-prices-service/index.mjs +9 -0
- package/dist/token-prices-service/index.mjs.map +1 -0
- package/dist/token-service.js +14 -133
- package/dist/token-service.js.map +1 -1
- package/dist/token-service.mjs +15 -0
- package/dist/token-service.mjs.map +1 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -0
- package/dist/types/AccountTrackerController.d.ts.map +1 -0
- package/dist/types/AssetsContractController.d.ts.map +1 -0
- package/dist/types/CurrencyRateController.d.ts.map +1 -0
- package/dist/types/NftController.d.ts.map +1 -0
- package/dist/types/NftDetectionController.d.ts.map +1 -0
- package/dist/types/Standards/ERC20Standard.d.ts.map +1 -0
- package/dist/types/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts.map +1 -0
- package/dist/types/Standards/NftStandards/ERC721/ERC721Standard.d.ts.map +1 -0
- package/dist/types/TokenBalancesController.d.ts.map +1 -0
- package/dist/types/TokenDetectionController.d.ts.map +1 -0
- package/dist/types/TokenListController.d.ts.map +1 -0
- package/dist/types/TokenRatesController.d.ts.map +1 -0
- package/dist/{TokensController.d.ts → types/TokensController.d.ts} +10 -3
- package/dist/types/TokensController.d.ts.map +1 -0
- package/dist/types/assetsUtil.d.ts.map +1 -0
- package/dist/types/constants.d.ts.map +1 -0
- package/dist/types/crypto-compare.d.ts.map +1 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/token-prices-service/abstract-token-prices-service.d.ts.map +1 -0
- package/dist/types/token-prices-service/codefi-v2.d.ts.map +1 -0
- package/dist/types/token-prices-service/index.d.ts.map +1 -0
- package/dist/types/token-service.d.ts.map +1 -0
- package/package.json +24 -14
- package/dist/AccountTrackerController.d.ts.map +0 -1
- package/dist/AssetsContractController.d.ts.map +0 -1
- package/dist/CurrencyRateController.d.ts.map +0 -1
- package/dist/NftController.d.ts.map +0 -1
- package/dist/NftDetectionController.d.ts.map +0 -1
- package/dist/Standards/ERC20Standard.d.ts.map +0 -1
- package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts.map +0 -1
- package/dist/Standards/NftStandards/ERC721/ERC721Standard.d.ts.map +0 -1
- package/dist/TokenBalancesController.d.ts.map +0 -1
- package/dist/TokenDetectionController.d.ts.map +0 -1
- package/dist/TokenListController.d.ts.map +0 -1
- package/dist/TokenRatesController.d.ts.map +0 -1
- package/dist/TokensController.d.ts.map +0 -1
- package/dist/assetsUtil.d.ts.map +0 -1
- package/dist/constants.d.ts.map +0 -1
- package/dist/crypto-compare.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/token-prices-service/abstract-token-prices-service.d.ts.map +0 -1
- package/dist/token-prices-service/codefi-v2.d.ts.map +0 -1
- package/dist/token-prices-service/index.d.ts.map +0 -1
- package/dist/token-service.d.ts.map +0 -1
- /package/dist/{AccountTrackerController.d.ts → types/AccountTrackerController.d.ts} +0 -0
- /package/dist/{AssetsContractController.d.ts → types/AssetsContractController.d.ts} +0 -0
- /package/dist/{CurrencyRateController.d.ts → types/CurrencyRateController.d.ts} +0 -0
- /package/dist/{NftController.d.ts → types/NftController.d.ts} +0 -0
- /package/dist/{NftDetectionController.d.ts → types/NftDetectionController.d.ts} +0 -0
- /package/dist/{Standards → types/Standards}/ERC20Standard.d.ts +0 -0
- /package/dist/{Standards → types/Standards}/NftStandards/ERC1155/ERC1155Standard.d.ts +0 -0
- /package/dist/{Standards → types/Standards}/NftStandards/ERC721/ERC721Standard.d.ts +0 -0
- /package/dist/{TokenBalancesController.d.ts → types/TokenBalancesController.d.ts} +0 -0
- /package/dist/{TokenDetectionController.d.ts → types/TokenDetectionController.d.ts} +0 -0
- /package/dist/{TokenListController.d.ts → types/TokenListController.d.ts} +0 -0
- /package/dist/{TokenRatesController.d.ts → types/TokenRatesController.d.ts} +0 -0
- /package/dist/{assetsUtil.d.ts → types/assetsUtil.d.ts} +0 -0
- /package/dist/{constants.d.ts → types/constants.d.ts} +0 -0
- /package/dist/{crypto-compare.d.ts → types/crypto-compare.d.ts} +0 -0
- /package/dist/{index.d.ts → types/index.d.ts} +0 -0
- /package/dist/{token-prices-service → types/token-prices-service}/abstract-token-prices-service.d.ts +0 -0
- /package/dist/{token-prices-service → types/token-prices-service}/codefi-v2.d.ts +0 -0
- /package/dist/{token-prices-service → types/token-prices-service}/index.d.ts +0 -0
- /package/dist/{token-service.d.ts → types/token-service.d.ts} +0 -0
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
var _chunkZ4BLTVTBjs = require('./chunk-Z4BLTVTB.js');
|
|
6
|
+
|
|
7
|
+
// src/token-prices-service/codefi-v2.ts
|
|
8
|
+
var _controllerutils = require('@metamask/controller-utils');
|
|
9
|
+
var _utils = require('@metamask/utils');
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
var _cockatiel = require('cockatiel');
|
|
19
|
+
var SUPPORTED_CURRENCIES = [
|
|
20
|
+
// Bitcoin
|
|
21
|
+
"btc",
|
|
22
|
+
// Ether
|
|
23
|
+
"eth",
|
|
24
|
+
// Litecoin
|
|
25
|
+
"ltc",
|
|
26
|
+
// Bitcoin Cash
|
|
27
|
+
"bch",
|
|
28
|
+
// Binance Coin
|
|
29
|
+
"bnb",
|
|
30
|
+
// EOS
|
|
31
|
+
"eos",
|
|
32
|
+
// XRP
|
|
33
|
+
"xrp",
|
|
34
|
+
// Lumens
|
|
35
|
+
"xlm",
|
|
36
|
+
// Chainlink
|
|
37
|
+
"link",
|
|
38
|
+
// Polkadot
|
|
39
|
+
"dot",
|
|
40
|
+
// Yearn.finance
|
|
41
|
+
"yfi",
|
|
42
|
+
// US Dollar
|
|
43
|
+
"usd",
|
|
44
|
+
// United Arab Emirates Dirham
|
|
45
|
+
"aed",
|
|
46
|
+
// Argentine Peso
|
|
47
|
+
"ars",
|
|
48
|
+
// Australian Dollar
|
|
49
|
+
"aud",
|
|
50
|
+
// Bangladeshi Taka
|
|
51
|
+
"bdt",
|
|
52
|
+
// Bahraini Dinar
|
|
53
|
+
"bhd",
|
|
54
|
+
// Bermudian Dollar
|
|
55
|
+
"bmd",
|
|
56
|
+
// Brazil Real
|
|
57
|
+
"brl",
|
|
58
|
+
// Canadian Dollar
|
|
59
|
+
"cad",
|
|
60
|
+
// Swiss Franc
|
|
61
|
+
"chf",
|
|
62
|
+
// Chilean Peso
|
|
63
|
+
"clp",
|
|
64
|
+
// Chinese Yuan
|
|
65
|
+
"cny",
|
|
66
|
+
// Czech Koruna
|
|
67
|
+
"czk",
|
|
68
|
+
// Danish Krone
|
|
69
|
+
"dkk",
|
|
70
|
+
// Euro
|
|
71
|
+
"eur",
|
|
72
|
+
// British Pound Sterling
|
|
73
|
+
"gbp",
|
|
74
|
+
// Hong Kong Dollar
|
|
75
|
+
"hkd",
|
|
76
|
+
// Hungarian Forint
|
|
77
|
+
"huf",
|
|
78
|
+
// Indonesian Rupiah
|
|
79
|
+
"idr",
|
|
80
|
+
// Israeli New Shekel
|
|
81
|
+
"ils",
|
|
82
|
+
// Indian Rupee
|
|
83
|
+
"inr",
|
|
84
|
+
// Japanese Yen
|
|
85
|
+
"jpy",
|
|
86
|
+
// South Korean Won
|
|
87
|
+
"krw",
|
|
88
|
+
// Kuwaiti Dinar
|
|
89
|
+
"kwd",
|
|
90
|
+
// Sri Lankan Rupee
|
|
91
|
+
"lkr",
|
|
92
|
+
// Burmese Kyat
|
|
93
|
+
"mmk",
|
|
94
|
+
// Mexican Peso
|
|
95
|
+
"mxn",
|
|
96
|
+
// Malaysian Ringgit
|
|
97
|
+
"myr",
|
|
98
|
+
// Nigerian Naira
|
|
99
|
+
"ngn",
|
|
100
|
+
// Norwegian Krone
|
|
101
|
+
"nok",
|
|
102
|
+
// New Zealand Dollar
|
|
103
|
+
"nzd",
|
|
104
|
+
// Philippine Peso
|
|
105
|
+
"php",
|
|
106
|
+
// Pakistani Rupee
|
|
107
|
+
"pkr",
|
|
108
|
+
// Polish Zloty
|
|
109
|
+
"pln",
|
|
110
|
+
// Russian Ruble
|
|
111
|
+
"rub",
|
|
112
|
+
// Saudi Riyal
|
|
113
|
+
"sar",
|
|
114
|
+
// Swedish Krona
|
|
115
|
+
"sek",
|
|
116
|
+
// Singapore Dollar
|
|
117
|
+
"sgd",
|
|
118
|
+
// Thai Baht
|
|
119
|
+
"thb",
|
|
120
|
+
// Turkish Lira
|
|
121
|
+
"try",
|
|
122
|
+
// New Taiwan Dollar
|
|
123
|
+
"twd",
|
|
124
|
+
// Ukrainian hryvnia
|
|
125
|
+
"uah",
|
|
126
|
+
// Venezuelan bolívar fuerte
|
|
127
|
+
"vef",
|
|
128
|
+
// Vietnamese đồng
|
|
129
|
+
"vnd",
|
|
130
|
+
// South African Rand
|
|
131
|
+
"zar",
|
|
132
|
+
// IMF Special Drawing Rights
|
|
133
|
+
"xdr",
|
|
134
|
+
// Silver - Troy Ounce
|
|
135
|
+
"xag",
|
|
136
|
+
// Gold - Troy Ounce
|
|
137
|
+
"xau",
|
|
138
|
+
// Bits
|
|
139
|
+
"bits",
|
|
140
|
+
// Satoshi
|
|
141
|
+
"sats"
|
|
142
|
+
];
|
|
143
|
+
var SUPPORTED_CHAIN_IDS = [
|
|
144
|
+
// Ethereum Mainnet
|
|
145
|
+
"0x1",
|
|
146
|
+
// OP Mainnet
|
|
147
|
+
"0xa",
|
|
148
|
+
// Cronos Mainnet
|
|
149
|
+
"0x19",
|
|
150
|
+
// BNB Smart Chain Mainnet
|
|
151
|
+
"0x38",
|
|
152
|
+
// Syscoin Mainnet
|
|
153
|
+
"0x39",
|
|
154
|
+
// OKXChain Mainnet
|
|
155
|
+
"0x42",
|
|
156
|
+
// Hoo Smart Chain
|
|
157
|
+
"0x46",
|
|
158
|
+
// Meter Mainnet
|
|
159
|
+
"0x52",
|
|
160
|
+
// TomoChain
|
|
161
|
+
"0x58",
|
|
162
|
+
// Gnosis
|
|
163
|
+
"0x64",
|
|
164
|
+
// Velas EVM Mainnet
|
|
165
|
+
"0x6a",
|
|
166
|
+
// Fuse Mainnet
|
|
167
|
+
"0x7a",
|
|
168
|
+
// Huobi ECO Chain Mainnet
|
|
169
|
+
"0x80",
|
|
170
|
+
// Polygon Mainnet
|
|
171
|
+
"0x89",
|
|
172
|
+
// Fantom Opera
|
|
173
|
+
"0xfa",
|
|
174
|
+
// Boba Network
|
|
175
|
+
"0x120",
|
|
176
|
+
// KCC Mainnet
|
|
177
|
+
"0x141",
|
|
178
|
+
// zkSync Era Mainnet
|
|
179
|
+
"0x144",
|
|
180
|
+
// Theta Mainnet
|
|
181
|
+
"0x169",
|
|
182
|
+
// Metis Andromeda Mainnet
|
|
183
|
+
"0x440",
|
|
184
|
+
// Moonbeam
|
|
185
|
+
"0x504",
|
|
186
|
+
// Moonriver
|
|
187
|
+
"0x505",
|
|
188
|
+
// Base
|
|
189
|
+
"0x2105",
|
|
190
|
+
// Shiden
|
|
191
|
+
"0x150",
|
|
192
|
+
// Smart Bitcoin Cash
|
|
193
|
+
"0x2710",
|
|
194
|
+
// Arbitrum One
|
|
195
|
+
"0xa4b1",
|
|
196
|
+
// Celo Mainnet
|
|
197
|
+
"0xa4ec",
|
|
198
|
+
// Oasis Emerald
|
|
199
|
+
"0xa516",
|
|
200
|
+
// Avalanche C-Chain
|
|
201
|
+
"0xa86a",
|
|
202
|
+
// Polis Mainnet
|
|
203
|
+
"0x518af",
|
|
204
|
+
// Aurora Mainnet
|
|
205
|
+
"0x4e454152",
|
|
206
|
+
// Harmony Mainnet Shard 0
|
|
207
|
+
"0x63564c40",
|
|
208
|
+
// Linea Mainnet
|
|
209
|
+
"0xe708"
|
|
210
|
+
];
|
|
211
|
+
var BASE_URL = "https://price-api.metafi.codefi.network/v2";
|
|
212
|
+
var DEFAULT_TOKEN_PRICE_RETRIES = 3;
|
|
213
|
+
var DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES = (1 + DEFAULT_TOKEN_PRICE_RETRIES) * 3;
|
|
214
|
+
var DEFAULT_DEGRADED_THRESHOLD = 5e3;
|
|
215
|
+
var _tokenPricePolicy;
|
|
216
|
+
var CodefiTokenPricesServiceV2 = class {
|
|
217
|
+
/**
|
|
218
|
+
* Construct a Codefi Token Price Service.
|
|
219
|
+
*
|
|
220
|
+
* @param options - Constructor options
|
|
221
|
+
* @param options.degradedThreshold - The threshold between "normal" and "degrated" service,
|
|
222
|
+
* in milliseconds.
|
|
223
|
+
* @param options.retries - Number of retry attempts for each token price update.
|
|
224
|
+
* @param options.maximumConsecutiveFailures - The maximum number of consecutive failures
|
|
225
|
+
* allowed before breaking the circuit and pausing further updates.
|
|
226
|
+
* @param options.onBreak - An event handler for when the circuit breaks, useful for capturing
|
|
227
|
+
* metrics about network failures.
|
|
228
|
+
* @param options.onDegraded - An event handler for when the circuit remains closed, but requests
|
|
229
|
+
* are failing or resolving too slowly (i.e. resolving more slowly than the `degradedThreshold).
|
|
230
|
+
* @param options.circuitBreakDuration - The amount of time to wait when the circuit breaks
|
|
231
|
+
* from too many consecutive failures.
|
|
232
|
+
*/
|
|
233
|
+
constructor({
|
|
234
|
+
degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,
|
|
235
|
+
retries = DEFAULT_TOKEN_PRICE_RETRIES,
|
|
236
|
+
maximumConsecutiveFailures = DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES,
|
|
237
|
+
onBreak,
|
|
238
|
+
onDegraded,
|
|
239
|
+
circuitBreakDuration = 30 * 60 * 1e3
|
|
240
|
+
} = {}) {
|
|
241
|
+
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _tokenPricePolicy, void 0);
|
|
242
|
+
const retryPolicy = _cockatiel.retry.call(void 0, _cockatiel.handleAll, {
|
|
243
|
+
maxAttempts: retries,
|
|
244
|
+
backoff: new (0, _cockatiel.ExponentialBackoff)()
|
|
245
|
+
});
|
|
246
|
+
const circuitBreakerPolicy = _cockatiel.circuitBreaker.call(void 0, _cockatiel.handleAll, {
|
|
247
|
+
halfOpenAfter: circuitBreakDuration,
|
|
248
|
+
breaker: new (0, _cockatiel.ConsecutiveBreaker)(maximumConsecutiveFailures)
|
|
249
|
+
});
|
|
250
|
+
if (onBreak) {
|
|
251
|
+
circuitBreakerPolicy.onBreak(onBreak);
|
|
252
|
+
}
|
|
253
|
+
if (onDegraded) {
|
|
254
|
+
retryPolicy.onGiveUp(() => {
|
|
255
|
+
if (circuitBreakerPolicy.state === _cockatiel.CircuitState.Closed) {
|
|
256
|
+
onDegraded();
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
retryPolicy.onSuccess(({ duration }) => {
|
|
260
|
+
if (circuitBreakerPolicy.state === _cockatiel.CircuitState.Closed && duration > degradedThreshold) {
|
|
261
|
+
onDegraded();
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
_chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _tokenPricePolicy, _cockatiel.wrap.call(void 0, retryPolicy, circuitBreakerPolicy));
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Retrieves prices in the given currency for the tokens identified by the
|
|
269
|
+
* given addresses which are expected to live on the given chain.
|
|
270
|
+
*
|
|
271
|
+
* @param args - The arguments to function.
|
|
272
|
+
* @param args.chainId - An EIP-155 chain ID.
|
|
273
|
+
* @param args.tokenAddresses - Addresses for tokens that live on the chain.
|
|
274
|
+
* @param args.currency - The desired currency of the token prices.
|
|
275
|
+
* @returns The prices for the requested tokens.
|
|
276
|
+
*/
|
|
277
|
+
async fetchTokenPrices({
|
|
278
|
+
chainId,
|
|
279
|
+
tokenAddresses,
|
|
280
|
+
currency
|
|
281
|
+
}) {
|
|
282
|
+
const chainIdAsNumber = _utils.hexToNumber.call(void 0, chainId);
|
|
283
|
+
const url = new URL(`${BASE_URL}/chains/${chainIdAsNumber}/spot-prices`);
|
|
284
|
+
url.searchParams.append("tokenAddresses", tokenAddresses.join(","));
|
|
285
|
+
url.searchParams.append("vsCurrency", currency);
|
|
286
|
+
const pricesByCurrencyByTokenAddress = await _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _tokenPricePolicy).execute(
|
|
287
|
+
() => _controllerutils.handleFetch.call(void 0, url, { headers: { "Cache-Control": "no-cache" } })
|
|
288
|
+
);
|
|
289
|
+
return tokenAddresses.reduce(
|
|
290
|
+
(obj, tokenAddress) => {
|
|
291
|
+
const lowercasedTokenAddress = tokenAddress.toLowerCase();
|
|
292
|
+
const lowercasedCurrency = currency.toLowerCase();
|
|
293
|
+
const price = pricesByCurrencyByTokenAddress[lowercasedTokenAddress]?.[lowercasedCurrency];
|
|
294
|
+
if (!price) {
|
|
295
|
+
console.error(
|
|
296
|
+
`Could not find price for "${tokenAddress}" in "${currency}"`
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
const tokenPrice = {
|
|
300
|
+
tokenAddress,
|
|
301
|
+
value: price,
|
|
302
|
+
currency
|
|
303
|
+
};
|
|
304
|
+
return {
|
|
305
|
+
...obj,
|
|
306
|
+
...tokenPrice.value !== void 0 ? { [tokenAddress]: tokenPrice } : {}
|
|
307
|
+
};
|
|
308
|
+
},
|
|
309
|
+
{}
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Type guard for whether the API can return token prices for the given chain
|
|
314
|
+
* ID.
|
|
315
|
+
*
|
|
316
|
+
* @param chainId - The chain ID to check.
|
|
317
|
+
* @returns True if the API supports the chain ID, false otherwise.
|
|
318
|
+
*/
|
|
319
|
+
validateChainIdSupported(chainId) {
|
|
320
|
+
const supportedChainIds = SUPPORTED_CHAIN_IDS;
|
|
321
|
+
return typeof chainId === "string" && supportedChainIds.includes(chainId);
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Type guard for whether the API can return token prices in the given
|
|
325
|
+
* currency.
|
|
326
|
+
*
|
|
327
|
+
* @param currency - The currency to check. If a string, can be either
|
|
328
|
+
* lowercase or uppercase.
|
|
329
|
+
* @returns True if the API supports the currency, false otherwise.
|
|
330
|
+
*/
|
|
331
|
+
validateCurrencySupported(currency) {
|
|
332
|
+
const supportedCurrencies = SUPPORTED_CURRENCIES;
|
|
333
|
+
return typeof currency === "string" && supportedCurrencies.includes(currency.toLowerCase());
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
_tokenPricePolicy = new WeakMap();
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
exports.SUPPORTED_CURRENCIES = SUPPORTED_CURRENCIES; exports.SUPPORTED_CHAIN_IDS = SUPPORTED_CHAIN_IDS; exports.CodefiTokenPricesServiceV2 = CodefiTokenPricesServiceV2;
|
|
343
|
+
//# sourceMappingURL=chunk-UAH5YURZ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/token-prices-service/codefi-v2.ts"],"names":[],"mappings":";;;;;;;AAAA,SAAS,mBAAmB;AAE5B,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAoBA,IAAM,uBAAuB;AAAA;AAAA,EAElC;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;A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C;AAAA,EAEvD;AACF;AApKE","sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\nimport { hexToNumber } from '@metamask/utils';\nimport {\n circuitBreaker,\n ConsecutiveBreaker,\n ExponentialBackoff,\n handleAll,\n type IPolicy,\n retry,\n wrap,\n CircuitState,\n} from 'cockatiel';\n\nimport type {\n AbstractTokenPricesService,\n TokenPrice,\n TokenPricesByTokenAddress,\n} from './abstract-token-prices-service';\n\n/**\n * The shape of the data that the /spot-prices endpoint returns.\n */\ntype SpotPricesEndpointData<\n TokenAddress extends Hex,\n Currency extends string,\n> = Record<TokenAddress, Record<Currency, number>>;\n\n/**\n * The list of currencies that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint, in lowercase form.\n */\nexport const SUPPORTED_CURRENCIES = [\n // Bitcoin\n 'btc',\n // Ether\n 'eth',\n // Litecoin\n 'ltc',\n // Bitcoin Cash\n 'bch',\n // Binance Coin\n 'bnb',\n // EOS\n 'eos',\n // XRP\n 'xrp',\n // Lumens\n 'xlm',\n // Chainlink\n 'link',\n // Polkadot\n 'dot',\n // Yearn.finance\n 'yfi',\n // US Dollar\n 'usd',\n // United Arab Emirates Dirham\n 'aed',\n // Argentine Peso\n 'ars',\n // Australian Dollar\n 'aud',\n // Bangladeshi Taka\n 'bdt',\n // Bahraini Dinar\n 'bhd',\n // Bermudian Dollar\n 'bmd',\n // Brazil Real\n 'brl',\n // Canadian Dollar\n 'cad',\n // Swiss Franc\n 'chf',\n // Chilean Peso\n 'clp',\n // Chinese Yuan\n 'cny',\n // Czech Koruna\n 'czk',\n // Danish Krone\n 'dkk',\n // Euro\n 'eur',\n // British Pound Sterling\n 'gbp',\n // Hong Kong Dollar\n 'hkd',\n // Hungarian Forint\n 'huf',\n // Indonesian Rupiah\n 'idr',\n // Israeli New Shekel\n 'ils',\n // Indian Rupee\n 'inr',\n // Japanese Yen\n 'jpy',\n // South Korean Won\n 'krw',\n // Kuwaiti Dinar\n 'kwd',\n // Sri Lankan Rupee\n 'lkr',\n // Burmese Kyat\n 'mmk',\n // Mexican Peso\n 'mxn',\n // Malaysian Ringgit\n 'myr',\n // Nigerian Naira\n 'ngn',\n // Norwegian Krone\n 'nok',\n // New Zealand Dollar\n 'nzd',\n // Philippine Peso\n 'php',\n // Pakistani Rupee\n 'pkr',\n // Polish Zloty\n 'pln',\n // Russian Ruble\n 'rub',\n // Saudi Riyal\n 'sar',\n // Swedish Krona\n 'sek',\n // Singapore Dollar\n 'sgd',\n // Thai Baht\n 'thb',\n // Turkish Lira\n 'try',\n // New Taiwan Dollar\n 'twd',\n // Ukrainian hryvnia\n 'uah',\n // Venezuelan bolívar fuerte\n 'vef',\n // Vietnamese đồng\n 'vnd',\n // South African Rand\n 'zar',\n // IMF Special Drawing Rights\n 'xdr',\n // Silver - Troy Ounce\n 'xag',\n // Gold - Troy Ounce\n 'xau',\n // Bits\n 'bits',\n // Satoshi\n 'sats',\n] as const;\n\n/**\n * A currency that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.\n */\ntype SupportedCurrency =\n | (typeof SUPPORTED_CURRENCIES)[number]\n | Uppercase<(typeof SUPPORTED_CURRENCIES)[number]>;\n\n/**\n * The list of chain IDs that can be supplied in the URL for the `/spot-prices`\n * endpoint, but in hexadecimal form (for consistency with how we represent\n * chain IDs in other places).\n */\nexport const SUPPORTED_CHAIN_IDS = [\n // Ethereum Mainnet\n '0x1',\n // OP Mainnet\n '0xa',\n // Cronos Mainnet\n '0x19',\n // BNB Smart Chain Mainnet\n '0x38',\n // Syscoin Mainnet\n '0x39',\n // OKXChain Mainnet\n '0x42',\n // Hoo Smart Chain\n '0x46',\n // Meter Mainnet\n '0x52',\n // TomoChain\n '0x58',\n // Gnosis\n '0x64',\n // Velas EVM Mainnet\n '0x6a',\n // Fuse Mainnet\n '0x7a',\n // Huobi ECO Chain Mainnet\n '0x80',\n // Polygon Mainnet\n '0x89',\n // Fantom Opera\n '0xfa',\n // Boba Network\n '0x120',\n // KCC Mainnet\n '0x141',\n // zkSync Era Mainnet\n '0x144',\n // Theta Mainnet\n '0x169',\n // Metis Andromeda Mainnet\n '0x440',\n // Moonbeam\n '0x504',\n // Moonriver\n '0x505',\n // Base\n '0x2105',\n // Shiden\n '0x150',\n // Smart Bitcoin Cash\n '0x2710',\n // Arbitrum One\n '0xa4b1',\n // Celo Mainnet\n '0xa4ec',\n // Oasis Emerald\n '0xa516',\n // Avalanche C-Chain\n '0xa86a',\n // Polis Mainnet\n '0x518af',\n // Aurora Mainnet\n '0x4e454152',\n // Harmony Mainnet Shard 0\n '0x63564c40',\n // Linea Mainnet\n '0xe708',\n] as const;\n\n/**\n * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,\n * but in hexadecimal form (for consistency with how we represent chain IDs in\n * other places).\n */\ntype SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];\n\n/**\n * All requests to V2 of the Price API start with this.\n */\nconst BASE_URL = 'https://price-api.metafi.codefi.network/v2';\n\nconst DEFAULT_TOKEN_PRICE_RETRIES = 3;\n// Each update attempt will result (1 + retries) calls if the server is down\nconst DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES =\n (1 + DEFAULT_TOKEN_PRICE_RETRIES) * 3;\n\nconst DEFAULT_DEGRADED_THRESHOLD = 5_000;\n\n/**\n * This version of the token prices service uses V2 of the Codefi Price API to\n * fetch token prices.\n */\nexport class CodefiTokenPricesServiceV2\n implements\n AbstractTokenPricesService<SupportedChainId, Hex, SupportedCurrency>\n{\n #tokenPricePolicy: IPolicy;\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @param options - Constructor options\n * @param options.degradedThreshold - The threshold between \"normal\" and \"degrated\" service,\n * in milliseconds.\n * @param options.retries - Number of retry attempts for each token price update.\n * @param options.maximumConsecutiveFailures - The maximum number of consecutive failures\n * allowed before breaking the circuit and pausing further updates.\n * @param options.onBreak - An event handler for when the circuit breaks, useful for capturing\n * metrics about network failures.\n * @param options.onDegraded - An event handler for when the circuit remains closed, but requests\n * are failing or resolving too slowly (i.e. resolving more slowly than the `degradedThreshold).\n * @param options.circuitBreakDuration - The amount of time to wait when the circuit breaks\n * from too many consecutive failures.\n */\n constructor({\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n retries = DEFAULT_TOKEN_PRICE_RETRIES,\n maximumConsecutiveFailures = DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES,\n onBreak,\n onDegraded,\n circuitBreakDuration = 30 * 60 * 1000,\n }: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n } = {}) {\n // Construct a policy that will retry each update, and halt further updates\n // for a certain period after too many consecutive failures.\n const retryPolicy = retry(handleAll, {\n maxAttempts: retries,\n backoff: new ExponentialBackoff(),\n });\n const circuitBreakerPolicy = circuitBreaker(handleAll, {\n halfOpenAfter: circuitBreakDuration,\n breaker: new ConsecutiveBreaker(maximumConsecutiveFailures),\n });\n if (onBreak) {\n circuitBreakerPolicy.onBreak(onBreak);\n }\n if (onDegraded) {\n retryPolicy.onGiveUp(() => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n onDegraded();\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (\n circuitBreakerPolicy.state === CircuitState.Closed &&\n duration > degradedThreshold\n ) {\n onDegraded();\n }\n });\n }\n this.#tokenPricePolicy = wrap(retryPolicy, circuitBreakerPolicy);\n }\n\n /**\n * Retrieves prices in the given currency for the tokens identified by the\n * given addresses which are expected to live on the given chain.\n *\n * @param args - The arguments to function.\n * @param args.chainId - An EIP-155 chain ID.\n * @param args.tokenAddresses - Addresses for tokens that live on the chain.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n async fetchTokenPrices({\n chainId,\n tokenAddresses,\n currency,\n }: {\n chainId: SupportedChainId;\n tokenAddresses: Hex[];\n currency: SupportedCurrency;\n }): Promise<Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>> {\n const chainIdAsNumber = hexToNumber(chainId);\n\n const url = new URL(`${BASE_URL}/chains/${chainIdAsNumber}/spot-prices`);\n url.searchParams.append('tokenAddresses', tokenAddresses.join(','));\n url.searchParams.append('vsCurrency', currency);\n\n const pricesByCurrencyByTokenAddress: SpotPricesEndpointData<\n Lowercase<Hex>,\n Lowercase<SupportedCurrency>\n > = await this.#tokenPricePolicy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n );\n\n return tokenAddresses.reduce(\n (\n obj: Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>,\n tokenAddress,\n ) => {\n // The Price API lowercases both currency and token addresses, so we have\n // to keep track of them and make sure we return the original versions.\n const lowercasedTokenAddress =\n tokenAddress.toLowerCase() as Lowercase<Hex>;\n const lowercasedCurrency =\n currency.toLowerCase() as Lowercase<SupportedCurrency>;\n\n const price =\n pricesByCurrencyByTokenAddress[lowercasedTokenAddress]?.[\n lowercasedCurrency\n ];\n\n if (!price) {\n // console error instead of throwing to not interrupt the fetching of other tokens in case just one fails\n console.error(\n `Could not find price for \"${tokenAddress}\" in \"${currency}\"`,\n );\n }\n\n const tokenPrice: TokenPrice<Hex, SupportedCurrency> = {\n tokenAddress,\n value: price,\n currency,\n };\n\n return {\n ...obj,\n ...(tokenPrice.value !== undefined\n ? { [tokenAddress]: tokenPrice }\n : {}),\n };\n },\n {},\n ) as Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>;\n }\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is SupportedChainId {\n const supportedChainIds: readonly string[] = SUPPORTED_CHAIN_IDS;\n return typeof chainId === 'string' && supportedChainIds.includes(chainId);\n }\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check. If a string, can be either\n * lowercase or uppercase.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is SupportedCurrency {\n const supportedCurrencies: readonly string[] = SUPPORTED_CURRENCIES;\n return (\n typeof currency === 'string' &&\n supportedCurrencies.includes(currency.toLowerCase())\n );\n }\n}\n"]}
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
var _chunkZ4BLTVTBjs = require('./chunk-Z4BLTVTB.js');
|
|
5
|
+
|
|
6
|
+
// src/AccountTrackerController.ts
|
|
7
|
+
var _controllerutils = require('@metamask/controller-utils');
|
|
8
|
+
var _ethquery = require('@metamask/eth-query'); var _ethquery2 = _interopRequireDefault(_ethquery);
|
|
9
|
+
var _pollingcontroller = require('@metamask/polling-controller');
|
|
10
|
+
var _utils = require('@metamask/utils');
|
|
11
|
+
var _asyncmutex = require('async-mutex');
|
|
12
|
+
var _lodash = require('lodash');
|
|
13
|
+
var _getCorrectNetworkClient, getCorrectNetworkClient_fn;
|
|
14
|
+
var AccountTrackerController = class extends _pollingcontroller.StaticIntervalPollingControllerV1 {
|
|
15
|
+
/**
|
|
16
|
+
* Creates an AccountTracker instance.
|
|
17
|
+
*
|
|
18
|
+
* @param options - The controller options.
|
|
19
|
+
* @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.
|
|
20
|
+
* @param options.getIdentities - Gets the identities from the Preferences store.
|
|
21
|
+
* @param options.getSelectedAddress - Gets the selected address from the Preferences store.
|
|
22
|
+
* @param options.getMultiAccountBalancesEnabled - Gets the multi account balances enabled flag from the Preferences store.
|
|
23
|
+
* @param options.getCurrentChainId - Gets the chain ID for the current network from the Network store.
|
|
24
|
+
* @param options.getNetworkClientById - Gets the network client with the given id from the NetworkController.
|
|
25
|
+
* @param config - Initial options used to configure this controller.
|
|
26
|
+
* @param state - Initial state to set on this controller.
|
|
27
|
+
*/
|
|
28
|
+
constructor({
|
|
29
|
+
onPreferencesStateChange,
|
|
30
|
+
getIdentities,
|
|
31
|
+
getSelectedAddress,
|
|
32
|
+
getMultiAccountBalancesEnabled,
|
|
33
|
+
getCurrentChainId,
|
|
34
|
+
getNetworkClientById
|
|
35
|
+
}, config, state) {
|
|
36
|
+
super(config, state);
|
|
37
|
+
/**
|
|
38
|
+
* Resolves a networkClientId to a network client config
|
|
39
|
+
* or globally selected network config if not provided
|
|
40
|
+
*
|
|
41
|
+
* @param networkClientId - Optional networkClientId to fetch a network client with
|
|
42
|
+
* @returns network client config
|
|
43
|
+
*/
|
|
44
|
+
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _getCorrectNetworkClient);
|
|
45
|
+
this.refreshMutex = new (0, _asyncmutex.Mutex)();
|
|
46
|
+
/**
|
|
47
|
+
* Name of this controller used during composition
|
|
48
|
+
*/
|
|
49
|
+
this.name = "AccountTrackerController";
|
|
50
|
+
/**
|
|
51
|
+
* Refreshes the balances of the accounts depending on the multi-account setting.
|
|
52
|
+
* If multi-account is disabled, only updates the selected account balance.
|
|
53
|
+
* If multi-account is enabled, updates balances for all accounts.
|
|
54
|
+
*
|
|
55
|
+
* @param networkClientId - Optional networkClientId to fetch a network client with
|
|
56
|
+
*/
|
|
57
|
+
this.refresh = async (networkClientId) => {
|
|
58
|
+
const releaseLock = await this.refreshMutex.acquire();
|
|
59
|
+
try {
|
|
60
|
+
const { chainId, ethQuery } = _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getCorrectNetworkClient, getCorrectNetworkClient_fn).call(this, networkClientId);
|
|
61
|
+
this.syncAccounts(chainId);
|
|
62
|
+
const { accounts, accountsByChainId } = this.state;
|
|
63
|
+
const isMultiAccountBalancesEnabled = this.getMultiAccountBalancesEnabled();
|
|
64
|
+
const accountsToUpdate = isMultiAccountBalancesEnabled ? Object.keys(accounts) : [this.getSelectedAddress()];
|
|
65
|
+
const accountsForChain = { ...accountsByChainId[chainId] };
|
|
66
|
+
for (const address of accountsToUpdate) {
|
|
67
|
+
const balance = await this.getBalanceFromChain(address, ethQuery);
|
|
68
|
+
if (balance) {
|
|
69
|
+
accountsForChain[address] = {
|
|
70
|
+
balance
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
this.update({
|
|
75
|
+
...chainId === this.getCurrentChainId() && {
|
|
76
|
+
accounts: accountsForChain
|
|
77
|
+
},
|
|
78
|
+
accountsByChainId: {
|
|
79
|
+
...this.state.accountsByChainId,
|
|
80
|
+
[chainId]: accountsForChain
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
} catch (err) {
|
|
84
|
+
releaseLock();
|
|
85
|
+
throw err;
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
this.defaultConfig = {
|
|
89
|
+
interval: 1e4
|
|
90
|
+
};
|
|
91
|
+
this.defaultState = {
|
|
92
|
+
accounts: {},
|
|
93
|
+
accountsByChainId: {
|
|
94
|
+
[getCurrentChainId()]: {}
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
this.initialize();
|
|
98
|
+
this.setIntervalLength(this.config.interval);
|
|
99
|
+
this.getIdentities = getIdentities;
|
|
100
|
+
this.getSelectedAddress = getSelectedAddress;
|
|
101
|
+
this.getMultiAccountBalancesEnabled = getMultiAccountBalancesEnabled;
|
|
102
|
+
this.getCurrentChainId = getCurrentChainId;
|
|
103
|
+
this.getNetworkClientById = getNetworkClientById;
|
|
104
|
+
onPreferencesStateChange(() => {
|
|
105
|
+
this.refresh();
|
|
106
|
+
});
|
|
107
|
+
this.poll();
|
|
108
|
+
}
|
|
109
|
+
syncAccounts(newChainId) {
|
|
110
|
+
const accounts = { ...this.state.accounts };
|
|
111
|
+
const accountsByChainId = _lodash.cloneDeep.call(void 0, this.state.accountsByChainId);
|
|
112
|
+
const existing = Object.keys(accounts);
|
|
113
|
+
if (!accountsByChainId[newChainId]) {
|
|
114
|
+
accountsByChainId[newChainId] = {};
|
|
115
|
+
existing.forEach((address) => {
|
|
116
|
+
accountsByChainId[newChainId][address] = { balance: "0x0" };
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
const addresses = Object.keys(this.getIdentities());
|
|
120
|
+
const newAddresses = addresses.filter(
|
|
121
|
+
(address) => !existing.includes(address)
|
|
122
|
+
);
|
|
123
|
+
const oldAddresses = existing.filter(
|
|
124
|
+
(address) => !addresses.includes(address)
|
|
125
|
+
);
|
|
126
|
+
newAddresses.forEach((address) => {
|
|
127
|
+
accounts[address] = { balance: "0x0" };
|
|
128
|
+
});
|
|
129
|
+
Object.keys(accountsByChainId).forEach((chainId) => {
|
|
130
|
+
newAddresses.forEach((address) => {
|
|
131
|
+
accountsByChainId[chainId][address] = {
|
|
132
|
+
balance: "0x0"
|
|
133
|
+
};
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
oldAddresses.forEach((address) => {
|
|
137
|
+
delete accounts[address];
|
|
138
|
+
});
|
|
139
|
+
Object.keys(accountsByChainId).forEach((chainId) => {
|
|
140
|
+
oldAddresses.forEach((address) => {
|
|
141
|
+
delete accountsByChainId[chainId][address];
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
this.update({ accounts, accountsByChainId });
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Sets a new provider.
|
|
148
|
+
*
|
|
149
|
+
* TODO: Replace this wth a method.
|
|
150
|
+
*
|
|
151
|
+
* @param provider - Provider used to create a new underlying EthQuery instance.
|
|
152
|
+
*/
|
|
153
|
+
set provider(provider) {
|
|
154
|
+
this._provider = provider;
|
|
155
|
+
}
|
|
156
|
+
get provider() {
|
|
157
|
+
throw new Error("Property only used for setting");
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Starts a new polling interval.
|
|
161
|
+
*
|
|
162
|
+
* @param interval - Polling interval trigger a 'refresh'.
|
|
163
|
+
*/
|
|
164
|
+
async poll(interval) {
|
|
165
|
+
interval && this.configure({ interval }, false, false);
|
|
166
|
+
this.handle && clearTimeout(this.handle);
|
|
167
|
+
await this.refresh();
|
|
168
|
+
this.handle = setTimeout(() => {
|
|
169
|
+
this.poll(this.config.interval);
|
|
170
|
+
}, this.config.interval);
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Refreshes the balances of the accounts using the networkClientId
|
|
174
|
+
*
|
|
175
|
+
* @param networkClientId - The network client ID used to get balances.
|
|
176
|
+
*/
|
|
177
|
+
async _executePoll(networkClientId) {
|
|
178
|
+
this.refresh(networkClientId);
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Fetches the balance of a given address from the blockchain.
|
|
182
|
+
*
|
|
183
|
+
* @param address - The account address to fetch the balance for.
|
|
184
|
+
* @param ethQuery - The EthQuery instance to query getBalnce with.
|
|
185
|
+
* @returns A promise that resolves to the balance in a hex string format.
|
|
186
|
+
*/
|
|
187
|
+
async getBalanceFromChain(address, ethQuery) {
|
|
188
|
+
return await _controllerutils.safelyExecuteWithTimeout.call(void 0, async () => {
|
|
189
|
+
_utils.assert.call(void 0, ethQuery, "Provider not set.");
|
|
190
|
+
return await _controllerutils.query.call(void 0, ethQuery, "getBalance", [address]);
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Sync accounts balances with some additional addresses.
|
|
195
|
+
*
|
|
196
|
+
* @param addresses - the additional addresses, may be hardware wallet addresses.
|
|
197
|
+
* @param networkClientId - Optional networkClientId to fetch a network client with.
|
|
198
|
+
* @returns accounts - addresses with synced balance
|
|
199
|
+
*/
|
|
200
|
+
async syncBalanceWithAddresses(addresses, networkClientId) {
|
|
201
|
+
const { ethQuery } = _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getCorrectNetworkClient, getCorrectNetworkClient_fn).call(this, networkClientId);
|
|
202
|
+
return await Promise.all(
|
|
203
|
+
addresses.map((address) => {
|
|
204
|
+
return _controllerutils.safelyExecuteWithTimeout.call(void 0, async () => {
|
|
205
|
+
_utils.assert.call(void 0, ethQuery, "Provider not set.");
|
|
206
|
+
const balance = await _controllerutils.query.call(void 0, ethQuery, "getBalance", [address]);
|
|
207
|
+
return [address, balance];
|
|
208
|
+
});
|
|
209
|
+
})
|
|
210
|
+
).then((value) => {
|
|
211
|
+
return value.reduce((obj, item) => {
|
|
212
|
+
if (!item) {
|
|
213
|
+
return obj;
|
|
214
|
+
}
|
|
215
|
+
const [address, balance] = item;
|
|
216
|
+
return {
|
|
217
|
+
...obj,
|
|
218
|
+
[address]: {
|
|
219
|
+
balance
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
}, {});
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
_getCorrectNetworkClient = new WeakSet();
|
|
227
|
+
getCorrectNetworkClient_fn = function(networkClientId) {
|
|
228
|
+
if (networkClientId) {
|
|
229
|
+
const networkClient = this.getNetworkClientById(networkClientId);
|
|
230
|
+
return {
|
|
231
|
+
chainId: networkClient.configuration.chainId,
|
|
232
|
+
ethQuery: new (0, _ethquery2.default)(networkClient.provider)
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
return {
|
|
236
|
+
chainId: this.getCurrentChainId(),
|
|
237
|
+
ethQuery: this._provider ? new (0, _ethquery2.default)(this._provider) : void 0
|
|
238
|
+
};
|
|
239
|
+
};
|
|
240
|
+
var AccountTrackerController_default = AccountTrackerController;
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
exports.AccountTrackerController = AccountTrackerController; exports.AccountTrackerController_default = AccountTrackerController_default;
|
|
246
|
+
//# sourceMappingURL=chunk-V4ZO3F2S.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/AccountTrackerController.ts"],"names":[],"mappings":";;;;;;AACA,SAAS,OAAO,gCAAgC;AAChD,OAAO,cAAc;AAOrB,SAAS,yCAAyC;AAElD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,EASA,MAAM,yBACJ,WACA,iBAC8C;AAC9C,UAAM,EAAE,SAAS,IAAI,sBAAK,sDAAL,WAA8B;AAEnD,WAAO,MAAM,QAAQ;AAAA,MACnB,UAAU,IAAI,CAAC,YAAmD;AAChE,eAAO,yBAAyB,YAAY;AAC1C,iBAAO,UAAU,mBAAmB;AACpC,gBAAM,UAAU,MAAM,MAAM,UAAU,cAAc,CAAC,OAAO,CAAC;AAC7D,iBAAO,CAAC,SAAS,OAAO;AAAA,QAC1B,CAAC;AAAA,MACH,CAAC;AAAA,IACH,EAAE,KAAK,CAAC,UAAU;AAChB,aAAO,MAAM,OAAO,CAAC,KAAK,SAAS;AACjC,YAAI,CAAC,MAAM;AACT,iBAAO;AAAA,QACT;AAEA,cAAM,CAAC,SAAS,OAAO,IAAI;AAC3B,eAAO;AAAA,UACL,GAAG;AAAA,UACH,CAAC,OAAO,GAAG;AAAA,YACT;AAAA,UACF;AAAA,QACF;AAAA,MACF,GAAG,CAAC,CAAC;AAAA,IACP,CAAC;AAAA,EACH;AACF;AA9IE;AAAA,6BAAwB,SAAC,iBAGvB;AACA,MAAI,iBAAiB;AACnB,UAAM,gBAAgB,KAAK,qBAAqB,eAAe;AAE/D,WAAO;AAAA,MACL,SAAS,cAAc,cAAc;AAAA,MACrC,UAAU,IAAI,SAAS,cAAc,QAAQ;AAAA,IAC/C;AAAA,EACF;AAEA,SAAO;AAAA,IACL,SAAS,KAAK,kBAAkB;AAAA,IAChC,UAAU,KAAK,YAAY,IAAI,SAAS,KAAK,SAAS,IAAI;AAAA,EAC5D;AACF;AA+HF,IAAO,mCAAQ","sourcesContent":["import type { BaseConfig, BaseState } from '@metamask/base-controller';\nimport { query, safelyExecuteWithTimeout } from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport type { Provider } from '@metamask/eth-query';\nimport type {\n NetworkClientId,\n NetworkController,\n NetworkState,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingControllerV1 } from '@metamask/polling-controller';\nimport type { PreferencesState } from '@metamask/preferences-controller';\nimport { assert } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\nimport { cloneDeep } from 'lodash';\n\n/**\n * @type AccountInformation\n *\n * Account information object\n * @property balance - Hex string of an account balancec in wei\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface AccountInformation {\n balance: string;\n}\n\n/**\n * @type AccountTrackerConfig\n *\n * Account tracker controller configuration\n * @property provider - Provider used to create a new underlying EthQuery instance\n */\n// This interface was created before this ESLint rule was added.\n// Remove in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface AccountTrackerConfig extends BaseConfig {\n interval: number;\n provider?: Provider;\n}\n\n/**\n * @type AccountTrackerState\n *\n * Account tracker controller state\n * @property accounts - Map of addresses to account information\n */\n// This interface was created before this ESLint rule was added.\n// Remove in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface AccountTrackerState extends BaseState {\n accounts: { [address: string]: AccountInformation };\n accountsByChainId: Record<string, { [address: string]: AccountInformation }>;\n}\n\n/**\n * Controller that tracks the network balances for all user accounts.\n */\nexport class AccountTrackerController extends StaticIntervalPollingControllerV1<\n AccountTrackerConfig,\n AccountTrackerState\n> {\n private _provider?: Provider;\n\n private readonly refreshMutex = new Mutex();\n\n private handle?: ReturnType<typeof setTimeout>;\n\n private syncAccounts(newChainId: string) {\n const accounts = { ...this.state.accounts };\n const accountsByChainId = cloneDeep(this.state.accountsByChainId);\n\n const existing = Object.keys(accounts);\n if (!accountsByChainId[newChainId]) {\n accountsByChainId[newChainId] = {};\n existing.forEach((address) => {\n accountsByChainId[newChainId][address] = { balance: '0x0' };\n });\n }\n\n const addresses = Object.keys(this.getIdentities());\n const newAddresses = addresses.filter(\n (address) => !existing.includes(address),\n );\n const oldAddresses = existing.filter(\n (address) => !addresses.includes(address),\n );\n newAddresses.forEach((address) => {\n accounts[address] = { balance: '0x0' };\n });\n Object.keys(accountsByChainId).forEach((chainId) => {\n newAddresses.forEach((address) => {\n accountsByChainId[chainId][address] = {\n balance: '0x0',\n };\n });\n });\n\n oldAddresses.forEach((address) => {\n delete accounts[address];\n });\n Object.keys(accountsByChainId).forEach((chainId) => {\n oldAddresses.forEach((address) => {\n delete accountsByChainId[chainId][address];\n });\n });\n\n this.update({ accounts, accountsByChainId });\n }\n\n /**\n * Name of this controller used during composition\n */\n override name = 'AccountTrackerController';\n\n private readonly getIdentities: () => PreferencesState['identities'];\n\n private readonly getSelectedAddress: () => PreferencesState['selectedAddress'];\n\n private readonly getMultiAccountBalancesEnabled: () => PreferencesState['isMultiAccountBalancesEnabled'];\n\n private readonly getCurrentChainId: () => NetworkState['providerConfig']['chainId'];\n\n private readonly getNetworkClientById: NetworkController['getNetworkClientById'];\n\n /**\n * Creates an AccountTracker instance.\n *\n * @param options - The controller options.\n * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.\n * @param options.getIdentities - Gets the identities from the Preferences store.\n * @param options.getSelectedAddress - Gets the selected address from the Preferences store.\n * @param options.getMultiAccountBalancesEnabled - Gets the multi account balances enabled flag from the Preferences store.\n * @param options.getCurrentChainId - Gets the chain ID for the current network from the Network store.\n * @param options.getNetworkClientById - Gets the network client with the given id from the NetworkController.\n * @param config - Initial options used to configure this controller.\n * @param state - Initial state to set on this controller.\n */\n constructor(\n {\n onPreferencesStateChange,\n getIdentities,\n getSelectedAddress,\n getMultiAccountBalancesEnabled,\n getCurrentChainId,\n getNetworkClientById,\n }: {\n onPreferencesStateChange: (\n listener: (preferencesState: PreferencesState) => void,\n ) => void;\n getIdentities: () => PreferencesState['identities'];\n getSelectedAddress: () => PreferencesState['selectedAddress'];\n getMultiAccountBalancesEnabled: () => PreferencesState['isMultiAccountBalancesEnabled'];\n getCurrentChainId: () => NetworkState['providerConfig']['chainId'];\n getNetworkClientById: NetworkController['getNetworkClientById'];\n },\n config?: Partial<AccountTrackerConfig>,\n state?: Partial<AccountTrackerState>,\n ) {\n super(config, state);\n this.defaultConfig = {\n interval: 10000,\n };\n this.defaultState = {\n accounts: {},\n accountsByChainId: {\n [getCurrentChainId()]: {},\n },\n };\n this.initialize();\n this.setIntervalLength(this.config.interval);\n this.getIdentities = getIdentities;\n this.getSelectedAddress = getSelectedAddress;\n this.getMultiAccountBalancesEnabled = getMultiAccountBalancesEnabled;\n this.getCurrentChainId = getCurrentChainId;\n this.getNetworkClientById = getNetworkClientById;\n onPreferencesStateChange(() => {\n this.refresh();\n });\n this.poll();\n }\n\n /**\n * Sets a new provider.\n *\n * TODO: Replace this wth a method.\n *\n * @param provider - Provider used to create a new underlying EthQuery instance.\n */\n set provider(provider: Provider) {\n this._provider = provider;\n }\n\n get provider() {\n throw new Error('Property only used for setting');\n }\n\n /**\n * Resolves a networkClientId to a network client config\n * or globally selected network config if not provided\n *\n * @param networkClientId - Optional networkClientId to fetch a network client with\n * @returns network client config\n */\n #getCorrectNetworkClient(networkClientId?: NetworkClientId): {\n chainId: string;\n ethQuery?: EthQuery;\n } {\n if (networkClientId) {\n const networkClient = this.getNetworkClientById(networkClientId);\n\n return {\n chainId: networkClient.configuration.chainId,\n ethQuery: new EthQuery(networkClient.provider),\n };\n }\n\n return {\n chainId: this.getCurrentChainId(),\n ethQuery: this._provider ? new EthQuery(this._provider) : undefined,\n };\n }\n\n /**\n * Starts a new polling interval.\n *\n * @param interval - Polling interval trigger a 'refresh'.\n */\n async poll(interval?: number): Promise<void> {\n interval && this.configure({ interval }, false, false);\n this.handle && clearTimeout(this.handle);\n await this.refresh();\n this.handle = setTimeout(() => {\n this.poll(this.config.interval);\n }, this.config.interval);\n }\n\n /**\n * Refreshes the balances of the accounts using the networkClientId\n *\n * @param networkClientId - The network client ID used to get balances.\n */\n async _executePoll(networkClientId: string): Promise<void> {\n this.refresh(networkClientId);\n }\n\n /**\n * Refreshes the balances of the accounts depending on the multi-account setting.\n * If multi-account is disabled, only updates the selected account balance.\n * If multi-account is enabled, updates balances for all accounts.\n *\n * @param networkClientId - Optional networkClientId to fetch a network client with\n */\n refresh = async (networkClientId?: NetworkClientId) => {\n const releaseLock = await this.refreshMutex.acquire();\n try {\n const { chainId, ethQuery } =\n this.#getCorrectNetworkClient(networkClientId);\n this.syncAccounts(chainId);\n const { accounts, accountsByChainId } = this.state;\n const isMultiAccountBalancesEnabled =\n this.getMultiAccountBalancesEnabled();\n\n const accountsToUpdate = isMultiAccountBalancesEnabled\n ? Object.keys(accounts)\n : [this.getSelectedAddress()];\n\n const accountsForChain = { ...accountsByChainId[chainId] };\n for (const address of accountsToUpdate) {\n const balance = await this.getBalanceFromChain(address, ethQuery);\n if (balance) {\n accountsForChain[address] = {\n balance,\n };\n }\n }\n\n this.update({\n ...(chainId === this.getCurrentChainId() && {\n accounts: accountsForChain,\n }),\n accountsByChainId: {\n ...this.state.accountsByChainId,\n [chainId]: accountsForChain,\n },\n });\n } catch (err) {\n releaseLock();\n throw err;\n }\n };\n\n /**\n * Fetches the balance of a given address from the blockchain.\n *\n * @param address - The account address to fetch the balance for.\n * @param ethQuery - The EthQuery instance to query getBalnce with.\n * @returns A promise that resolves to the balance in a hex string format.\n */\n private async getBalanceFromChain(\n address: string,\n ethQuery?: EthQuery,\n ): Promise<string | undefined> {\n return await safelyExecuteWithTimeout(async () => {\n assert(ethQuery, 'Provider not set.');\n return await query(ethQuery, 'getBalance', [address]);\n });\n }\n\n /**\n * Sync accounts balances with some additional addresses.\n *\n * @param addresses - the additional addresses, may be hardware wallet addresses.\n * @param networkClientId - Optional networkClientId to fetch a network client with.\n * @returns accounts - addresses with synced balance\n */\n async syncBalanceWithAddresses(\n addresses: string[],\n networkClientId?: NetworkClientId,\n ): Promise<Record<string, { balance: string }>> {\n const { ethQuery } = this.#getCorrectNetworkClient(networkClientId);\n\n return await Promise.all(\n addresses.map((address): Promise<[string, string] | undefined> => {\n return safelyExecuteWithTimeout(async () => {\n assert(ethQuery, 'Provider not set.');\n const balance = await query(ethQuery, 'getBalance', [address]);\n return [address, balance];\n });\n }),\n ).then((value) => {\n return value.reduce((obj, item) => {\n if (!item) {\n return obj;\n }\n\n const [address, balance] = item;\n return {\n ...obj,\n [address]: {\n balance,\n },\n };\n }, {});\n });\n }\n}\n\nexport default AccountTrackerController;\n"]}
|