@metamask-previews/assets-controllers 26.0.0-preview.d78968a2 → 26.0.0-preview.eb2135e

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.
Files changed (229) hide show
  1. package/dist/AccountTrackerController.js +9 -239
  2. package/dist/AccountTrackerController.js.map +1 -1
  3. package/dist/AccountTrackerController.mjs +10 -0
  4. package/dist/AccountTrackerController.mjs.map +1 -0
  5. package/dist/AssetsContractController.js +17 -384
  6. package/dist/AssetsContractController.js.map +1 -1
  7. package/dist/AssetsContractController.mjs +18 -0
  8. package/dist/AssetsContractController.mjs.map +1 -0
  9. package/dist/CurrencyRateController.js +10 -157
  10. package/dist/CurrencyRateController.js.map +1 -1
  11. package/dist/CurrencyRateController.mjs +11 -0
  12. package/dist/CurrencyRateController.mjs.map +1 -0
  13. package/dist/NftController.js +15 -1041
  14. package/dist/NftController.js.map +1 -1
  15. package/dist/NftController.mjs +16 -0
  16. package/dist/NftController.mjs.map +1 -0
  17. package/dist/NftDetectionController.js +12 -213
  18. package/dist/NftDetectionController.js.map +1 -1
  19. package/dist/NftDetectionController.mjs +13 -0
  20. package/dist/NftDetectionController.mjs.map +1 -0
  21. package/dist/Standards/ERC20Standard.js +8 -142
  22. package/dist/Standards/ERC20Standard.js.map +1 -1
  23. package/dist/Standards/ERC20Standard.mjs +9 -0
  24. package/dist/Standards/ERC20Standard.mjs.map +1 -0
  25. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js +8 -217
  26. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js.map +1 -1
  27. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.mjs +9 -0
  28. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.mjs.map +1 -0
  29. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js +8 -174
  30. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js.map +1 -1
  31. package/dist/Standards/NftStandards/ERC721/ERC721Standard.mjs +9 -0
  32. package/dist/Standards/NftStandards/ERC721/ERC721Standard.mjs.map +1 -0
  33. package/dist/TokenBalancesController.js +11 -141
  34. package/dist/TokenBalancesController.js.map +1 -1
  35. package/dist/TokenBalancesController.mjs +12 -0
  36. package/dist/TokenBalancesController.mjs.map +1 -0
  37. package/dist/TokenDetectionController.js +16 -362
  38. package/dist/TokenDetectionController.js.map +1 -1
  39. package/dist/TokenDetectionController.mjs +17 -0
  40. package/dist/TokenDetectionController.mjs.map +1 -0
  41. package/dist/TokenListController.js +13 -250
  42. package/dist/TokenListController.js.map +1 -1
  43. package/dist/TokenListController.mjs +14 -0
  44. package/dist/TokenListController.mjs.map +1 -0
  45. package/dist/TokenRatesController.js +11 -328
  46. package/dist/TokenRatesController.js.map +1 -1
  47. package/dist/TokenRatesController.mjs +12 -0
  48. package/dist/TokenRatesController.mjs.map +1 -0
  49. package/dist/TokensController.js +15 -629
  50. package/dist/TokensController.js.map +1 -1
  51. package/dist/TokensController.mjs +16 -0
  52. package/dist/TokensController.mjs.map +1 -0
  53. package/dist/assetsUtil.js +41 -384
  54. package/dist/assetsUtil.js.map +1 -1
  55. package/dist/assetsUtil.mjs +42 -0
  56. package/dist/assetsUtil.mjs.map +1 -0
  57. package/dist/chunk-23F5W3A2.mjs +157 -0
  58. package/dist/chunk-23F5W3A2.mjs.map +1 -0
  59. package/dist/chunk-27KOXCQK.mjs +1 -0
  60. package/dist/chunk-27KOXCQK.mjs.map +1 -0
  61. package/dist/chunk-3FMWI46J.mjs +361 -0
  62. package/dist/chunk-3FMWI46J.mjs.map +1 -0
  63. package/dist/chunk-3FOTFZIL.mjs +411 -0
  64. package/dist/chunk-3FOTFZIL.mjs.map +1 -0
  65. package/dist/chunk-4LY47RPI.mjs +139 -0
  66. package/dist/chunk-4LY47RPI.mjs.map +1 -0
  67. package/dist/chunk-5C7ZVZNM.mjs +267 -0
  68. package/dist/chunk-5C7ZVZNM.mjs.map +1 -0
  69. package/dist/chunk-64EHFYLM.mjs +245 -0
  70. package/dist/chunk-64EHFYLM.mjs.map +1 -0
  71. package/dist/chunk-6C2ZIK7A.js +245 -0
  72. package/dist/chunk-6C2ZIK7A.js.map +1 -0
  73. package/dist/chunk-6DTCHPBB.mjs +178 -0
  74. package/dist/chunk-6DTCHPBB.mjs.map +1 -0
  75. package/dist/chunk-74IP34EL.js +1177 -0
  76. package/dist/chunk-74IP34EL.js.map +1 -0
  77. package/dist/chunk-BZI7P3TD.js +115 -0
  78. package/dist/chunk-BZI7P3TD.js.map +1 -0
  79. package/dist/chunk-C4PQK53K.js +32 -0
  80. package/dist/chunk-C4PQK53K.js.map +1 -0
  81. package/dist/chunk-CP3HC7AQ.mjs +12 -0
  82. package/dist/chunk-CP3HC7AQ.mjs.map +1 -0
  83. package/dist/chunk-GHZX5DE4.js +215 -0
  84. package/dist/chunk-GHZX5DE4.js.map +1 -0
  85. package/dist/chunk-GMKIOYCB.js +361 -0
  86. package/dist/chunk-GMKIOYCB.js.map +1 -0
  87. package/dist/chunk-H6TOSWUM.js +157 -0
  88. package/dist/chunk-H6TOSWUM.js.map +1 -0
  89. package/dist/chunk-HWFBJFHS.js +284 -0
  90. package/dist/chunk-HWFBJFHS.js.map +1 -0
  91. package/dist/chunk-J2JQQNHN.mjs +115 -0
  92. package/dist/chunk-J2JQQNHN.mjs.map +1 -0
  93. package/dist/chunk-J6HPEQL3.mjs +704 -0
  94. package/dist/chunk-J6HPEQL3.mjs.map +1 -0
  95. package/dist/chunk-JC4WAN2J.mjs +1177 -0
  96. package/dist/chunk-JC4WAN2J.mjs.map +1 -0
  97. package/dist/chunk-LD4GC7OR.js +139 -0
  98. package/dist/chunk-LD4GC7OR.js.map +1 -0
  99. package/dist/chunk-NG2UOKDD.js +178 -0
  100. package/dist/chunk-NG2UOKDD.js.map +1 -0
  101. package/dist/chunk-NGIXA5M5.mjs +418 -0
  102. package/dist/chunk-NGIXA5M5.mjs.map +1 -0
  103. package/dist/chunk-NLNXQHAU.js +704 -0
  104. package/dist/chunk-NLNXQHAU.js.map +1 -0
  105. package/dist/chunk-OBUR4TXH.js +1 -0
  106. package/dist/chunk-OBUR4TXH.js.map +1 -0
  107. package/dist/chunk-PAJTKWEC.mjs +246 -0
  108. package/dist/chunk-PAJTKWEC.mjs.map +1 -0
  109. package/dist/chunk-PRIXT2R6.js +411 -0
  110. package/dist/chunk-PRIXT2R6.js.map +1 -0
  111. package/dist/chunk-PUFSYRJZ.js +74 -0
  112. package/dist/chunk-PUFSYRJZ.js.map +1 -0
  113. package/dist/chunk-QHRPRO5U.mjs +74 -0
  114. package/dist/chunk-QHRPRO5U.mjs.map +1 -0
  115. package/dist/chunk-QR4CX2JT.mjs +284 -0
  116. package/dist/chunk-QR4CX2JT.mjs.map +1 -0
  117. package/dist/chunk-RGHTNZQ6.js +12 -0
  118. package/dist/chunk-RGHTNZQ6.js.map +1 -0
  119. package/dist/chunk-TCO22VIO.mjs +32 -0
  120. package/dist/chunk-TCO22VIO.mjs.map +1 -0
  121. package/dist/chunk-TDKCVCGP.mjs +215 -0
  122. package/dist/chunk-TDKCVCGP.mjs.map +1 -0
  123. package/dist/chunk-UAH5YURZ.js +343 -0
  124. package/dist/chunk-UAH5YURZ.js.map +1 -0
  125. package/dist/chunk-V4ZO3F2S.js +246 -0
  126. package/dist/chunk-V4ZO3F2S.js.map +1 -0
  127. package/dist/chunk-VDJBJAUB.js +418 -0
  128. package/dist/chunk-VDJBJAUB.js.map +1 -0
  129. package/dist/chunk-WRQ7POD7.mjs +343 -0
  130. package/dist/chunk-WRQ7POD7.mjs.map +1 -0
  131. package/dist/chunk-XUI43LEZ.mjs +30 -0
  132. package/dist/chunk-XUI43LEZ.mjs.map +1 -0
  133. package/dist/chunk-YD3NRMFC.js +267 -0
  134. package/dist/chunk-YD3NRMFC.js.map +1 -0
  135. package/dist/chunk-Z4BLTVTB.js +30 -0
  136. package/dist/chunk-Z4BLTVTB.js.map +1 -0
  137. package/dist/constants.js +7 -9
  138. package/dist/constants.js.map +1 -1
  139. package/dist/constants.mjs +8 -0
  140. package/dist/constants.mjs.map +1 -0
  141. package/dist/crypto-compare.js +7 -66
  142. package/dist/crypto-compare.js.map +1 -1
  143. package/dist/crypto-compare.mjs +8 -0
  144. package/dist/crypto-compare.mjs.map +1 -0
  145. package/dist/index.js +72 -39
  146. package/dist/index.js.map +1 -1
  147. package/dist/index.mjs +73 -0
  148. package/dist/index.mjs.map +1 -0
  149. package/dist/token-prices-service/abstract-token-prices-service.js +1 -3
  150. package/dist/token-prices-service/abstract-token-prices-service.js.map +1 -1
  151. package/dist/token-prices-service/abstract-token-prices-service.mjs +1 -0
  152. package/dist/token-prices-service/abstract-token-prices-service.mjs.map +1 -0
  153. package/dist/token-prices-service/codefi-v2.js +11 -353
  154. package/dist/token-prices-service/codefi-v2.js.map +1 -1
  155. package/dist/token-prices-service/codefi-v2.mjs +12 -0
  156. package/dist/token-prices-service/codefi-v2.mjs.map +1 -0
  157. package/dist/token-prices-service/index.js +8 -5
  158. package/dist/token-prices-service/index.js.map +1 -1
  159. package/dist/token-prices-service/index.mjs +9 -0
  160. package/dist/token-prices-service/index.mjs.map +1 -0
  161. package/dist/token-service.js +14 -133
  162. package/dist/token-service.js.map +1 -1
  163. package/dist/token-service.mjs +15 -0
  164. package/dist/token-service.mjs.map +1 -0
  165. package/dist/tsconfig.build.tsbuildinfo +1 -0
  166. package/dist/types/AccountTrackerController.d.ts.map +1 -0
  167. package/dist/types/AssetsContractController.d.ts.map +1 -0
  168. package/dist/types/CurrencyRateController.d.ts.map +1 -0
  169. package/dist/types/NftController.d.ts.map +1 -0
  170. package/dist/types/NftDetectionController.d.ts.map +1 -0
  171. package/dist/types/Standards/ERC20Standard.d.ts.map +1 -0
  172. package/dist/types/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts.map +1 -0
  173. package/dist/types/Standards/NftStandards/ERC721/ERC721Standard.d.ts.map +1 -0
  174. package/dist/types/TokenBalancesController.d.ts.map +1 -0
  175. package/dist/types/TokenDetectionController.d.ts.map +1 -0
  176. package/dist/types/TokenListController.d.ts.map +1 -0
  177. package/dist/types/TokenRatesController.d.ts.map +1 -0
  178. package/dist/types/TokensController.d.ts.map +1 -0
  179. package/dist/types/assetsUtil.d.ts.map +1 -0
  180. package/dist/types/constants.d.ts.map +1 -0
  181. package/dist/types/crypto-compare.d.ts.map +1 -0
  182. package/dist/types/index.d.ts.map +1 -0
  183. package/dist/types/token-prices-service/abstract-token-prices-service.d.ts.map +1 -0
  184. package/dist/types/token-prices-service/codefi-v2.d.ts.map +1 -0
  185. package/dist/types/token-prices-service/index.d.ts.map +1 -0
  186. package/dist/types/token-service.d.ts.map +1 -0
  187. package/package.json +11 -1
  188. package/dist/AccountTrackerController.d.ts.map +0 -1
  189. package/dist/AssetsContractController.d.ts.map +0 -1
  190. package/dist/CurrencyRateController.d.ts.map +0 -1
  191. package/dist/NftController.d.ts.map +0 -1
  192. package/dist/NftDetectionController.d.ts.map +0 -1
  193. package/dist/Standards/ERC20Standard.d.ts.map +0 -1
  194. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts.map +0 -1
  195. package/dist/Standards/NftStandards/ERC721/ERC721Standard.d.ts.map +0 -1
  196. package/dist/TokenBalancesController.d.ts.map +0 -1
  197. package/dist/TokenDetectionController.d.ts.map +0 -1
  198. package/dist/TokenListController.d.ts.map +0 -1
  199. package/dist/TokenRatesController.d.ts.map +0 -1
  200. package/dist/TokensController.d.ts.map +0 -1
  201. package/dist/assetsUtil.d.ts.map +0 -1
  202. package/dist/constants.d.ts.map +0 -1
  203. package/dist/crypto-compare.d.ts.map +0 -1
  204. package/dist/index.d.ts.map +0 -1
  205. package/dist/token-prices-service/abstract-token-prices-service.d.ts.map +0 -1
  206. package/dist/token-prices-service/codefi-v2.d.ts.map +0 -1
  207. package/dist/token-prices-service/index.d.ts.map +0 -1
  208. package/dist/token-service.d.ts.map +0 -1
  209. /package/dist/{AccountTrackerController.d.ts → types/AccountTrackerController.d.ts} +0 -0
  210. /package/dist/{AssetsContractController.d.ts → types/AssetsContractController.d.ts} +0 -0
  211. /package/dist/{CurrencyRateController.d.ts → types/CurrencyRateController.d.ts} +0 -0
  212. /package/dist/{NftController.d.ts → types/NftController.d.ts} +0 -0
  213. /package/dist/{NftDetectionController.d.ts → types/NftDetectionController.d.ts} +0 -0
  214. /package/dist/{Standards → types/Standards}/ERC20Standard.d.ts +0 -0
  215. /package/dist/{Standards → types/Standards}/NftStandards/ERC1155/ERC1155Standard.d.ts +0 -0
  216. /package/dist/{Standards → types/Standards}/NftStandards/ERC721/ERC721Standard.d.ts +0 -0
  217. /package/dist/{TokenBalancesController.d.ts → types/TokenBalancesController.d.ts} +0 -0
  218. /package/dist/{TokenDetectionController.d.ts → types/TokenDetectionController.d.ts} +0 -0
  219. /package/dist/{TokenListController.d.ts → types/TokenListController.d.ts} +0 -0
  220. /package/dist/{TokenRatesController.d.ts → types/TokenRatesController.d.ts} +0 -0
  221. /package/dist/{TokensController.d.ts → types/TokensController.d.ts} +0 -0
  222. /package/dist/{assetsUtil.d.ts → types/assetsUtil.d.ts} +0 -0
  223. /package/dist/{constants.d.ts → types/constants.d.ts} +0 -0
  224. /package/dist/{crypto-compare.d.ts → types/crypto-compare.d.ts} +0 -0
  225. /package/dist/{index.d.ts → types/index.d.ts} +0 -0
  226. /package/dist/{token-prices-service → types/token-prices-service}/abstract-token-prices-service.d.ts +0 -0
  227. /package/dist/{token-prices-service → types/token-prices-service}/codefi-v2.d.ts +0 -0
  228. /package/dist/{token-prices-service → types/token-prices-service}/index.d.ts +0 -0
  229. /package/dist/{token-service.d.ts → types/token-service.d.ts} +0 -0
@@ -0,0 +1,343 @@
1
+ import {
2
+ __privateAdd,
3
+ __privateGet,
4
+ __privateSet
5
+ } from "./chunk-XUI43LEZ.mjs";
6
+
7
+ // src/token-prices-service/codefi-v2.ts
8
+ import { handleFetch } from "@metamask/controller-utils";
9
+ import { hexToNumber } from "@metamask/utils";
10
+ import {
11
+ circuitBreaker,
12
+ ConsecutiveBreaker,
13
+ ExponentialBackoff,
14
+ handleAll,
15
+ retry,
16
+ wrap,
17
+ CircuitState
18
+ } from "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
+ __privateAdd(this, _tokenPricePolicy, void 0);
242
+ const retryPolicy = retry(handleAll, {
243
+ maxAttempts: retries,
244
+ backoff: new ExponentialBackoff()
245
+ });
246
+ const circuitBreakerPolicy = circuitBreaker(handleAll, {
247
+ halfOpenAfter: circuitBreakDuration,
248
+ breaker: new ConsecutiveBreaker(maximumConsecutiveFailures)
249
+ });
250
+ if (onBreak) {
251
+ circuitBreakerPolicy.onBreak(onBreak);
252
+ }
253
+ if (onDegraded) {
254
+ retryPolicy.onGiveUp(() => {
255
+ if (circuitBreakerPolicy.state === CircuitState.Closed) {
256
+ onDegraded();
257
+ }
258
+ });
259
+ retryPolicy.onSuccess(({ duration }) => {
260
+ if (circuitBreakerPolicy.state === CircuitState.Closed && duration > degradedThreshold) {
261
+ onDegraded();
262
+ }
263
+ });
264
+ }
265
+ __privateSet(this, _tokenPricePolicy, wrap(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 = hexToNumber(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 __privateGet(this, _tokenPricePolicy).execute(
287
+ () => handleFetch(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
+ export {
339
+ SUPPORTED_CURRENCIES,
340
+ SUPPORTED_CHAIN_IDS,
341
+ CodefiTokenPricesServiceV2
342
+ };
343
+ //# sourceMappingURL=chunk-WRQ7POD7.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/token-prices-service/codefi-v2.ts"],"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 support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,QACF;AAEA,eAAO;AAAA,UACL,GAAG;AAAA,UACH,GAAI,WAAW,UAAU,SACrB,EAAE,CAAC,YAAY,GAAG,WAAW,IAC7B,CAAC;AAAA,QACP;AAAA,MACF;AAAA,MACA,CAAC;AAAA,IACH;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,yBAAyB,SAA+C;AACtE,UAAM,oBAAuC;AAC7C,WAAO,OAAO,YAAY,YAAY,kBAAkB,SAAS,OAAO;AAAA,EAC1E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,0BAA0B,UAAkD;AAC1E,UAAM,sBAAyC;AAC/C,WACE,OAAO,aAAa,YACpB,oBAAoB,SAAS,SAAS,YAAY,CAAC;AAAA,EAEvD;AACF;AApKE;","names":[]}
@@ -0,0 +1,30 @@
1
+ var __accessCheck = (obj, member, msg) => {
2
+ if (!member.has(obj))
3
+ throw TypeError("Cannot " + msg);
4
+ };
5
+ var __privateGet = (obj, member, getter) => {
6
+ __accessCheck(obj, member, "read from private field");
7
+ return getter ? getter.call(obj) : member.get(obj);
8
+ };
9
+ var __privateAdd = (obj, member, value) => {
10
+ if (member.has(obj))
11
+ throw TypeError("Cannot add the same private member more than once");
12
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
13
+ };
14
+ var __privateSet = (obj, member, value, setter) => {
15
+ __accessCheck(obj, member, "write to private field");
16
+ setter ? setter.call(obj, value) : member.set(obj, value);
17
+ return value;
18
+ };
19
+ var __privateMethod = (obj, member, method) => {
20
+ __accessCheck(obj, member, "access private method");
21
+ return method;
22
+ };
23
+
24
+ export {
25
+ __privateGet,
26
+ __privateAdd,
27
+ __privateSet,
28
+ __privateMethod
29
+ };
30
+ //# sourceMappingURL=chunk-XUI43LEZ.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,267 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// src/assetsUtil.ts
2
+
3
+
4
+
5
+ var _controllerutils = require('@metamask/controller-utils');
6
+ var _utils = require('@metamask/utils');
7
+ var _bnjs = require('bn.js'); var _bnjs2 = _interopRequireDefault(_bnjs);
8
+ var _cid = require('multiformats/cid');
9
+ var TOKEN_PRICES_BATCH_SIZE = 30;
10
+ function compareNftMetadata(newNftMetadata, nft) {
11
+ const keys = [
12
+ "image",
13
+ "backgroundColor",
14
+ "imagePreview",
15
+ "imageThumbnail",
16
+ "imageOriginal",
17
+ "animation",
18
+ "animationOriginal",
19
+ "externalLink"
20
+ ];
21
+ const differentValues = keys.reduce((value, key) => {
22
+ if (newNftMetadata[key] && newNftMetadata[key] !== nft[key]) {
23
+ return value + 1;
24
+ }
25
+ return value;
26
+ }, 0);
27
+ return differentValues > 0;
28
+ }
29
+ var aggregatorNameByKey = {
30
+ aave: "Aave",
31
+ bancor: "Bancor",
32
+ cmc: "CMC",
33
+ cryptocom: "Crypto.com",
34
+ coinGecko: "CoinGecko",
35
+ oneInch: "1inch",
36
+ paraswap: "Paraswap",
37
+ pmm: "PMM",
38
+ zapper: "Zapper",
39
+ zerion: "Zerion",
40
+ zeroEx: "0x",
41
+ synthetix: "Synthetix",
42
+ yearn: "Yearn",
43
+ apeswap: "ApeSwap",
44
+ binanceDex: "BinanceDex",
45
+ pancakeTop100: "PancakeTop100",
46
+ pancakeExtended: "PancakeExtended",
47
+ balancer: "Balancer",
48
+ quickswap: "QuickSwap",
49
+ matcha: "Matcha",
50
+ pangolinDex: "PangolinDex",
51
+ pangolinDexStableCoin: "PangolinDexStableCoin",
52
+ pangolinDexAvaxBridge: "PangolinDexAvaxBridge",
53
+ traderJoe: "TraderJoe",
54
+ airswapLight: "AirswapLight",
55
+ kleros: "Kleros"
56
+ };
57
+ var formatAggregatorNames = (aggregators) => {
58
+ return aggregators.map(
59
+ (key) => aggregatorNameByKey[key] || `${key[0].toUpperCase()}${key.substring(1, key.length)}`
60
+ );
61
+ };
62
+ var formatIconUrlWithProxy = ({
63
+ chainId,
64
+ tokenAddress
65
+ }) => {
66
+ const chainIdDecimal = _controllerutils.convertHexToDecimal.call(void 0, chainId).toString();
67
+ return `https://static.metafi.codefi.network/api/v1/tokenIcons/${chainIdDecimal}/${tokenAddress.toLowerCase()}.png`;
68
+ };
69
+ var SupportedTokenDetectionNetworks = /* @__PURE__ */ ((SupportedTokenDetectionNetworks2) => {
70
+ SupportedTokenDetectionNetworks2["mainnet"] = "0x1";
71
+ SupportedTokenDetectionNetworks2["bsc"] = "0x38";
72
+ SupportedTokenDetectionNetworks2["polygon"] = "0x89";
73
+ SupportedTokenDetectionNetworks2["avax"] = "0xa86a";
74
+ SupportedTokenDetectionNetworks2["aurora"] = "0x4e454152";
75
+ SupportedTokenDetectionNetworks2["linea_goerli"] = "0xe704";
76
+ SupportedTokenDetectionNetworks2["linea_mainnet"] = "0xe708";
77
+ SupportedTokenDetectionNetworks2["arbitrum"] = "0xa4b1";
78
+ SupportedTokenDetectionNetworks2["optimism"] = "0xa";
79
+ SupportedTokenDetectionNetworks2["base"] = "0x2105";
80
+ SupportedTokenDetectionNetworks2["zksync"] = "0x144";
81
+ return SupportedTokenDetectionNetworks2;
82
+ })(SupportedTokenDetectionNetworks || {});
83
+ function isTokenDetectionSupportedForNetwork(chainId) {
84
+ return Object.values(SupportedTokenDetectionNetworks).includes(chainId);
85
+ }
86
+ function isTokenListSupportedForNetwork(chainId) {
87
+ return isTokenDetectionSupportedForNetwork(chainId);
88
+ }
89
+ function removeIpfsProtocolPrefix(ipfsUrl) {
90
+ if (ipfsUrl.startsWith("ipfs://ipfs/")) {
91
+ return ipfsUrl.replace("ipfs://ipfs/", "");
92
+ } else if (ipfsUrl.startsWith("ipfs://")) {
93
+ return ipfsUrl.replace("ipfs://", "");
94
+ }
95
+ throw new Error("this method should not be used with non ipfs urls");
96
+ }
97
+ function getIpfsCIDv1AndPath(ipfsUrl) {
98
+ const url = removeIpfsProtocolPrefix(ipfsUrl);
99
+ const index = url.indexOf("/");
100
+ const cid = index !== -1 ? url.substring(0, index) : url;
101
+ const path = index !== -1 ? url.substring(index) : void 0;
102
+ return {
103
+ cid: _cid.CID.parse(cid).toV1().toString(),
104
+ path
105
+ };
106
+ }
107
+ function getFormattedIpfsUrl(ipfsGateway, ipfsUrl, subdomainSupported) {
108
+ const { host, protocol, origin } = new URL(addUrlProtocolPrefix(ipfsGateway));
109
+ if (subdomainSupported) {
110
+ const { cid, path } = getIpfsCIDv1AndPath(ipfsUrl);
111
+ return `${protocol}//${cid}.ipfs.${host}${path ?? ""}`;
112
+ }
113
+ const cidAndPath = removeIpfsProtocolPrefix(ipfsUrl);
114
+ return `${origin}/ipfs/${cidAndPath}`;
115
+ }
116
+ function addUrlProtocolPrefix(urlString) {
117
+ if (!urlString.match(/(^http:\/\/)|(^https:\/\/)/u)) {
118
+ return `https://${urlString}`;
119
+ }
120
+ return urlString;
121
+ }
122
+ function ethersBigNumberToBN(bigNumber) {
123
+ return new (0, _bnjs2.default)(_utils.remove0x.call(void 0, bigNumber.toHexString()), "hex");
124
+ }
125
+ function divideIntoBatches(values, { batchSize }) {
126
+ const batches = [];
127
+ for (let i = 0; i < values.length; i += batchSize) {
128
+ batches.push(values.slice(i, i + batchSize));
129
+ }
130
+ return batches;
131
+ }
132
+ async function reduceInBatchesSerially({
133
+ values,
134
+ batchSize,
135
+ eachBatch,
136
+ initialResult
137
+ }) {
138
+ const batches = divideIntoBatches(values, { batchSize });
139
+ let workingResult = initialResult;
140
+ for (const [index, batch] of batches.entries()) {
141
+ workingResult = await eachBatch(workingResult, batch, index);
142
+ }
143
+ const finalResult = workingResult;
144
+ return finalResult;
145
+ }
146
+ function mapOpenSeaNftV2ToV1(nft) {
147
+ return {
148
+ token_id: nft.identifier,
149
+ num_sales: null,
150
+ background_color: null,
151
+ image_url: nft.image_url ?? null,
152
+ image_preview_url: null,
153
+ image_thumbnail_url: null,
154
+ image_original_url: null,
155
+ animation_url: null,
156
+ animation_original_url: null,
157
+ name: nft.name,
158
+ description: nft.description,
159
+ external_link: null,
160
+ asset_contract: {
161
+ address: nft.contract,
162
+ asset_contract_type: null,
163
+ created_date: null,
164
+ schema_name: nft.token_standard.toUpperCase(),
165
+ symbol: null,
166
+ total_supply: null,
167
+ description: nft.description,
168
+ external_link: null,
169
+ collection: {
170
+ name: nft.collection,
171
+ image_url: null
172
+ }
173
+ },
174
+ creator: {
175
+ user: { username: "" },
176
+ profile_img_url: "",
177
+ address: ""
178
+ },
179
+ last_sale: null
180
+ };
181
+ }
182
+ function mapOpenSeaDetailedNftV2ToV1(nft) {
183
+ const mapped = mapOpenSeaNftV2ToV1(nft);
184
+ return {
185
+ ...mapped,
186
+ animation_url: nft.animation_url ?? null,
187
+ creator: {
188
+ ...mapped.creator,
189
+ address: nft.creator
190
+ }
191
+ };
192
+ }
193
+ function mapOpenSeaContractV2ToV1(contract, collection) {
194
+ return {
195
+ address: contract.address,
196
+ asset_contract_type: null,
197
+ created_date: null,
198
+ schema_name: contract.contract_standard.toUpperCase(),
199
+ symbol: null,
200
+ total_supply: collection?.total_supply?.toString() ?? contract.total_supply?.toString() ?? null,
201
+ description: collection?.description ?? null,
202
+ external_link: collection?.project_url ?? null,
203
+ collection: {
204
+ name: collection?.name ?? contract.name,
205
+ image_url: collection?.image_url
206
+ }
207
+ };
208
+ }
209
+ async function fetchTokenContractExchangeRates({
210
+ tokenPricesService,
211
+ nativeCurrency,
212
+ tokenAddresses,
213
+ chainId
214
+ }) {
215
+ const isChainIdSupported = tokenPricesService.validateChainIdSupported(chainId);
216
+ const isCurrencySupported = tokenPricesService.validateCurrencySupported(nativeCurrency);
217
+ if (!isChainIdSupported || !isCurrencySupported) {
218
+ return {};
219
+ }
220
+ const tokenPricesByTokenAddress = await reduceInBatchesSerially({
221
+ values: [...tokenAddresses].sort(),
222
+ batchSize: TOKEN_PRICES_BATCH_SIZE,
223
+ eachBatch: async (allTokenPricesByTokenAddress, batch) => {
224
+ const tokenPricesByTokenAddressForBatch = await tokenPricesService.fetchTokenPrices({
225
+ tokenAddresses: batch,
226
+ chainId,
227
+ currency: nativeCurrency
228
+ });
229
+ return {
230
+ ...allTokenPricesByTokenAddress,
231
+ ...tokenPricesByTokenAddressForBatch
232
+ };
233
+ },
234
+ initialResult: {}
235
+ });
236
+ return Object.entries(tokenPricesByTokenAddress).reduce(
237
+ (obj, [tokenAddress, tokenPrice]) => {
238
+ return {
239
+ ...obj,
240
+ [_controllerutils.toChecksumHexAddress.call(void 0, tokenAddress)]: tokenPrice?.value
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
+ exports.TOKEN_PRICES_BATCH_SIZE = TOKEN_PRICES_BATCH_SIZE; exports.compareNftMetadata = compareNftMetadata; exports.formatAggregatorNames = formatAggregatorNames; exports.formatIconUrlWithProxy = formatIconUrlWithProxy; exports.SupportedTokenDetectionNetworks = SupportedTokenDetectionNetworks; exports.isTokenDetectionSupportedForNetwork = isTokenDetectionSupportedForNetwork; exports.isTokenListSupportedForNetwork = isTokenListSupportedForNetwork; exports.removeIpfsProtocolPrefix = removeIpfsProtocolPrefix; exports.getIpfsCIDv1AndPath = getIpfsCIDv1AndPath; exports.getFormattedIpfsUrl = getFormattedIpfsUrl; exports.addUrlProtocolPrefix = addUrlProtocolPrefix; exports.ethersBigNumberToBN = ethersBigNumberToBN; exports.divideIntoBatches = divideIntoBatches; exports.reduceInBatchesSerially = reduceInBatchesSerially; exports.mapOpenSeaNftV2ToV1 = mapOpenSeaNftV2ToV1; exports.mapOpenSeaDetailedNftV2ToV1 = mapOpenSeaDetailedNftV2ToV1; exports.mapOpenSeaContractV2ToV1 = mapOpenSeaContractV2ToV1; exports.fetchTokenContractExchangeRates = fetchTokenContractExchangeRates;
267
+ //# sourceMappingURL=chunk-YD3NRMFC.js.map