@metamask/assets-controllers 25.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.
Files changed (235) hide show
  1. package/CHANGELOG.md +210 -39
  2. package/dist/AccountTrackerController.js +9 -236
  3. package/dist/AccountTrackerController.js.map +1 -1
  4. package/dist/AccountTrackerController.mjs +10 -0
  5. package/dist/AccountTrackerController.mjs.map +1 -0
  6. package/dist/AssetsContractController.js +17 -385
  7. package/dist/AssetsContractController.js.map +1 -1
  8. package/dist/AssetsContractController.mjs +18 -0
  9. package/dist/AssetsContractController.mjs.map +1 -0
  10. package/dist/CurrencyRateController.js +10 -157
  11. package/dist/CurrencyRateController.js.map +1 -1
  12. package/dist/CurrencyRateController.mjs +11 -0
  13. package/dist/CurrencyRateController.mjs.map +1 -0
  14. package/dist/NftController.js +15 -1039
  15. package/dist/NftController.js.map +1 -1
  16. package/dist/NftController.mjs +16 -0
  17. package/dist/NftController.mjs.map +1 -0
  18. package/dist/NftDetectionController.js +12 -215
  19. package/dist/NftDetectionController.js.map +1 -1
  20. package/dist/NftDetectionController.mjs +13 -0
  21. package/dist/NftDetectionController.mjs.map +1 -0
  22. package/dist/Standards/ERC20Standard.js +8 -144
  23. package/dist/Standards/ERC20Standard.js.map +1 -1
  24. package/dist/Standards/ERC20Standard.mjs +9 -0
  25. package/dist/Standards/ERC20Standard.mjs.map +1 -0
  26. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js +8 -217
  27. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js.map +1 -1
  28. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.mjs +9 -0
  29. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.mjs.map +1 -0
  30. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js +8 -175
  31. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js.map +1 -1
  32. package/dist/Standards/NftStandards/ERC721/ERC721Standard.mjs +9 -0
  33. package/dist/Standards/NftStandards/ERC721/ERC721Standard.mjs.map +1 -0
  34. package/dist/TokenBalancesController.js +11 -144
  35. package/dist/TokenBalancesController.js.map +1 -1
  36. package/dist/TokenBalancesController.mjs +12 -0
  37. package/dist/TokenBalancesController.mjs.map +1 -0
  38. package/dist/TokenDetectionController.js +16 -245
  39. package/dist/TokenDetectionController.js.map +1 -1
  40. package/dist/TokenDetectionController.mjs +17 -0
  41. package/dist/TokenDetectionController.mjs.map +1 -0
  42. package/dist/TokenListController.js +13 -250
  43. package/dist/TokenListController.js.map +1 -1
  44. package/dist/TokenListController.mjs +14 -0
  45. package/dist/TokenListController.mjs.map +1 -0
  46. package/dist/TokenRatesController.js +11 -328
  47. package/dist/TokenRatesController.js.map +1 -1
  48. package/dist/TokenRatesController.mjs +12 -0
  49. package/dist/TokenRatesController.mjs.map +1 -0
  50. package/dist/TokensController.js +15 -636
  51. package/dist/TokensController.js.map +1 -1
  52. package/dist/TokensController.mjs +16 -0
  53. package/dist/TokensController.mjs.map +1 -0
  54. package/dist/assetsUtil.js +41 -380
  55. package/dist/assetsUtil.js.map +1 -1
  56. package/dist/assetsUtil.mjs +42 -0
  57. package/dist/assetsUtil.mjs.map +1 -0
  58. package/dist/chunk-23F5W3A2.mjs +157 -0
  59. package/dist/chunk-23F5W3A2.mjs.map +1 -0
  60. package/dist/chunk-27KOXCQK.mjs +1 -0
  61. package/dist/chunk-27KOXCQK.mjs.map +1 -0
  62. package/dist/chunk-3FMWI46J.mjs +361 -0
  63. package/dist/chunk-3FMWI46J.mjs.map +1 -0
  64. package/dist/chunk-3FOTFZIL.mjs +411 -0
  65. package/dist/chunk-3FOTFZIL.mjs.map +1 -0
  66. package/dist/chunk-4LY47RPI.mjs +139 -0
  67. package/dist/chunk-4LY47RPI.mjs.map +1 -0
  68. package/dist/chunk-5C7ZVZNM.mjs +267 -0
  69. package/dist/chunk-5C7ZVZNM.mjs.map +1 -0
  70. package/dist/chunk-64EHFYLM.mjs +245 -0
  71. package/dist/chunk-64EHFYLM.mjs.map +1 -0
  72. package/dist/chunk-6C2ZIK7A.js +245 -0
  73. package/dist/chunk-6C2ZIK7A.js.map +1 -0
  74. package/dist/chunk-6DTCHPBB.mjs +178 -0
  75. package/dist/chunk-6DTCHPBB.mjs.map +1 -0
  76. package/dist/chunk-74IP34EL.js +1177 -0
  77. package/dist/chunk-74IP34EL.js.map +1 -0
  78. package/dist/chunk-BZI7P3TD.js +115 -0
  79. package/dist/chunk-BZI7P3TD.js.map +1 -0
  80. package/dist/chunk-C4PQK53K.js +32 -0
  81. package/dist/chunk-C4PQK53K.js.map +1 -0
  82. package/dist/chunk-CP3HC7AQ.mjs +12 -0
  83. package/dist/chunk-CP3HC7AQ.mjs.map +1 -0
  84. package/dist/chunk-GHZX5DE4.js +215 -0
  85. package/dist/chunk-GHZX5DE4.js.map +1 -0
  86. package/dist/chunk-GMKIOYCB.js +361 -0
  87. package/dist/chunk-GMKIOYCB.js.map +1 -0
  88. package/dist/chunk-H6TOSWUM.js +157 -0
  89. package/dist/chunk-H6TOSWUM.js.map +1 -0
  90. package/dist/chunk-HWFBJFHS.js +284 -0
  91. package/dist/chunk-HWFBJFHS.js.map +1 -0
  92. package/dist/chunk-J2JQQNHN.mjs +115 -0
  93. package/dist/chunk-J2JQQNHN.mjs.map +1 -0
  94. package/dist/chunk-J6HPEQL3.mjs +704 -0
  95. package/dist/chunk-J6HPEQL3.mjs.map +1 -0
  96. package/dist/chunk-JC4WAN2J.mjs +1177 -0
  97. package/dist/chunk-JC4WAN2J.mjs.map +1 -0
  98. package/dist/chunk-LD4GC7OR.js +139 -0
  99. package/dist/chunk-LD4GC7OR.js.map +1 -0
  100. package/dist/chunk-NG2UOKDD.js +178 -0
  101. package/dist/chunk-NG2UOKDD.js.map +1 -0
  102. package/dist/chunk-NGIXA5M5.mjs +418 -0
  103. package/dist/chunk-NGIXA5M5.mjs.map +1 -0
  104. package/dist/chunk-NLNXQHAU.js +704 -0
  105. package/dist/chunk-NLNXQHAU.js.map +1 -0
  106. package/dist/chunk-OBUR4TXH.js +1 -0
  107. package/dist/chunk-OBUR4TXH.js.map +1 -0
  108. package/dist/chunk-PAJTKWEC.mjs +246 -0
  109. package/dist/chunk-PAJTKWEC.mjs.map +1 -0
  110. package/dist/chunk-PRIXT2R6.js +411 -0
  111. package/dist/chunk-PRIXT2R6.js.map +1 -0
  112. package/dist/chunk-PUFSYRJZ.js +74 -0
  113. package/dist/chunk-PUFSYRJZ.js.map +1 -0
  114. package/dist/chunk-QHRPRO5U.mjs +74 -0
  115. package/dist/chunk-QHRPRO5U.mjs.map +1 -0
  116. package/dist/chunk-QR4CX2JT.mjs +284 -0
  117. package/dist/chunk-QR4CX2JT.mjs.map +1 -0
  118. package/dist/chunk-RGHTNZQ6.js +12 -0
  119. package/dist/chunk-RGHTNZQ6.js.map +1 -0
  120. package/dist/chunk-TCO22VIO.mjs +32 -0
  121. package/dist/chunk-TCO22VIO.mjs.map +1 -0
  122. package/dist/chunk-TDKCVCGP.mjs +215 -0
  123. package/dist/chunk-TDKCVCGP.mjs.map +1 -0
  124. package/dist/chunk-UAH5YURZ.js +343 -0
  125. package/dist/chunk-UAH5YURZ.js.map +1 -0
  126. package/dist/chunk-V4ZO3F2S.js +246 -0
  127. package/dist/chunk-V4ZO3F2S.js.map +1 -0
  128. package/dist/chunk-VDJBJAUB.js +418 -0
  129. package/dist/chunk-VDJBJAUB.js.map +1 -0
  130. package/dist/chunk-WRQ7POD7.mjs +343 -0
  131. package/dist/chunk-WRQ7POD7.mjs.map +1 -0
  132. package/dist/chunk-XUI43LEZ.mjs +30 -0
  133. package/dist/chunk-XUI43LEZ.mjs.map +1 -0
  134. package/dist/chunk-YD3NRMFC.js +267 -0
  135. package/dist/chunk-YD3NRMFC.js.map +1 -0
  136. package/dist/chunk-Z4BLTVTB.js +30 -0
  137. package/dist/chunk-Z4BLTVTB.js.map +1 -0
  138. package/dist/constants.js +7 -9
  139. package/dist/constants.js.map +1 -1
  140. package/dist/constants.mjs +8 -0
  141. package/dist/constants.mjs.map +1 -0
  142. package/dist/crypto-compare.js +7 -66
  143. package/dist/crypto-compare.js.map +1 -1
  144. package/dist/crypto-compare.mjs +8 -0
  145. package/dist/crypto-compare.mjs.map +1 -0
  146. package/dist/index.js +72 -36
  147. package/dist/index.js.map +1 -1
  148. package/dist/index.mjs +73 -0
  149. package/dist/index.mjs.map +1 -0
  150. package/dist/token-prices-service/abstract-token-prices-service.js +1 -3
  151. package/dist/token-prices-service/abstract-token-prices-service.js.map +1 -1
  152. package/dist/token-prices-service/abstract-token-prices-service.mjs +1 -0
  153. package/dist/token-prices-service/abstract-token-prices-service.mjs.map +1 -0
  154. package/dist/token-prices-service/codefi-v2.js +11 -353
  155. package/dist/token-prices-service/codefi-v2.js.map +1 -1
  156. package/dist/token-prices-service/codefi-v2.mjs +12 -0
  157. package/dist/token-prices-service/codefi-v2.mjs.map +1 -0
  158. package/dist/token-prices-service/index.js +8 -5
  159. package/dist/token-prices-service/index.js.map +1 -1
  160. package/dist/token-prices-service/index.mjs +9 -0
  161. package/dist/token-prices-service/index.mjs.map +1 -0
  162. package/dist/token-service.js +14 -133
  163. package/dist/token-service.js.map +1 -1
  164. package/dist/token-service.mjs +15 -0
  165. package/dist/token-service.mjs.map +1 -0
  166. package/dist/tsconfig.build.tsbuildinfo +1 -0
  167. package/dist/types/AccountTrackerController.d.ts.map +1 -0
  168. package/dist/{AssetsContractController.d.ts → types/AssetsContractController.d.ts} +5 -6
  169. package/dist/types/AssetsContractController.d.ts.map +1 -0
  170. package/dist/types/CurrencyRateController.d.ts.map +1 -0
  171. package/dist/types/NftController.d.ts.map +1 -0
  172. package/dist/types/NftDetectionController.d.ts.map +1 -0
  173. package/dist/{Standards → types/Standards}/ERC20Standard.d.ts +1 -2
  174. package/dist/types/Standards/ERC20Standard.d.ts.map +1 -0
  175. package/dist/{Standards → types/Standards}/NftStandards/ERC1155/ERC1155Standard.d.ts +1 -2
  176. package/dist/types/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts.map +1 -0
  177. package/dist/types/Standards/NftStandards/ERC721/ERC721Standard.d.ts.map +1 -0
  178. package/dist/{TokenBalancesController.d.ts → types/TokenBalancesController.d.ts} +12 -10
  179. package/dist/types/TokenBalancesController.d.ts.map +1 -0
  180. package/dist/types/TokenDetectionController.d.ts +111 -0
  181. package/dist/types/TokenDetectionController.d.ts.map +1 -0
  182. package/dist/types/TokenListController.d.ts.map +1 -0
  183. package/dist/types/TokenRatesController.d.ts.map +1 -0
  184. package/dist/{TokensController.d.ts → types/TokensController.d.ts} +26 -19
  185. package/dist/types/TokensController.d.ts.map +1 -0
  186. package/dist/{assetsUtil.d.ts → types/assetsUtil.d.ts} +1 -2
  187. package/dist/types/assetsUtil.d.ts.map +1 -0
  188. package/dist/types/constants.d.ts.map +1 -0
  189. package/dist/types/crypto-compare.d.ts.map +1 -0
  190. package/dist/{index.d.ts → types/index.d.ts} +6 -3
  191. package/dist/types/index.d.ts.map +1 -0
  192. package/dist/types/token-prices-service/abstract-token-prices-service.d.ts.map +1 -0
  193. package/dist/types/token-prices-service/codefi-v2.d.ts.map +1 -0
  194. package/dist/types/token-prices-service/index.d.ts.map +1 -0
  195. package/dist/types/token-service.d.ts.map +1 -0
  196. package/package.json +30 -13
  197. package/dist/AccountTrackerController.d.ts.map +0 -1
  198. package/dist/AssetsContractController.d.ts.map +0 -1
  199. package/dist/CurrencyRateController.d.ts.map +0 -1
  200. package/dist/NftController.d.ts.map +0 -1
  201. package/dist/NftDetectionController.d.ts.map +0 -1
  202. package/dist/Standards/ERC20Standard.d.ts.map +0 -1
  203. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts.map +0 -1
  204. package/dist/Standards/NftStandards/ERC721/ERC721Standard.d.ts.map +0 -1
  205. package/dist/Standards/standards-types.d.ts +0 -15
  206. package/dist/Standards/standards-types.d.ts.map +0 -1
  207. package/dist/Standards/standards-types.js +0 -3
  208. package/dist/Standards/standards-types.js.map +0 -1
  209. package/dist/TokenBalancesController.d.ts.map +0 -1
  210. package/dist/TokenDetectionController.d.ts +0 -88
  211. package/dist/TokenDetectionController.d.ts.map +0 -1
  212. package/dist/TokenListController.d.ts.map +0 -1
  213. package/dist/TokenRatesController.d.ts.map +0 -1
  214. package/dist/TokensController.d.ts.map +0 -1
  215. package/dist/assetsUtil.d.ts.map +0 -1
  216. package/dist/constants.d.ts.map +0 -1
  217. package/dist/crypto-compare.d.ts.map +0 -1
  218. package/dist/index.d.ts.map +0 -1
  219. package/dist/token-prices-service/abstract-token-prices-service.d.ts.map +0 -1
  220. package/dist/token-prices-service/codefi-v2.d.ts.map +0 -1
  221. package/dist/token-prices-service/index.d.ts.map +0 -1
  222. package/dist/token-service.d.ts.map +0 -1
  223. /package/dist/{AccountTrackerController.d.ts → types/AccountTrackerController.d.ts} +0 -0
  224. /package/dist/{CurrencyRateController.d.ts → types/CurrencyRateController.d.ts} +0 -0
  225. /package/dist/{NftController.d.ts → types/NftController.d.ts} +0 -0
  226. /package/dist/{NftDetectionController.d.ts → types/NftDetectionController.d.ts} +0 -0
  227. /package/dist/{Standards → types/Standards}/NftStandards/ERC721/ERC721Standard.d.ts +0 -0
  228. /package/dist/{TokenListController.d.ts → types/TokenListController.d.ts} +0 -0
  229. /package/dist/{TokenRatesController.d.ts → types/TokenRatesController.d.ts} +0 -0
  230. /package/dist/{constants.d.ts → types/constants.d.ts} +0 -0
  231. /package/dist/{crypto-compare.d.ts → types/crypto-compare.d.ts} +0 -0
  232. /package/dist/{token-prices-service → types/token-prices-service}/abstract-token-prices-service.d.ts +0 -0
  233. /package/dist/{token-prices-service → types/token-prices-service}/codefi-v2.d.ts +0 -0
  234. /package/dist/{token-prices-service → types/token-prices-service}/index.d.ts +0 -0
  235. /package/dist/{token-service.d.ts → types/token-service.d.ts} +0 -0
@@ -1,251 +1,14 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
12
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
13
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
14
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
15
- };
16
- var _TokenListController_instances, _TokenListController_onNetworkControllerStateChange, _TokenListController_fetchFromCache;
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.TokenListController = exports.getDefaultTokenListState = void 0;
19
- const controller_utils_1 = require("@metamask/controller-utils");
20
- const polling_controller_1 = require("@metamask/polling-controller");
21
- const async_mutex_1 = require("async-mutex");
22
- const assetsUtil_1 = require("./assetsUtil");
23
- const token_service_1 = require("./token-service");
24
- const DEFAULT_INTERVAL = 24 * 60 * 60 * 1000;
25
- const DEFAULT_THRESHOLD = 24 * 60 * 60 * 1000;
26
- const name = 'TokenListController';
27
- const metadata = {
28
- tokenList: { persist: true, anonymous: true },
29
- tokensChainsCache: { persist: true, anonymous: true },
30
- preventPollingOnNetworkRestart: { persist: true, anonymous: true },
31
- };
32
- const getDefaultTokenListState = () => {
33
- return {
34
- tokenList: {},
35
- tokensChainsCache: {},
36
- preventPollingOnNetworkRestart: false,
37
- };
38
- };
39
- exports.getDefaultTokenListState = getDefaultTokenListState;
40
- /**
41
- * Controller that passively polls on a set interval for the list of tokens from metaswaps api
42
- */
43
- class TokenListController extends polling_controller_1.StaticIntervalPollingController {
44
- /**
45
- * Creates a TokenListController instance.
46
- *
47
- * @param options - The controller options.
48
- * @param options.chainId - The chain ID of the current network.
49
- * @param options.onNetworkStateChange - A function for registering an event handler for network state changes.
50
- * @param options.interval - The polling interval, in milliseconds.
51
- * @param options.cacheRefreshThreshold - The token cache expiry time, in milliseconds.
52
- * @param options.messenger - A restricted controller messenger.
53
- * @param options.state - Initial state to set on this controller.
54
- * @param options.preventPollingOnNetworkRestart - Determines whether to prevent poilling on network restart in extension.
55
- */
56
- constructor({ chainId, preventPollingOnNetworkRestart = false, onNetworkStateChange, interval = DEFAULT_INTERVAL, cacheRefreshThreshold = DEFAULT_THRESHOLD, messenger, state, }) {
57
- super({
58
- name,
59
- metadata,
60
- messenger,
61
- state: Object.assign(Object.assign({}, (0, exports.getDefaultTokenListState)()), state),
62
- });
63
- _TokenListController_instances.add(this);
64
- this.mutex = new async_mutex_1.Mutex();
65
- this.intervalDelay = interval;
66
- this.cacheRefreshThreshold = cacheRefreshThreshold;
67
- this.chainId = chainId;
68
- this.updatePreventPollingOnNetworkRestart(preventPollingOnNetworkRestart);
69
- this.abortController = new AbortController();
70
- if (onNetworkStateChange) {
71
- onNetworkStateChange((networkControllerState) => __awaiter(this, void 0, void 0, function* () {
72
- yield __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_onNetworkControllerStateChange).call(this, networkControllerState);
73
- }));
74
- }
75
- else {
76
- this.messagingSystem.subscribe('NetworkController:stateChange', (networkControllerState) => __awaiter(this, void 0, void 0, function* () {
77
- yield __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_onNetworkControllerStateChange).call(this, networkControllerState);
78
- }));
79
- }
80
- }
81
- /**
82
- * Start polling for the token list.
83
- */
84
- start() {
85
- return __awaiter(this, void 0, void 0, function* () {
86
- if (!(0, assetsUtil_1.isTokenListSupportedForNetwork)(this.chainId)) {
87
- return;
88
- }
89
- yield this.startPolling();
90
- });
91
- }
92
- /**
93
- * Restart polling for the token list.
94
- */
95
- restart() {
96
- return __awaiter(this, void 0, void 0, function* () {
97
- this.stopPolling();
98
- yield this.startPolling();
99
- });
100
- }
101
- /**
102
- * Stop polling for the token list.
103
- */
104
- stop() {
105
- this.stopPolling();
106
- }
107
- /**
108
- * Prepare to discard this controller.
109
- *
110
- * This stops any active polling.
111
- */
112
- destroy() {
113
- super.destroy();
114
- this.stopPolling();
115
- }
116
- stopPolling() {
117
- if (this.intervalId) {
118
- clearInterval(this.intervalId);
119
- }
120
- }
121
- /**
122
- * Starts a new polling interval.
123
- */
124
- startPolling() {
125
- return __awaiter(this, void 0, void 0, function* () {
126
- yield (0, controller_utils_1.safelyExecute)(() => this.fetchTokenList());
127
- this.intervalId = setInterval(() => __awaiter(this, void 0, void 0, function* () {
128
- yield (0, controller_utils_1.safelyExecute)(() => this.fetchTokenList());
129
- }), this.intervalDelay);
130
- });
131
- }
132
- /**
133
- * Fetching token list from the Token Service API.
134
- *
135
- * @private
136
- * @param networkClientId - The ID of the network client triggering the fetch.
137
- * @returns A promise that resolves when this operation completes.
138
- */
139
- _executePoll(networkClientId) {
140
- return __awaiter(this, void 0, void 0, function* () {
141
- return this.fetchTokenList(networkClientId);
142
- });
143
- }
144
- /**
145
- * Fetching token list from the Token Service API.
146
- *
147
- * @param networkClientId - The ID of the network client triggering the fetch.
148
- */
149
- fetchTokenList(networkClientId) {
150
- var _a, _b;
151
- return __awaiter(this, void 0, void 0, function* () {
152
- const releaseLock = yield this.mutex.acquire();
153
- let networkClient;
154
- if (networkClientId) {
155
- networkClient = this.messagingSystem.call('NetworkController:getNetworkClientById', networkClientId);
156
- }
157
- const chainId = (_a = networkClient === null || networkClient === void 0 ? void 0 : networkClient.configuration.chainId) !== null && _a !== void 0 ? _a : this.chainId;
158
- try {
159
- const { tokensChainsCache } = this.state;
160
- let tokenList = {};
161
- const cachedTokens = yield (0, controller_utils_1.safelyExecute)(() => __classPrivateFieldGet(this, _TokenListController_instances, "m", _TokenListController_fetchFromCache).call(this, chainId));
162
- if (cachedTokens) {
163
- // Use non-expired cached tokens
164
- tokenList = Object.assign({}, cachedTokens);
165
- }
166
- else {
167
- // Fetch fresh token list
168
- const tokensFromAPI = yield (0, controller_utils_1.safelyExecute)(() => (0, token_service_1.fetchTokenListByChainId)(chainId, this.abortController.signal));
169
- if (!tokensFromAPI) {
170
- // Fallback to expired cached tokens
171
- tokenList = Object.assign({}, (((_b = tokensChainsCache[chainId]) === null || _b === void 0 ? void 0 : _b.data) || {}));
172
- this.update(() => {
173
- return Object.assign(Object.assign({}, this.state), { tokenList,
174
- tokensChainsCache });
175
- });
176
- return;
177
- }
178
- for (const token of tokensFromAPI) {
179
- const formattedToken = Object.assign(Object.assign({}, token), { aggregators: (0, assetsUtil_1.formatAggregatorNames)(token.aggregators), iconUrl: (0, assetsUtil_1.formatIconUrlWithProxy)({
180
- chainId,
181
- tokenAddress: token.address,
182
- }) });
183
- tokenList[token.address] = formattedToken;
184
- }
185
- }
186
- const updatedTokensChainsCache = Object.assign(Object.assign({}, tokensChainsCache), { [chainId]: {
187
- timestamp: Date.now(),
188
- data: tokenList,
189
- } });
190
- this.update(() => {
191
- return Object.assign(Object.assign({}, this.state), { tokenList, tokensChainsCache: updatedTokensChainsCache });
192
- });
193
- }
194
- finally {
195
- releaseLock();
196
- }
197
- });
198
- }
199
- /**
200
- * Clearing tokenList and tokensChainsCache explicitly.
201
- */
202
- clearingTokenListData() {
203
- this.update(() => {
204
- return Object.assign(Object.assign({}, this.state), { tokenList: {}, tokensChainsCache: {} });
205
- });
206
- }
207
- /**
208
- * Updates preventPollingOnNetworkRestart from extension.
209
- *
210
- * @param shouldPreventPolling - Determine whether to prevent polling on network change
211
- */
212
- updatePreventPollingOnNetworkRestart(shouldPreventPolling) {
213
- this.update(() => {
214
- return Object.assign(Object.assign({}, this.state), { preventPollingOnNetworkRestart: shouldPreventPolling });
215
- });
216
- }
217
- }
218
- exports.TokenListController = TokenListController;
219
- _TokenListController_instances = new WeakSet(), _TokenListController_onNetworkControllerStateChange = function _TokenListController_onNetworkControllerStateChange(networkControllerState) {
220
- return __awaiter(this, void 0, void 0, function* () {
221
- if (this.chainId !== networkControllerState.providerConfig.chainId) {
222
- this.abortController.abort();
223
- this.abortController = new AbortController();
224
- this.chainId = networkControllerState.providerConfig.chainId;
225
- if (this.state.preventPollingOnNetworkRestart) {
226
- this.clearingTokenListData();
227
- }
228
- else {
229
- // Ensure tokenList is referencing data from correct network
230
- this.update(() => {
231
- var _a;
232
- return Object.assign(Object.assign({}, this.state), { tokenList: ((_a = this.state.tokensChainsCache[this.chainId]) === null || _a === void 0 ? void 0 : _a.data) || {} });
233
- });
234
- yield this.restart();
235
- }
236
- }
237
- });
238
- }, _TokenListController_fetchFromCache = function _TokenListController_fetchFromCache(chainId) {
239
- return __awaiter(this, void 0, void 0, function* () {
240
- const { tokensChainsCache } = this.state;
241
- const dataCache = tokensChainsCache[chainId];
242
- const now = Date.now();
243
- if ((dataCache === null || dataCache === void 0 ? void 0 : dataCache.data) &&
244
- now - (dataCache === null || dataCache === void 0 ? void 0 : dataCache.timestamp) < this.cacheRefreshThreshold) {
245
- return dataCache.data;
246
- }
247
- return null;
248
- });
249
- };
250
- exports.default = TokenListController;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+ var _chunkHWFBJFHSjs = require('./chunk-HWFBJFHS.js');
6
+ require('./chunk-PUFSYRJZ.js');
7
+ require('./chunk-YD3NRMFC.js');
8
+ require('./chunk-Z4BLTVTB.js');
9
+
10
+
11
+
12
+
13
+ exports.TokenListController = _chunkHWFBJFHSjs.TokenListController; exports.default = _chunkHWFBJFHSjs.TokenListController_default; exports.getDefaultTokenListState = _chunkHWFBJFHSjs.getDefaultTokenListState;
251
14
  //# sourceMappingURL=TokenListController.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"TokenListController.js","sourceRoot":"","sources":["../src/TokenListController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAKA,iEAA2D;AAO3D,qEAA+E;AAE/E,6CAAoC;AAEpC,6CAIsB;AACtB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,kDA4RC;mKA7MuC,sBAAoC;;QACxE,IAAI,IAAI,CAAC,OAAO,KAAK,sBAAsB,CAAC,cAAc,CAAC,OAAO,EAAE;YAClE,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,CAAC;YAC7B,IAAI,CAAC,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC;YAC7C,IAAI,CAAC,OAAO,GAAG,sBAAsB,CAAC,cAAc,CAAC,OAAO,CAAC;YAC7D,IAAI,IAAI,CAAC,KAAK,CAAC,8BAA8B,EAAE;gBAC7C,IAAI,CAAC,qBAAqB,EAAE,CAAC;aAC9B;iBAAM;gBACL,4DAA4D;gBAC5D,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE;;oBACf,uCACK,IAAI,CAAC,KAAK,KACb,SAAS,EAAE,CAAA,MAAA,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC,IAAI,CAAC,OAAO,CAAC,0CAAE,IAAI,KAAI,EAAE,IACjE;gBACJ,CAAC,CAAC,CAAC;gBACH,MAAM,IAAI,CAAC,OAAO,EAAE,CAAC;aACtB;SACF;IACH,CAAC;sFAoJqB,OAAY;;QAChC,MAAM,EAAE,iBAAiB,EAAE,GAAmB,IAAI,CAAC,KAAK,CAAC;QACzD,MAAM,SAAS,GAAG,iBAAiB,CAAC,OAAO,CAAC,CAAC;QAC7C,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,IACE,CAAA,SAAS,aAAT,SAAS,uBAAT,SAAS,CAAE,IAAI;YACf,GAAG,IAAG,SAAS,aAAT,SAAS,uBAAT,SAAS,CAAE,SAAS,CAAA,GAAG,IAAI,CAAC,qBAAqB,EACvD;YACA,OAAO,SAAS,CAAC,IAAI,CAAC;SACvB;QACD,OAAO,IAAI,CAAC;IACd,CAAC;;AA8BH,kBAAe,mBAAmB,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { safelyExecute } from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkControllerStateChangeEvent,\n NetworkState,\n NetworkControllerGetNetworkClientByIdAction,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { Hex } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\n\nimport {\n isTokenListSupportedForNetwork,\n formatAggregatorNames,\n formatIconUrlWithProxy,\n} from './assetsUtil';\nimport { fetchTokenListByChainId } from './token-service';\n\nconst DEFAULT_INTERVAL = 24 * 60 * 60 * 1000;\nconst DEFAULT_THRESHOLD = 24 * 60 * 60 * 1000;\n\nconst name = 'TokenListController';\n\nexport type TokenListToken = {\n name: string;\n symbol: string;\n decimals: number;\n address: string;\n occurrences: number;\n aggregators: string[];\n iconUrl: string;\n};\n\nexport type TokenListMap = Record<string, TokenListToken>;\n\ntype DataCache = {\n timestamp: number;\n data: TokenListMap;\n};\ntype TokensChainsCache = {\n [chainId: Hex]: DataCache;\n};\n\nexport type TokenListState = {\n tokenList: TokenListMap;\n tokensChainsCache: TokensChainsCache;\n preventPollingOnNetworkRestart: boolean;\n};\n\nexport type TokenListStateChange = ControllerStateChangeEvent<\n typeof name,\n TokenListState\n>;\n\nexport type TokenListControllerEvents = TokenListStateChange;\n\nexport type GetTokenListState = ControllerGetStateAction<\n typeof name,\n TokenListState\n>;\n\nexport type TokenListControllerActions = GetTokenListState;\n\ntype AllowedActions = NetworkControllerGetNetworkClientByIdAction;\n\ntype AllowedEvents = NetworkControllerStateChangeEvent;\n\nexport type TokenListControllerMessenger = RestrictedControllerMessenger<\n typeof name,\n TokenListControllerActions | AllowedActions,\n TokenListControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\nconst metadata = {\n tokenList: { persist: true, anonymous: true },\n tokensChainsCache: { persist: true, anonymous: true },\n preventPollingOnNetworkRestart: { persist: true, anonymous: true },\n};\n\nexport const getDefaultTokenListState = (): TokenListState => {\n return {\n tokenList: {},\n tokensChainsCache: {},\n preventPollingOnNetworkRestart: false,\n };\n};\n\n/**\n * Controller that passively polls on a set interval for the list of tokens from metaswaps api\n */\nexport class TokenListController extends StaticIntervalPollingController<\n typeof name,\n TokenListState,\n TokenListControllerMessenger\n> {\n private readonly mutex = new Mutex();\n\n private intervalId?: ReturnType<typeof setTimeout>;\n\n private readonly intervalDelay: number;\n\n private readonly cacheRefreshThreshold: number;\n\n private chainId: Hex;\n\n private abortController: AbortController;\n\n /**\n * Creates a TokenListController instance.\n *\n * @param options - The controller options.\n * @param options.chainId - The chain ID of the current network.\n * @param options.onNetworkStateChange - A function for registering an event handler for network state changes.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.cacheRefreshThreshold - The token cache expiry time, in milliseconds.\n * @param options.messenger - A restricted controller messenger.\n * @param options.state - Initial state to set on this controller.\n * @param options.preventPollingOnNetworkRestart - Determines whether to prevent poilling on network restart in extension.\n */\n constructor({\n chainId,\n preventPollingOnNetworkRestart = false,\n onNetworkStateChange,\n interval = DEFAULT_INTERVAL,\n cacheRefreshThreshold = DEFAULT_THRESHOLD,\n messenger,\n state,\n }: {\n chainId: Hex;\n preventPollingOnNetworkRestart?: boolean;\n onNetworkStateChange?: (\n listener: (networkState: NetworkState) => void,\n ) => void;\n interval?: number;\n cacheRefreshThreshold?: number;\n messenger: TokenListControllerMessenger;\n state?: Partial<TokenListState>;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...getDefaultTokenListState(), ...state },\n });\n this.intervalDelay = interval;\n this.cacheRefreshThreshold = cacheRefreshThreshold;\n this.chainId = chainId;\n this.updatePreventPollingOnNetworkRestart(preventPollingOnNetworkRestart);\n this.abortController = new AbortController();\n if (onNetworkStateChange) {\n onNetworkStateChange(async (networkControllerState) => {\n await this.#onNetworkControllerStateChange(networkControllerState);\n });\n } else {\n this.messagingSystem.subscribe(\n 'NetworkController:stateChange',\n async (networkControllerState) => {\n await this.#onNetworkControllerStateChange(networkControllerState);\n },\n );\n }\n }\n\n /**\n * Updates state and restarts polling on changes to the network controller\n * state.\n *\n * @param networkControllerState - The updated network controller state.\n */\n async #onNetworkControllerStateChange(networkControllerState: NetworkState) {\n if (this.chainId !== networkControllerState.providerConfig.chainId) {\n this.abortController.abort();\n this.abortController = new AbortController();\n this.chainId = networkControllerState.providerConfig.chainId;\n if (this.state.preventPollingOnNetworkRestart) {\n this.clearingTokenListData();\n } else {\n // Ensure tokenList is referencing data from correct network\n this.update(() => {\n return {\n ...this.state,\n tokenList: this.state.tokensChainsCache[this.chainId]?.data || {},\n };\n });\n await this.restart();\n }\n }\n }\n\n /**\n * Start polling for the token list.\n */\n async start() {\n if (!isTokenListSupportedForNetwork(this.chainId)) {\n return;\n }\n await this.startPolling();\n }\n\n /**\n * Restart polling for the token list.\n */\n async restart() {\n this.stopPolling();\n await this.startPolling();\n }\n\n /**\n * Stop polling for the token list.\n */\n stop() {\n this.stopPolling();\n }\n\n /**\n * Prepare to discard this controller.\n *\n * This stops any active polling.\n */\n override destroy() {\n super.destroy();\n this.stopPolling();\n }\n\n private stopPolling() {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n }\n }\n\n /**\n * Starts a new polling interval.\n */\n private async startPolling(): Promise<void> {\n await safelyExecute(() => this.fetchTokenList());\n this.intervalId = setInterval(async () => {\n await safelyExecute(() => this.fetchTokenList());\n }, this.intervalDelay);\n }\n\n /**\n * Fetching token list from the Token Service API.\n *\n * @private\n * @param networkClientId - The ID of the network client triggering the fetch.\n * @returns A promise that resolves when this operation completes.\n */\n async _executePoll(networkClientId: string): Promise<void> {\n return this.fetchTokenList(networkClientId);\n }\n\n /**\n * Fetching token list from the Token Service API.\n *\n * @param networkClientId - The ID of the network client triggering the fetch.\n */\n async fetchTokenList(networkClientId?: NetworkClientId): Promise<void> {\n const releaseLock = await this.mutex.acquire();\n let networkClient;\n if (networkClientId) {\n networkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n }\n const chainId = networkClient?.configuration.chainId ?? this.chainId;\n try {\n const { tokensChainsCache } = this.state;\n let tokenList: TokenListMap = {};\n const cachedTokens = await safelyExecute(() =>\n this.#fetchFromCache(chainId),\n );\n if (cachedTokens) {\n // Use non-expired cached tokens\n tokenList = { ...cachedTokens };\n } else {\n // Fetch fresh token list\n const tokensFromAPI = await safelyExecute(\n () =>\n fetchTokenListByChainId(\n chainId,\n this.abortController.signal,\n ) as Promise<TokenListToken[]>,\n );\n\n if (!tokensFromAPI) {\n // Fallback to expired cached tokens\n tokenList = { ...(tokensChainsCache[chainId]?.data || {}) };\n this.update(() => {\n return {\n ...this.state,\n tokenList,\n tokensChainsCache,\n };\n });\n return;\n }\n for (const token of tokensFromAPI) {\n const formattedToken: TokenListToken = {\n ...token,\n aggregators: formatAggregatorNames(token.aggregators),\n iconUrl: formatIconUrlWithProxy({\n chainId,\n tokenAddress: token.address,\n }),\n };\n tokenList[token.address] = formattedToken;\n }\n }\n const updatedTokensChainsCache: TokensChainsCache = {\n ...tokensChainsCache,\n [chainId]: {\n timestamp: Date.now(),\n data: tokenList,\n },\n };\n this.update(() => {\n return {\n ...this.state,\n tokenList,\n tokensChainsCache: updatedTokensChainsCache,\n };\n });\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Checks if the Cache timestamp is valid,\n * if yes data in cache will be returned\n * otherwise null will be returned.\n * @param chainId - The chain ID of the network for which to fetch the cache.\n * @returns The cached data, or `null` if the cache was expired.\n */\n async #fetchFromCache(chainId: Hex): Promise<TokenListMap | null> {\n const { tokensChainsCache }: TokenListState = this.state;\n const dataCache = tokensChainsCache[chainId];\n const now = Date.now();\n if (\n dataCache?.data &&\n now - dataCache?.timestamp < this.cacheRefreshThreshold\n ) {\n return dataCache.data;\n }\n return null;\n }\n\n /**\n * Clearing tokenList and tokensChainsCache explicitly.\n */\n clearingTokenListData(): void {\n this.update(() => {\n return {\n ...this.state,\n tokenList: {},\n tokensChainsCache: {},\n };\n });\n }\n\n /**\n * Updates preventPollingOnNetworkRestart from extension.\n *\n * @param shouldPreventPolling - Determine whether to prevent polling on network change\n */\n updatePreventPollingOnNetworkRestart(shouldPreventPolling: boolean): void {\n this.update(() => {\n return {\n ...this.state,\n preventPollingOnNetworkRestart: shouldPreventPolling,\n };\n });\n }\n}\n\nexport default TokenListController;\n"]}
1
+ {"version":3,"sources":[],"names":[],"mappings":""}
@@ -0,0 +1,14 @@
1
+ import {
2
+ TokenListController,
3
+ TokenListController_default,
4
+ getDefaultTokenListState
5
+ } from "./chunk-QR4CX2JT.mjs";
6
+ import "./chunk-QHRPRO5U.mjs";
7
+ import "./chunk-5C7ZVZNM.mjs";
8
+ import "./chunk-XUI43LEZ.mjs";
9
+ export {
10
+ TokenListController,
11
+ TokenListController_default as default,
12
+ getDefaultTokenListState
13
+ };
14
+ //# sourceMappingURL=TokenListController.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,329 +1,12 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
12
- if (kind === "m") throw new TypeError("Private method is not writable");
13
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
14
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
15
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
16
- };
17
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
18
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
19
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
20
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
21
- };
22
- var _TokenRatesController_instances, _TokenRatesController_pollState, _TokenRatesController_tokenPricesService, _TokenRatesController_inProcessExchangeRateUpdates, _TokenRatesController_getTokenAddresses, _TokenRatesController_stopPoll, _TokenRatesController_poll, _TokenRatesController_fetchAndMapExchangeRates, _TokenRatesController_fetchAndMapExchangeRatesForSupportedNativeCurrency, _TokenRatesController_fetchAndMapExchangeRatesForUnsupportedNativeCurrency;
23
- Object.defineProperty(exports, "__esModule", { value: true });
24
- exports.TokenRatesController = void 0;
25
- const controller_utils_1 = require("@metamask/controller-utils");
26
- const polling_controller_1 = require("@metamask/polling-controller");
27
- const utils_1 = require("@metamask/utils");
28
- const lodash_1 = require("lodash");
29
- const assetsUtil_1 = require("./assetsUtil");
30
- const crypto_compare_1 = require("./crypto-compare");
31
- var PollState;
32
- (function (PollState) {
33
- PollState["Active"] = "Active";
34
- PollState["Inactive"] = "Inactive";
35
- })(PollState || (PollState = {}));
36
- /**
37
- * Uses the CryptoCompare API to fetch the exchange rate between one currency
38
- * and another, i.e., the multiplier to apply the amount of one currency in
39
- * order to convert it to another.
40
- *
41
- * @param args - The arguments to this function.
42
- * @param args.from - The currency to convert from.
43
- * @param args.to - The currency to convert to.
44
- * @returns The exchange rate between `fromCurrency` to `toCurrency` if one
45
- * exists, or null if one does not.
46
- */
47
- function getCurrencyConversionRate({ from, to, }) {
48
- return __awaiter(this, void 0, void 0, function* () {
49
- const includeUSDRate = false;
50
- try {
51
- const result = yield (0, crypto_compare_1.fetchExchangeRate)(to, from, includeUSDRate);
52
- return result.conversionRate;
53
- }
54
- catch (error) {
55
- if (error instanceof Error &&
56
- error.message.includes('market does not exist for this coin pair')) {
57
- return null;
58
- }
59
- throw error;
60
- }
61
- });
62
- }
63
- /**
64
- * Controller that passively polls on a set interval for token-to-fiat exchange rates
65
- * for tokens stored in the TokensController
66
- */
67
- class TokenRatesController extends polling_controller_1.StaticIntervalPollingControllerV1 {
68
- /**
69
- * Creates a TokenRatesController instance.
70
- *
71
- * @param options - The controller options.
72
- * @param options.interval - The polling interval in ms
73
- * @param options.threshold - The duration in ms before metadata fetched from CoinGecko is considered stale
74
- * @param options.getNetworkClientById - Gets the network client with the given id from the NetworkController.
75
- * @param options.chainId - The chain ID of the current network.
76
- * @param options.ticker - The ticker for the current network.
77
- * @param options.selectedAddress - The current selected address.
78
- * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.
79
- * @param options.onTokensStateChange - Allows subscribing to token controller state changes.
80
- * @param options.onNetworkStateChange - Allows subscribing to network state changes.
81
- * @param options.tokenPricesService - An object in charge of retrieving token prices.
82
- * @param config - Initial options used to configure this controller.
83
- * @param state - Initial state to set on this controller.
84
- */
85
- constructor({ interval = 3 * 60 * 1000, threshold = 6 * 60 * 60 * 1000, getNetworkClientById, chainId: initialChainId, ticker: initialTicker, selectedAddress: initialSelectedAddress, onPreferencesStateChange, onTokensStateChange, onNetworkStateChange, tokenPricesService, }, config, state) {
86
- super(config, state);
87
- _TokenRatesController_instances.add(this);
88
- _TokenRatesController_pollState.set(this, PollState.Inactive);
89
- _TokenRatesController_tokenPricesService.set(this, void 0);
90
- _TokenRatesController_inProcessExchangeRateUpdates.set(this, {});
91
- /**
92
- * Name of this controller used during composition
93
- */
94
- this.name = 'TokenRatesController';
95
- this.defaultConfig = {
96
- interval,
97
- threshold,
98
- disabled: false,
99
- nativeCurrency: initialTicker,
100
- chainId: initialChainId,
101
- selectedAddress: initialSelectedAddress,
102
- allTokens: {},
103
- allDetectedTokens: {},
104
- };
105
- this.defaultState = {
106
- contractExchangeRates: {},
107
- contractExchangeRatesByChainId: {},
108
- };
109
- this.initialize();
110
- this.setIntervalLength(interval);
111
- this.getNetworkClientById = getNetworkClientById;
112
- __classPrivateFieldSet(this, _TokenRatesController_tokenPricesService, tokenPricesService, "f");
113
- if (config === null || config === void 0 ? void 0 : config.disabled) {
114
- this.configure({ disabled: true }, false, false);
115
- }
116
- onPreferencesStateChange(({ selectedAddress }) => __awaiter(this, void 0, void 0, function* () {
117
- if (this.config.selectedAddress !== selectedAddress) {
118
- this.configure({ selectedAddress });
119
- if (__classPrivateFieldGet(this, _TokenRatesController_pollState, "f") === PollState.Active) {
120
- yield this.updateExchangeRates();
121
- }
122
- }
123
- }));
124
- onTokensStateChange(({ allTokens, allDetectedTokens }) => __awaiter(this, void 0, void 0, function* () {
125
- const previousTokenAddresses = __classPrivateFieldGet(this, _TokenRatesController_instances, "m", _TokenRatesController_getTokenAddresses).call(this, this.config.chainId);
126
- this.configure({ allTokens, allDetectedTokens });
127
- const newTokenAddresses = __classPrivateFieldGet(this, _TokenRatesController_instances, "m", _TokenRatesController_getTokenAddresses).call(this, this.config.chainId);
128
- if (!(0, lodash_1.isEqual)(previousTokenAddresses, newTokenAddresses) &&
129
- __classPrivateFieldGet(this, _TokenRatesController_pollState, "f") === PollState.Active) {
130
- yield this.updateExchangeRates();
131
- }
132
- }));
133
- onNetworkStateChange(({ providerConfig }) => __awaiter(this, void 0, void 0, function* () {
134
- const { chainId, ticker } = providerConfig;
135
- if (this.config.chainId !== chainId ||
136
- this.config.nativeCurrency !== ticker) {
137
- this.update({ contractExchangeRates: {} });
138
- this.configure({ chainId, nativeCurrency: ticker });
139
- if (__classPrivateFieldGet(this, _TokenRatesController_pollState, "f") === PollState.Active) {
140
- yield this.updateExchangeRates();
141
- }
142
- }
143
- }));
144
- }
145
- /**
146
- * Start (or restart) polling.
147
- */
148
- start() {
149
- return __awaiter(this, void 0, void 0, function* () {
150
- __classPrivateFieldGet(this, _TokenRatesController_instances, "m", _TokenRatesController_stopPoll).call(this);
151
- __classPrivateFieldSet(this, _TokenRatesController_pollState, PollState.Active, "f");
152
- yield __classPrivateFieldGet(this, _TokenRatesController_instances, "m", _TokenRatesController_poll).call(this);
153
- });
154
- }
155
- /**
156
- * Stop polling.
157
- */
158
- stop() {
159
- __classPrivateFieldGet(this, _TokenRatesController_instances, "m", _TokenRatesController_stopPoll).call(this);
160
- __classPrivateFieldSet(this, _TokenRatesController_pollState, PollState.Inactive, "f");
161
- }
162
- /**
163
- * Updates exchange rates for all tokens.
164
- */
165
- updateExchangeRates() {
166
- return __awaiter(this, void 0, void 0, function* () {
167
- const { chainId, nativeCurrency } = this.config;
168
- yield this.updateExchangeRatesByChainId({
169
- chainId,
170
- nativeCurrency,
171
- });
172
- });
173
- }
174
- /**
175
- * Updates exchange rates for all tokens.
176
- *
177
- * @param options - The options to fetch exchange rates.
178
- * @param options.chainId - The chain ID.
179
- * @param options.nativeCurrency - The ticker for the chain.
180
- */
181
- updateExchangeRatesByChainId({ chainId, nativeCurrency, }) {
182
- var _a;
183
- return __awaiter(this, void 0, void 0, function* () {
184
- if (this.disabled) {
185
- return;
186
- }
187
- const tokenAddresses = __classPrivateFieldGet(this, _TokenRatesController_instances, "m", _TokenRatesController_getTokenAddresses).call(this, chainId);
188
- if (tokenAddresses.length === 0) {
189
- return;
190
- }
191
- const updateKey = `${chainId}:${nativeCurrency}`;
192
- if (updateKey in __classPrivateFieldGet(this, _TokenRatesController_inProcessExchangeRateUpdates, "f")) {
193
- // This prevents redundant updates
194
- // This promise is resolved after the in-progress update has finished,
195
- // and state has been updated.
196
- yield __classPrivateFieldGet(this, _TokenRatesController_inProcessExchangeRateUpdates, "f")[updateKey];
197
- return;
198
- }
199
- const { promise: inProgressUpdate, resolve: updateSucceeded, reject: updateFailed, } = (0, utils_1.createDeferredPromise)({ suppressUnhandledRejection: true });
200
- __classPrivateFieldGet(this, _TokenRatesController_inProcessExchangeRateUpdates, "f")[updateKey] = inProgressUpdate;
201
- try {
202
- const newContractExchangeRates = yield __classPrivateFieldGet(this, _TokenRatesController_instances, "m", _TokenRatesController_fetchAndMapExchangeRates).call(this, {
203
- tokenAddresses,
204
- chainId,
205
- nativeCurrency,
206
- });
207
- const existingContractExchangeRates = this.state.contractExchangeRates;
208
- const updatedContractExchangeRates = chainId === this.config.chainId &&
209
- nativeCurrency === this.config.nativeCurrency
210
- ? newContractExchangeRates
211
- : existingContractExchangeRates;
212
- const existingContractExchangeRatesForChainId = (_a = this.state.contractExchangeRatesByChainId[chainId]) !== null && _a !== void 0 ? _a : {};
213
- const updatedContractExchangeRatesForChainId = Object.assign(Object.assign({}, this.state.contractExchangeRatesByChainId), { [chainId]: Object.assign(Object.assign({}, existingContractExchangeRatesForChainId), { [nativeCurrency]: Object.assign(Object.assign({}, existingContractExchangeRatesForChainId[nativeCurrency]), newContractExchangeRates) }) });
214
- this.update({
215
- contractExchangeRates: updatedContractExchangeRates,
216
- contractExchangeRatesByChainId: updatedContractExchangeRatesForChainId,
217
- });
218
- updateSucceeded();
219
- }
220
- catch (error) {
221
- updateFailed(error);
222
- throw error;
223
- }
224
- finally {
225
- delete __classPrivateFieldGet(this, _TokenRatesController_inProcessExchangeRateUpdates, "f")[updateKey];
226
- }
227
- });
228
- }
229
- /**
230
- * Updates token rates for the given networkClientId
231
- *
232
- * @param networkClientId - The network client ID used to get a ticker value.
233
- * @returns The controller state.
234
- */
235
- _executePoll(networkClientId) {
236
- return __awaiter(this, void 0, void 0, function* () {
237
- const networkClient = this.getNetworkClientById(networkClientId);
238
- yield this.updateExchangeRatesByChainId({
239
- chainId: networkClient.configuration.chainId,
240
- nativeCurrency: networkClient.configuration.ticker,
241
- });
242
- });
243
- }
244
- }
245
- exports.TokenRatesController = TokenRatesController;
246
- _TokenRatesController_pollState = new WeakMap(), _TokenRatesController_tokenPricesService = new WeakMap(), _TokenRatesController_inProcessExchangeRateUpdates = new WeakMap(), _TokenRatesController_instances = new WeakSet(), _TokenRatesController_getTokenAddresses = function _TokenRatesController_getTokenAddresses(chainId) {
247
- var _a, _b;
248
- const { allTokens, allDetectedTokens } = this.config;
249
- const tokens = ((_a = allTokens[chainId]) === null || _a === void 0 ? void 0 : _a[this.config.selectedAddress]) || [];
250
- const detectedTokens = ((_b = allDetectedTokens[chainId]) === null || _b === void 0 ? void 0 : _b[this.config.selectedAddress]) || [];
251
- return [
252
- ...new Set([...tokens, ...detectedTokens].map((token) => (0, controller_utils_1.toHex)((0, controller_utils_1.toChecksumHexAddress)(token.address)))),
253
- ].sort();
254
- }, _TokenRatesController_stopPoll = function _TokenRatesController_stopPoll() {
255
- if (this.handle) {
256
- clearTimeout(this.handle);
257
- }
258
- }, _TokenRatesController_poll = function _TokenRatesController_poll() {
259
- return __awaiter(this, void 0, void 0, function* () {
260
- yield (0, controller_utils_1.safelyExecute)(() => this.updateExchangeRates());
261
- // Poll using recursive `setTimeout` instead of `setInterval` so that
262
- // requests don't stack if they take longer than the polling interval
263
- this.handle = setTimeout(() => {
264
- __classPrivateFieldGet(this, _TokenRatesController_instances, "m", _TokenRatesController_poll).call(this);
265
- }, this.config.interval);
266
- });
267
- }, _TokenRatesController_fetchAndMapExchangeRates = function _TokenRatesController_fetchAndMapExchangeRates({ tokenAddresses, chainId, nativeCurrency, }) {
268
- return __awaiter(this, void 0, void 0, function* () {
269
- if (!__classPrivateFieldGet(this, _TokenRatesController_tokenPricesService, "f").validateChainIdSupported(chainId)) {
270
- return tokenAddresses.reduce((obj, tokenAddress) => {
271
- return Object.assign(Object.assign({}, obj), { [tokenAddress]: undefined });
272
- }, {});
273
- }
274
- if (__classPrivateFieldGet(this, _TokenRatesController_tokenPricesService, "f").validateCurrencySupported(nativeCurrency)) {
275
- return yield __classPrivateFieldGet(this, _TokenRatesController_instances, "m", _TokenRatesController_fetchAndMapExchangeRatesForSupportedNativeCurrency).call(this, {
276
- tokenAddresses,
277
- chainId,
278
- nativeCurrency,
279
- });
280
- }
281
- return yield __classPrivateFieldGet(this, _TokenRatesController_instances, "m", _TokenRatesController_fetchAndMapExchangeRatesForUnsupportedNativeCurrency).call(this, {
282
- tokenAddresses,
283
- nativeCurrency,
284
- });
285
- });
286
- }, _TokenRatesController_fetchAndMapExchangeRatesForSupportedNativeCurrency = function _TokenRatesController_fetchAndMapExchangeRatesForSupportedNativeCurrency({ tokenAddresses, chainId, nativeCurrency, }) {
287
- return __awaiter(this, void 0, void 0, function* () {
288
- const tokenPricesByTokenAddress = yield (0, assetsUtil_1.reduceInBatchesSerially)({
289
- values: [...tokenAddresses].sort(),
290
- batchSize: assetsUtil_1.TOKEN_PRICES_BATCH_SIZE,
291
- eachBatch: (allTokenPricesByTokenAddress, batch) => __awaiter(this, void 0, void 0, function* () {
292
- const tokenPricesByTokenAddressForBatch = yield __classPrivateFieldGet(this, _TokenRatesController_tokenPricesService, "f").fetchTokenPrices({
293
- tokenAddresses: batch,
294
- chainId,
295
- currency: nativeCurrency,
296
- });
297
- return Object.assign(Object.assign({}, allTokenPricesByTokenAddress), tokenPricesByTokenAddressForBatch);
298
- }),
299
- initialResult: {},
300
- });
301
- return Object.entries(tokenPricesByTokenAddress).reduce((obj, [tokenAddress, tokenPrice]) => {
302
- return Object.assign(Object.assign({}, obj), { [tokenAddress]: tokenPrice === null || tokenPrice === void 0 ? void 0 : tokenPrice.value });
303
- }, {});
304
- });
305
- }, _TokenRatesController_fetchAndMapExchangeRatesForUnsupportedNativeCurrency = function _TokenRatesController_fetchAndMapExchangeRatesForUnsupportedNativeCurrency({ tokenAddresses, nativeCurrency, }) {
306
- return __awaiter(this, void 0, void 0, function* () {
307
- const [contractExchangeRates, fallbackCurrencyToNativeCurrencyConversionRate,] = yield Promise.all([
308
- __classPrivateFieldGet(this, _TokenRatesController_instances, "m", _TokenRatesController_fetchAndMapExchangeRatesForSupportedNativeCurrency).call(this, {
309
- tokenAddresses,
310
- chainId: this.config.chainId,
311
- nativeCurrency: controller_utils_1.FALL_BACK_VS_CURRENCY,
312
- }),
313
- getCurrencyConversionRate({
314
- from: controller_utils_1.FALL_BACK_VS_CURRENCY,
315
- to: nativeCurrency,
316
- }),
317
- ]);
318
- if (fallbackCurrencyToNativeCurrencyConversionRate === null) {
319
- return {};
320
- }
321
- return Object.entries(contractExchangeRates).reduce((obj, [tokenAddress, tokenValue]) => {
322
- return Object.assign(Object.assign({}, obj), { [tokenAddress]: tokenValue
323
- ? tokenValue * fallbackCurrencyToNativeCurrencyConversionRate
324
- : undefined });
325
- }, {});
326
- });
327
- };
328
- exports.default = TokenRatesController;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+ var _chunkVDJBJAUBjs = require('./chunk-VDJBJAUB.js');
5
+ require('./chunk-C4PQK53K.js');
6
+ require('./chunk-YD3NRMFC.js');
7
+ require('./chunk-Z4BLTVTB.js');
8
+
9
+
10
+
11
+ exports.TokenRatesController = _chunkVDJBJAUBjs.TokenRatesController; exports.default = _chunkVDJBJAUBjs.TokenRatesController_default;
329
12
  //# sourceMappingURL=TokenRatesController.js.map