@metamask/assets-controllers 29.0.0 → 30.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 (176) hide show
  1. package/CHANGELOG.md +25 -1
  2. package/README.md +29 -0
  3. package/dist/AssetsContractController.js +6 -6
  4. package/dist/AssetsContractController.mjs +5 -5
  5. package/dist/CurrencyRateController.js +4 -3
  6. package/dist/CurrencyRateController.mjs +3 -2
  7. package/dist/NftController.js +3 -3
  8. package/dist/NftController.mjs +2 -2
  9. package/dist/NftDetectionController.js +2 -2
  10. package/dist/NftDetectionController.mjs +1 -1
  11. package/dist/RatesController/RatesController.js +14 -0
  12. package/dist/RatesController/RatesController.mjs +14 -0
  13. package/dist/RatesController/index.js +13 -0
  14. package/dist/RatesController/index.js.map +1 -0
  15. package/dist/RatesController/index.mjs +13 -0
  16. package/dist/RatesController/index.mjs.map +1 -0
  17. package/dist/RatesController/types.js +1 -0
  18. package/dist/RatesController/types.js.map +1 -0
  19. package/dist/RatesController/types.mjs +1 -0
  20. package/dist/RatesController/types.mjs.map +1 -0
  21. package/dist/Standards/ERC20Standard.js +3 -3
  22. package/dist/Standards/ERC20Standard.mjs +2 -2
  23. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js +3 -3
  24. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.mjs +2 -2
  25. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js +3 -3
  26. package/dist/Standards/NftStandards/ERC721/ERC721Standard.mjs +2 -2
  27. package/dist/TokenDetectionController.js +3 -3
  28. package/dist/TokenDetectionController.mjs +2 -2
  29. package/dist/TokenListController.js +4 -4
  30. package/dist/TokenListController.mjs +3 -3
  31. package/dist/TokenRatesController.js +6 -4
  32. package/dist/TokenRatesController.mjs +5 -3
  33. package/dist/TokensController.js +6 -6
  34. package/dist/TokensController.mjs +5 -5
  35. package/dist/assetsUtil.js +2 -2
  36. package/dist/assetsUtil.mjs +1 -1
  37. package/dist/{chunk-OHSQRYVL.js → chunk-3R43XIIX.js} +17 -6
  38. package/dist/chunk-3R43XIIX.js.map +1 -0
  39. package/dist/{chunk-S6CZP74C.mjs → chunk-46UZDIXW.mjs} +35 -12
  40. package/dist/chunk-46UZDIXW.mjs.map +1 -0
  41. package/dist/{chunk-QHU4H6HP.js → chunk-4ODKGWYQ.js} +7 -7
  42. package/dist/{chunk-DEQZ35QE.js → chunk-5F5EQAX5.js} +7 -7
  43. package/dist/{chunk-IOQX3VTD.js → chunk-6W5EQ3JQ.js} +56 -42
  44. package/dist/chunk-6W5EQ3JQ.js.map +1 -0
  45. package/dist/chunk-7K6PSEAA.js +1 -0
  46. package/dist/chunk-7K6PSEAA.js.map +1 -0
  47. package/dist/{chunk-6XOM7KOQ.mjs → chunk-7MMEHAKG.mjs} +7 -7
  48. package/dist/{chunk-V46CHMOU.mjs → chunk-ASA5RLBY.mjs} +2 -2
  49. package/dist/chunk-B5YVX5IO.mjs +202 -0
  50. package/dist/chunk-B5YVX5IO.mjs.map +1 -0
  51. package/dist/{chunk-BO2WZDUM.js → chunk-B5YY22QQ.js} +3 -3
  52. package/dist/{chunk-QWACHXRH.mjs → chunk-B6W4CQOR.mjs} +2 -2
  53. package/dist/chunk-B6W4CQOR.mjs.map +1 -0
  54. package/dist/{chunk-3ZHN4GFT.js → chunk-BOTVAG4A.js} +5 -5
  55. package/dist/chunk-CNKVITJO.mjs +66 -0
  56. package/dist/chunk-CNKVITJO.mjs.map +1 -0
  57. package/dist/{chunk-LLYYJY7H.mjs → chunk-D3K5MPMW.mjs} +2 -2
  58. package/dist/{chunk-LRKDZWS6.js → chunk-ELSMS5S7.js} +3 -3
  59. package/dist/chunk-ELSMS5S7.js.map +1 -0
  60. package/dist/{chunk-X2MMIBYW.js → chunk-FMZML3V5.js} +7 -5
  61. package/dist/chunk-FMZML3V5.js.map +1 -0
  62. package/dist/{chunk-I53XGBU3.js → chunk-HDI4L2DD.js} +5 -5
  63. package/dist/chunk-JYHAAA6W.mjs +1 -0
  64. package/dist/chunk-JYHAAA6W.mjs.map +1 -0
  65. package/dist/{chunk-ASFD56OL.mjs → chunk-KOKB6U4Z.mjs} +7 -5
  66. package/dist/{chunk-ASFD56OL.mjs.map → chunk-KOKB6U4Z.mjs.map} +1 -1
  67. package/dist/{chunk-KM3J4DO6.js → chunk-LAU6ZDZR.js} +37 -14
  68. package/dist/chunk-LAU6ZDZR.js.map +1 -0
  69. package/dist/{chunk-S7UA2DU7.mjs → chunk-LZ5ZGQEX.mjs} +2 -2
  70. package/dist/{chunk-SOK5YX7I.js → chunk-MBCN3MNX.js} +11 -11
  71. package/dist/{chunk-5MRF7YPD.mjs → chunk-MHN7CJCZ.mjs} +6 -6
  72. package/dist/{chunk-D3PCUDTX.mjs → chunk-MR6EF4B7.mjs} +2 -2
  73. package/dist/{chunk-LS6R3HQL.js → chunk-NEXY7SE2.js} +2 -2
  74. package/dist/chunk-NEXY7SE2.js.map +1 -0
  75. package/dist/{chunk-X5PLVMOQ.mjs → chunk-Q5JRBGWO.mjs} +2 -2
  76. package/dist/chunk-Q5JRBGWO.mjs.map +1 -0
  77. package/dist/chunk-TTH3ES66.mjs +1 -0
  78. package/dist/chunk-TTH3ES66.mjs.map +1 -0
  79. package/dist/{chunk-OBOWNEJU.js → chunk-U3DJJN4X.js} +4 -4
  80. package/dist/chunk-WB6KJX4N.js +66 -0
  81. package/dist/chunk-WB6KJX4N.js.map +1 -0
  82. package/dist/{chunk-OWTCG2N3.mjs → chunk-X4FFNQHE.mjs} +53 -39
  83. package/dist/chunk-X4FFNQHE.mjs.map +1 -0
  84. package/dist/chunk-XC3SOOGC.js +1 -0
  85. package/dist/chunk-XC3SOOGC.js.map +1 -0
  86. package/dist/{chunk-RUE635TV.mjs → chunk-XHMM35YT.mjs} +3 -3
  87. package/dist/{chunk-OSEZFHQ3.mjs → chunk-Y35SM7TO.mjs} +19 -14
  88. package/dist/chunk-Y35SM7TO.mjs.map +1 -0
  89. package/dist/chunk-YIFA2HXH.js +202 -0
  90. package/dist/chunk-YIFA2HXH.js.map +1 -0
  91. package/dist/{chunk-NXGX7LZJ.mjs → chunk-Z3OQU4XW.mjs} +17 -6
  92. package/dist/chunk-Z3OQU4XW.mjs.map +1 -0
  93. package/dist/{chunk-4FMVFW2T.js → chunk-Z6TBQQE5.js} +20 -15
  94. package/dist/chunk-Z6TBQQE5.js.map +1 -0
  95. package/dist/crypto-compare-service/crypto-compare.js +10 -0
  96. package/dist/crypto-compare-service/crypto-compare.js.map +1 -0
  97. package/dist/crypto-compare-service/crypto-compare.mjs +10 -0
  98. package/dist/crypto-compare-service/crypto-compare.mjs.map +1 -0
  99. package/dist/crypto-compare-service/index.js +11 -0
  100. package/dist/crypto-compare-service/index.js.map +1 -0
  101. package/dist/crypto-compare-service/index.mjs +11 -0
  102. package/dist/crypto-compare-service/index.mjs.map +1 -0
  103. package/dist/index.js +24 -16
  104. package/dist/index.mjs +25 -17
  105. package/dist/token-prices-service/codefi-v2.js +4 -2
  106. package/dist/token-prices-service/codefi-v2.mjs +5 -3
  107. package/dist/token-prices-service/index.js +2 -2
  108. package/dist/token-prices-service/index.mjs +1 -1
  109. package/dist/token-service.js +3 -3
  110. package/dist/token-service.mjs +2 -2
  111. package/dist/tsconfig.build.tsbuildinfo +1 -1
  112. package/dist/types/CurrencyRateController.d.ts +1 -1
  113. package/dist/types/CurrencyRateController.d.ts.map +1 -1
  114. package/dist/types/NftController.d.ts +3 -3
  115. package/dist/types/NftController.d.ts.map +1 -1
  116. package/dist/types/NftDetectionController.d.ts.map +1 -1
  117. package/dist/types/RatesController/RatesController.d.ts +44 -0
  118. package/dist/types/RatesController/RatesController.d.ts.map +1 -0
  119. package/dist/types/RatesController/index.d.ts +3 -0
  120. package/dist/types/RatesController/index.d.ts.map +1 -0
  121. package/dist/types/RatesController/types.d.ts +100 -0
  122. package/dist/types/RatesController/types.d.ts.map +1 -0
  123. package/dist/types/TokenRatesController.d.ts +26 -4
  124. package/dist/types/TokenRatesController.d.ts.map +1 -1
  125. package/dist/types/TokensController.d.ts +1 -1
  126. package/dist/types/TokensController.d.ts.map +1 -1
  127. package/dist/types/crypto-compare-service/crypto-compare.d.ts +22 -0
  128. package/dist/types/crypto-compare-service/crypto-compare.d.ts.map +1 -0
  129. package/dist/types/crypto-compare-service/index.d.ts +2 -0
  130. package/dist/types/crypto-compare-service/index.d.ts.map +1 -0
  131. package/dist/types/index.d.ts +2 -0
  132. package/dist/types/index.d.ts.map +1 -1
  133. package/dist/types/token-prices-service/abstract-token-prices-service.d.ts +18 -0
  134. package/dist/types/token-prices-service/abstract-token-prices-service.d.ts.map +1 -1
  135. package/dist/types/token-prices-service/codefi-v2.d.ts +7 -0
  136. package/dist/types/token-prices-service/codefi-v2.d.ts.map +1 -1
  137. package/dist/types/token-service.d.ts +1 -1
  138. package/dist/types/token-service.d.ts.map +1 -1
  139. package/package.json +5 -5
  140. package/dist/chunk-4FMVFW2T.js.map +0 -1
  141. package/dist/chunk-DYH5P3VY.js +0 -35
  142. package/dist/chunk-DYH5P3VY.js.map +0 -1
  143. package/dist/chunk-IOQX3VTD.js.map +0 -1
  144. package/dist/chunk-KM3J4DO6.js.map +0 -1
  145. package/dist/chunk-LRKDZWS6.js.map +0 -1
  146. package/dist/chunk-LS6R3HQL.js.map +0 -1
  147. package/dist/chunk-NXGX7LZJ.mjs.map +0 -1
  148. package/dist/chunk-OHSQRYVL.js.map +0 -1
  149. package/dist/chunk-OSEZFHQ3.mjs.map +0 -1
  150. package/dist/chunk-OWTCG2N3.mjs.map +0 -1
  151. package/dist/chunk-PWZE6KJV.mjs +0 -35
  152. package/dist/chunk-PWZE6KJV.mjs.map +0 -1
  153. package/dist/chunk-QWACHXRH.mjs.map +0 -1
  154. package/dist/chunk-S6CZP74C.mjs.map +0 -1
  155. package/dist/chunk-X2MMIBYW.js.map +0 -1
  156. package/dist/chunk-X5PLVMOQ.mjs.map +0 -1
  157. package/dist/crypto-compare.js +0 -8
  158. package/dist/crypto-compare.mjs +0 -8
  159. package/dist/types/crypto-compare.d.ts +0 -13
  160. package/dist/types/crypto-compare.d.ts.map +0 -1
  161. /package/dist/{crypto-compare.js.map → RatesController/RatesController.js.map} +0 -0
  162. /package/dist/{crypto-compare.mjs.map → RatesController/RatesController.mjs.map} +0 -0
  163. /package/dist/{chunk-QHU4H6HP.js.map → chunk-4ODKGWYQ.js.map} +0 -0
  164. /package/dist/{chunk-DEQZ35QE.js.map → chunk-5F5EQAX5.js.map} +0 -0
  165. /package/dist/{chunk-6XOM7KOQ.mjs.map → chunk-7MMEHAKG.mjs.map} +0 -0
  166. /package/dist/{chunk-V46CHMOU.mjs.map → chunk-ASA5RLBY.mjs.map} +0 -0
  167. /package/dist/{chunk-BO2WZDUM.js.map → chunk-B5YY22QQ.js.map} +0 -0
  168. /package/dist/{chunk-3ZHN4GFT.js.map → chunk-BOTVAG4A.js.map} +0 -0
  169. /package/dist/{chunk-LLYYJY7H.mjs.map → chunk-D3K5MPMW.mjs.map} +0 -0
  170. /package/dist/{chunk-I53XGBU3.js.map → chunk-HDI4L2DD.js.map} +0 -0
  171. /package/dist/{chunk-S7UA2DU7.mjs.map → chunk-LZ5ZGQEX.mjs.map} +0 -0
  172. /package/dist/{chunk-SOK5YX7I.js.map → chunk-MBCN3MNX.js.map} +0 -0
  173. /package/dist/{chunk-5MRF7YPD.mjs.map → chunk-MHN7CJCZ.mjs.map} +0 -0
  174. /package/dist/{chunk-D3PCUDTX.mjs.map → chunk-MR6EF4B7.mjs.map} +0 -0
  175. /package/dist/{chunk-OBOWNEJU.js.map → chunk-U3DJJN4X.js.map} +0 -0
  176. /package/dist/{chunk-RUE635TV.mjs.map → chunk-XHMM35YT.mjs.map} +0 -0
@@ -1,17 +1,17 @@
1
- import {
2
- ERC1155Standard
3
- } from "./chunk-S7UA2DU7.mjs";
4
1
  import {
5
2
  ERC20Standard
6
- } from "./chunk-LLYYJY7H.mjs";
3
+ } from "./chunk-D3K5MPMW.mjs";
4
+ import {
5
+ ERC1155Standard
6
+ } from "./chunk-LZ5ZGQEX.mjs";
7
7
  import {
8
8
  TOKEN_METADATA_NO_SUPPORT_ERROR,
9
9
  fetchTokenMetadata
10
- } from "./chunk-NXGX7LZJ.mjs";
10
+ } from "./chunk-Z3OQU4XW.mjs";
11
11
  import {
12
12
  formatAggregatorNames,
13
13
  formatIconUrlWithProxy
14
- } from "./chunk-X5PLVMOQ.mjs";
14
+ } from "./chunk-Q5JRBGWO.mjs";
15
15
 
16
16
  // src/TokensController.ts
17
17
  import { Contract } from "@ethersproject/contracts";
@@ -701,4 +701,4 @@ export {
701
701
  TokensController,
702
702
  TokensController_default
703
703
  };
704
- //# sourceMappingURL=chunk-6XOM7KOQ.mjs.map
704
+ //# sourceMappingURL=chunk-7MMEHAKG.mjs.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getFormattedIpfsUrl
3
- } from "./chunk-X5PLVMOQ.mjs";
3
+ } from "./chunk-Q5JRBGWO.mjs";
4
4
 
5
5
  // src/Standards/NftStandards/ERC721/ERC721Standard.ts
6
6
  import { Contract } from "@ethersproject/contracts";
@@ -175,4 +175,4 @@ var ERC721Standard = class {
175
175
  export {
176
176
  ERC721Standard
177
177
  };
178
- //# sourceMappingURL=chunk-V46CHMOU.mjs.map
178
+ //# sourceMappingURL=chunk-ASA5RLBY.mjs.map
@@ -0,0 +1,202 @@
1
+ import {
2
+ fetchMultiExchangeRate
3
+ } from "./chunk-CNKVITJO.mjs";
4
+ import {
5
+ __privateAdd,
6
+ __privateGet,
7
+ __privateMethod,
8
+ __privateSet
9
+ } from "./chunk-XUI43LEZ.mjs";
10
+
11
+ // src/RatesController/RatesController.ts
12
+ import { BaseController } from "@metamask/base-controller";
13
+ import { Mutex } from "async-mutex";
14
+ var name = "RatesController";
15
+ var Cryptocurrency = /* @__PURE__ */ ((Cryptocurrency2) => {
16
+ Cryptocurrency2["Btc"] = "btc";
17
+ return Cryptocurrency2;
18
+ })(Cryptocurrency || {});
19
+ var DEFAULT_INTERVAL = 18e4;
20
+ var metadata = {
21
+ fiatCurrency: { persist: true, anonymous: true },
22
+ rates: { persist: true, anonymous: true },
23
+ cryptocurrencies: { persist: true, anonymous: true }
24
+ };
25
+ var defaultState = {
26
+ fiatCurrency: "usd",
27
+ rates: {
28
+ ["btc" /* Btc */]: {
29
+ conversionDate: 0,
30
+ conversionRate: "0"
31
+ }
32
+ },
33
+ cryptocurrencies: ["btc" /* Btc */]
34
+ };
35
+ var _mutex, _fetchMultiExchangeRate, _includeUsdRate, _intervalLength, _intervalId, _withLock, withLock_fn, _executePoll, executePoll_fn, _updateRates, updateRates_fn;
36
+ var RatesController = class extends BaseController {
37
+ /**
38
+ * Creates a RatesController instance.
39
+ *
40
+ * @param options - Constructor options.
41
+ * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.
42
+ * @param options.interval - The polling interval, in milliseconds.
43
+ * @param options.messenger - A reference to the messaging system.
44
+ * @param options.state - Initial state to set on this controller.
45
+ * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
46
+ */
47
+ constructor({
48
+ interval = DEFAULT_INTERVAL,
49
+ messenger,
50
+ state,
51
+ includeUsdRate,
52
+ fetchMultiExchangeRate: fetchMultiExchangeRate2 = fetchMultiExchangeRate
53
+ }) {
54
+ super({
55
+ name,
56
+ metadata,
57
+ messenger,
58
+ state: { ...defaultState, ...state }
59
+ });
60
+ /**
61
+ * Executes a function `callback` within a mutex lock to ensure that only one instance of `callback` runs at a time across all invocations of `#withLock`.
62
+ * This method is useful for synchronizing access to a resource or section of code that should not be executed concurrently.
63
+ *
64
+ * @template R - The return type of the function `callback`.
65
+ * @param callback - A callback to execute once the lock is acquired. This callback can be synchronous or asynchronous.
66
+ * @returns A promise that resolves to the result of the function `callback`. The promise is fulfilled once `callback` has completed execution.
67
+ * @example
68
+ * async function criticalLogic() {
69
+ * // Critical logic code goes here.
70
+ * }
71
+ *
72
+ * // Execute criticalLogic within a lock.
73
+ * const result = await this.#withLock(criticalLogic);
74
+ */
75
+ __privateAdd(this, _withLock);
76
+ /**
77
+ * Executes the polling operation to update rates.
78
+ */
79
+ __privateAdd(this, _executePoll);
80
+ /**
81
+ * Updates the rates by fetching new data.
82
+ */
83
+ __privateAdd(this, _updateRates);
84
+ __privateAdd(this, _mutex, new Mutex());
85
+ __privateAdd(this, _fetchMultiExchangeRate, void 0);
86
+ __privateAdd(this, _includeUsdRate, void 0);
87
+ __privateAdd(this, _intervalLength, void 0);
88
+ __privateAdd(this, _intervalId, void 0);
89
+ __privateSet(this, _includeUsdRate, includeUsdRate);
90
+ __privateSet(this, _fetchMultiExchangeRate, fetchMultiExchangeRate2);
91
+ __privateSet(this, _intervalLength, interval);
92
+ }
93
+ /**
94
+ * Starts the polling process.
95
+ */
96
+ async start() {
97
+ if (__privateGet(this, _intervalId)) {
98
+ return;
99
+ }
100
+ this.messagingSystem.publish(`${name}:pollingStarted`);
101
+ __privateSet(this, _intervalId, setInterval(() => {
102
+ __privateMethod(this, _executePoll, executePoll_fn).call(this).catch(console.error);
103
+ }, __privateGet(this, _intervalLength)));
104
+ }
105
+ /**
106
+ * Stops the polling process.
107
+ */
108
+ async stop() {
109
+ if (!__privateGet(this, _intervalId)) {
110
+ return;
111
+ }
112
+ clearInterval(__privateGet(this, _intervalId));
113
+ __privateSet(this, _intervalId, void 0);
114
+ this.messagingSystem.publish(`${name}:pollingStopped`);
115
+ }
116
+ /**
117
+ * Returns the current list of cryptocurrency.
118
+ * @returns The cryptocurrency list.
119
+ */
120
+ getCryptocurrencyList() {
121
+ const { cryptocurrencies } = this.state;
122
+ return cryptocurrencies;
123
+ }
124
+ /**
125
+ * Sets the list of supported cryptocurrencies.
126
+ * @param list - The list of supported cryptocurrencies.
127
+ */
128
+ async setCryptocurrencyList(list) {
129
+ await __privateMethod(this, _withLock, withLock_fn).call(this, () => {
130
+ this.update(() => {
131
+ return {
132
+ ...this.state,
133
+ fromCurrencies: list
134
+ };
135
+ });
136
+ });
137
+ }
138
+ /**
139
+ * Sets the internal fiat currency and update rates accordingly.
140
+ * @param fiatCurrency - The fiat currency.
141
+ */
142
+ async setFiatCurrency(fiatCurrency) {
143
+ if (fiatCurrency === "") {
144
+ throw new Error("The currency can not be an empty string");
145
+ }
146
+ await __privateMethod(this, _withLock, withLock_fn).call(this, () => {
147
+ this.update(() => {
148
+ return {
149
+ ...defaultState,
150
+ fiatCurrency
151
+ };
152
+ });
153
+ });
154
+ await __privateMethod(this, _updateRates, updateRates_fn).call(this);
155
+ }
156
+ };
157
+ _mutex = new WeakMap();
158
+ _fetchMultiExchangeRate = new WeakMap();
159
+ _includeUsdRate = new WeakMap();
160
+ _intervalLength = new WeakMap();
161
+ _intervalId = new WeakMap();
162
+ _withLock = new WeakSet();
163
+ withLock_fn = async function(callback) {
164
+ const releaseLock = await __privateGet(this, _mutex).acquire();
165
+ try {
166
+ return callback();
167
+ } finally {
168
+ releaseLock();
169
+ }
170
+ };
171
+ _executePoll = new WeakSet();
172
+ executePoll_fn = async function() {
173
+ await __privateMethod(this, _updateRates, updateRates_fn).call(this);
174
+ };
175
+ _updateRates = new WeakSet();
176
+ updateRates_fn = async function() {
177
+ await __privateMethod(this, _withLock, withLock_fn).call(this, async () => {
178
+ const { fiatCurrency, cryptocurrencies } = this.state;
179
+ const response = await __privateGet(this, _fetchMultiExchangeRate).call(this, fiatCurrency, cryptocurrencies, __privateGet(this, _includeUsdRate));
180
+ const updatedRates = {};
181
+ for (const [cryptocurrency, values] of Object.entries(response)) {
182
+ updatedRates[cryptocurrency] = {
183
+ conversionDate: Date.now(),
184
+ conversionRate: values[fiatCurrency],
185
+ ...__privateGet(this, _includeUsdRate) && { usdConversionRate: values.usd }
186
+ };
187
+ }
188
+ this.update(() => {
189
+ return {
190
+ ...this.state,
191
+ rates: updatedRates
192
+ };
193
+ });
194
+ });
195
+ };
196
+
197
+ export {
198
+ name,
199
+ Cryptocurrency,
200
+ RatesController
201
+ };
202
+ //# sourceMappingURL=chunk-B5YVX5IO.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/RatesController/RatesController.ts"],"sourcesContent":["import { BaseController } from '@metamask/base-controller';\nimport { Mutex } from 'async-mutex';\n\nimport { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n ConversionRates,\n RatesControllerState,\n RatesControllerOptions,\n RatesControllerMessenger,\n} from './types';\n\nexport const name = 'RatesController';\n\nexport enum Cryptocurrency {\n Btc = 'btc',\n}\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst metadata = {\n fiatCurrency: { persist: true, anonymous: true },\n rates: { persist: true, anonymous: true },\n cryptocurrencies: { persist: true, anonymous: true },\n};\n\nconst defaultState = {\n fiatCurrency: 'usd',\n rates: {\n [Cryptocurrency.Btc]: {\n conversionDate: 0,\n conversionRate: '0',\n },\n },\n cryptocurrencies: [Cryptocurrency.Btc],\n};\n\nexport class RatesController extends BaseController<\n typeof name,\n RatesControllerState,\n RatesControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n readonly #fetchMultiExchangeRate;\n\n readonly #includeUsdRate;\n\n #intervalLength: number;\n\n #intervalId: NodeJS.Timeout | undefined;\n\n /**\n * Creates a RatesController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n messenger,\n state,\n includeUsdRate,\n fetchMultiExchangeRate = defaultFetchExchangeRate,\n }: RatesControllerOptions) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.#includeUsdRate = includeUsdRate;\n this.#fetchMultiExchangeRate = fetchMultiExchangeRate;\n this.#intervalLength = interval;\n }\n\n /**\n * Executes a function `callback` within a mutex lock to ensure that only one instance of `callback` runs at a time across all invocations of `#withLock`.\n * This method is useful for synchronizing access to a resource or section of code that should not be executed concurrently.\n *\n * @template R - The return type of the function `callback`.\n * @param callback - A callback to execute once the lock is acquired. This callback can be synchronous or asynchronous.\n * @returns A promise that resolves to the result of the function `callback`. The promise is fulfilled once `callback` has completed execution.\n * @example\n * async function criticalLogic() {\n * // Critical logic code goes here.\n * }\n *\n * // Execute criticalLogic within a lock.\n * const result = await this.#withLock(criticalLogic);\n */\n async #withLock<R>(callback: () => R) {\n const releaseLock = await this.#mutex.acquire();\n try {\n return callback();\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Executes the polling operation to update rates.\n */\n async #executePoll(): Promise<void> {\n await this.#updateRates();\n }\n\n /**\n * Updates the rates by fetching new data.\n */\n async #updateRates(): Promise<void> {\n await this.#withLock(async () => {\n const { fiatCurrency, cryptocurrencies } = this.state;\n const response: Record<\n Cryptocurrency,\n Record<string, string>\n > = await this.#fetchMultiExchangeRate(\n fiatCurrency,\n cryptocurrencies,\n this.#includeUsdRate,\n );\n\n const updatedRates: ConversionRates = {};\n for (const [cryptocurrency, values] of Object.entries(response)) {\n updatedRates[cryptocurrency] = {\n conversionDate: Date.now(),\n conversionRate: values[fiatCurrency],\n ...(this.#includeUsdRate && { usdConversionRate: values.usd }),\n };\n }\n\n this.update(() => {\n return {\n ...this.state,\n rates: updatedRates,\n };\n });\n });\n }\n\n /**\n * Starts the polling process.\n */\n async start(): Promise<void> {\n if (this.#intervalId) {\n return;\n }\n\n this.messagingSystem.publish(`${name}:pollingStarted`);\n\n this.#intervalId = setInterval(() => {\n this.#executePoll().catch(console.error);\n }, this.#intervalLength);\n }\n\n /**\n * Stops the polling process.\n */\n async stop(): Promise<void> {\n if (!this.#intervalId) {\n return;\n }\n\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n this.messagingSystem.publish(`${name}:pollingStopped`);\n }\n\n /**\n * Returns the current list of cryptocurrency.\n * @returns The cryptocurrency list.\n */\n getCryptocurrencyList(): Cryptocurrency[] {\n const { cryptocurrencies } = this.state;\n return cryptocurrencies;\n }\n\n /**\n * Sets the list of supported cryptocurrencies.\n * @param list - The list of supported cryptocurrencies.\n */\n async setCryptocurrencyList(list: Cryptocurrency[]): Promise<void> {\n await this.#withLock(() => {\n this.update(() => {\n return {\n ...this.state,\n fromCurrencies: list,\n };\n });\n });\n }\n\n /**\n * Sets the internal fiat currency and update rates accordingly.\n * @param fiatCurrency - The fiat currency.\n */\n async setFiatCurrency(fiatCurrency: string): Promise<void> {\n if (fiatCurrency === '') {\n throw new Error('The currency can not be an empty string');\n }\n\n await this.#withLock(() => {\n this.update(() => {\n return {\n ...defaultState,\n fiatCurrency,\n };\n });\n });\n await this.#updateRates();\n }\n}\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,sBAAsB;AAC/B,SAAS,aAAa;AAUf,IAAM,OAAO;AAEb,IAAK,iBAAL,kBAAKA,oBAAL;AACL,EAAAA,gBAAA,SAAM;AADI,SAAAA;AAAA,GAAA;AAIZ,IAAM,mBAAmB;AAEzB,IAAM,WAAW;AAAA,EACf,cAAc,EAAE,SAAS,MAAM,WAAW,KAAK;AAAA,EAC/C,OAAO,EAAE,SAAS,MAAM,WAAW,KAAK;AAAA,EACxC,kBAAkB,EAAE,SAAS,MAAM,WAAW,KAAK;AACrD;AAEA,IAAM,eAAe;AAAA,EACnB,cAAc;AAAA,EACd,OAAO;AAAA,IACL,CAAC,eAAkB,GAAG;AAAA,MACpB,gBAAgB;AAAA,MAChB,gBAAgB;AAAA,IAClB;AAAA,EACF;AAAA,EACA,kBAAkB,CAAC,eAAkB;AACvC;AAlCA;AAoCO,IAAM,kBAAN,cAA8B,eAInC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqBA,YAAY;AAAA,IACV,WAAW;AAAA,IACX;AAAA,IACA;AAAA,IACA;AAAA,IACA,wBAAAC,0BAAyB;AAAA,EAC3B,GAA2B;AACzB,UAAM;AAAA,MACJ;AAAA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A,EAMA,MAAM,gBAAgB,cAAqC;AACzD,QAAI,iBAAiB,IAAI;AACvB,YAAM,IAAI,MAAM,yCAAyC;AAAA,IAC3D;AAEA,UAAM,sBAAK,wBAAL,WAAe,MAAM;AACzB,WAAK,OAAO,MAAM;AAChB,eAAO;AAAA,UACL,GAAG;AAAA,UACH;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACH;AACA,UAAM,sBAAK,8BAAL;AAAA,EACR;AACF;AA7KW;AAEA;AAEA;AAET;AAEA;AA6CM;AAAA,cAAY,eAAC,UAAmB;AACpC,QAAM,cAAc,MAAM,mBAAK,QAAO,QAAQ;AAC9C,MAAI;AACF,WAAO,SAAS;AAAA,EAClB,UAAE;AACA,gBAAY;AAAA,EACd;AACF;AAKM;AAAA,iBAAY,iBAAkB;AAClC,QAAM,sBAAK,8BAAL;AACR;AAKM;AAAA,iBAAY,iBAAkB;AAClC,QAAM,sBAAK,wBAAL,WAAe,YAAY;AAC/B,UAAM,EAAE,cAAc,iBAAiB,IAAI,KAAK;AAChD,UAAM,WAGF,MAAM,mBAAK,yBAAL,WACR,cACA,kBACA,mBAAK;AAGP,UAAM,eAAgC,CAAC;AACvC,eAAW,CAAC,gBAAgB,MAAM,KAAK,OAAO,QAAQ,QAAQ,GAAG;AAC/D,mBAAa,cAAc,IAAI;AAAA,QAC7B,gBAAgB,KAAK,IAAI;AAAA,QACzB,gBAAgB,OAAO,YAAY;AAAA,QACnC,GAAI,mBAAK,oBAAmB,EAAE,mBAAmB,OAAO,IAAI;AAAA,MAC9D;AAAA,IACF;AAEA,SAAK,OAAO,MAAM;AAChB,aAAO;AAAA,QACL,GAAG,KAAK;AAAA,QACR,OAAO;AAAA,MACT;AAAA,IACF,CAAC;AAAA,EACH;AACF;","names":["Cryptocurrency","fetchMultiExchangeRate"]}
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunkLS6R3HQLjs = require('./chunk-LS6R3HQL.js');
3
+ var _chunkNEXY7SE2js = require('./chunk-NEXY7SE2.js');
4
4
 
5
5
  // src/Standards/ERC20Standard.ts
6
6
  var _util = require('@ethereumjs/util');
@@ -23,7 +23,7 @@ var ERC20Standard = class {
23
23
  async getBalanceOf(address, selectedAddress) {
24
24
  const contract = new (0, _contracts.Contract)(address, _metamaskethabis.abiERC20, this.provider);
25
25
  const balance = await contract.balanceOf(selectedAddress);
26
- return _chunkLS6R3HQLjs.ethersBigNumberToBN.call(void 0, balance);
26
+ return _chunkNEXY7SE2js.ethersBigNumberToBN.call(void 0, balance);
27
27
  }
28
28
  /**
29
29
  * Query for the decimals for a given ERC20 asset.
@@ -112,4 +112,4 @@ var ERC20Standard = class {
112
112
 
113
113
 
114
114
  exports.ERC20Standard = ERC20Standard;
115
- //# sourceMappingURL=chunk-BO2WZDUM.js.map
115
+ //# sourceMappingURL=chunk-B5YY22QQ.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  fetchExchangeRate
3
- } from "./chunk-PWZE6KJV.mjs";
3
+ } from "./chunk-CNKVITJO.mjs";
4
4
 
5
5
  // src/CurrencyRateController.ts
6
6
  import {
@@ -154,4 +154,4 @@ export {
154
154
  CurrencyRateController,
155
155
  CurrencyRateController_default
156
156
  };
157
- //# sourceMappingURL=chunk-QWACHXRH.mjs.map
157
+ //# sourceMappingURL=chunk-B6W4CQOR.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/CurrencyRateController.ts"],"sourcesContent":["import type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport {\n TESTNET_TICKER_SYMBOLS,\n FALL_BACK_VS_CURRENCY,\n} from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkControllerGetNetworkClientByIdAction,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport { Mutex } from 'async-mutex';\n\nimport { fetchExchangeRate as defaultFetchExchangeRate } from './crypto-compare-service';\n\n/**\n * @type CurrencyRateState\n * @property currencyRates - Object keyed by native currency\n * @property currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch\n * @property currencyRates.conversionRate - Conversion rate from current base asset to the current currency\n * @property currentCurrency - Currently-active ISO 4217 currency code\n * @property usdConversionRate - Conversion rate from usd to the current currency\n */\nexport type CurrencyRateState = {\n currentCurrency: string;\n currencyRates: Record<\n string,\n {\n conversionDate: number | null;\n conversionRate: number | null;\n usdConversionRate: number | null;\n }\n >;\n};\n\nconst name = 'CurrencyRateController';\n\nexport type CurrencyRateStateChange = ControllerStateChangeEvent<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerEvents = CurrencyRateStateChange;\n\nexport type GetCurrencyRateState = ControllerGetStateAction<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerActions = GetCurrencyRateState;\n\ntype AllowedActions = NetworkControllerGetNetworkClientByIdAction;\n\ntype CurrencyRateMessenger = RestrictedControllerMessenger<\n typeof name,\n CurrencyRateControllerActions | AllowedActions,\n CurrencyRateControllerEvents,\n AllowedActions['type'],\n never\n>;\n\nconst metadata = {\n currentCurrency: { persist: true, anonymous: true },\n currencyRates: { persist: true, anonymous: true },\n};\n\nconst defaultState = {\n currentCurrency: 'usd',\n currencyRates: {\n ETH: {\n conversionDate: 0,\n conversionRate: 0,\n usdConversionRate: null,\n },\n },\n};\n\n/**\n * Controller that passively polls on a set interval for an exchange rate from the current network\n * asset to the user's preferred currency.\n */\nexport class CurrencyRateController extends StaticIntervalPollingController<\n typeof name,\n CurrencyRateState,\n CurrencyRateMessenger\n> {\n private readonly mutex = new Mutex();\n\n private readonly fetchExchangeRate;\n\n private readonly includeUsdRate;\n\n /**\n * Creates a CurrencyRateController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.fetchExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n includeUsdRate = false,\n interval = 180000,\n messenger,\n state,\n fetchExchangeRate = defaultFetchExchangeRate,\n }: {\n includeUsdRate?: boolean;\n interval?: number;\n messenger: CurrencyRateMessenger;\n state?: Partial<CurrencyRateState>;\n fetchExchangeRate?: typeof defaultFetchExchangeRate;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.includeUsdRate = includeUsdRate;\n this.setIntervalLength(interval);\n this.fetchExchangeRate = fetchExchangeRate;\n }\n\n /**\n * Sets a currency to track.\n *\n * @param currentCurrency - ISO 4217 currency code.\n */\n async setCurrentCurrency(currentCurrency: string) {\n const releaseLock = await this.mutex.acquire();\n const nativeCurrencies = Object.keys(this.state.currencyRates);\n try {\n this.update(() => {\n return {\n ...defaultState,\n currentCurrency,\n };\n });\n } finally {\n releaseLock();\n }\n nativeCurrencies.forEach(this.updateExchangeRate.bind(this));\n }\n\n /**\n * Updates the exchange rate for the current currency and native currency pair.\n *\n * @param nativeCurrency - The ticker symbol for the chain.\n */\n async updateExchangeRate(nativeCurrency: string): Promise<void> {\n const releaseLock = await this.mutex.acquire();\n const { currentCurrency, currencyRates } = this.state;\n\n let conversionDate: number | null = null;\n let conversionRate: number | null = null;\n let usdConversionRate: number | null = null;\n\n // For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.\n const nativeCurrencyForExchangeRate = Object.values(\n TESTNET_TICKER_SYMBOLS,\n ).includes(nativeCurrency)\n ? FALL_BACK_VS_CURRENCY // ETH\n : nativeCurrency;\n\n try {\n if (\n currentCurrency &&\n nativeCurrency &&\n // if either currency is an empty string we can skip the comparison\n // because it will result in an error from the api and ultimately\n // a null conversionRate either way.\n currentCurrency !== '' &&\n nativeCurrency !== ''\n ) {\n const fetchExchangeRateResponse = await this.fetchExchangeRate(\n currentCurrency,\n nativeCurrencyForExchangeRate,\n this.includeUsdRate,\n );\n conversionRate = fetchExchangeRateResponse.conversionRate;\n usdConversionRate = fetchExchangeRateResponse.usdConversionRate;\n conversionDate = Date.now() / 1000;\n }\n } catch (error) {\n if (\n !(\n error instanceof Error &&\n error.message.includes('market does not exist for this coin pair')\n )\n ) {\n throw error;\n }\n } finally {\n try {\n this.update(() => {\n return {\n currencyRates: {\n ...currencyRates,\n [nativeCurrency]: {\n conversionDate,\n conversionRate,\n usdConversionRate,\n },\n },\n currentCurrency,\n };\n });\n } finally {\n releaseLock();\n }\n }\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.stopAllPolling();\n }\n\n /**\n * Updates exchange rate for the current currency.\n *\n * @param networkClientId - The network client ID used to get a ticker value.\n * @returns The controller state.\n */\n async _executePoll(networkClientId: NetworkClientId): Promise<void> {\n const networkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n await this.updateExchangeRate(networkClient.configuration.ticker);\n }\n}\n\nexport default CurrencyRateController;\n"],"mappings":";;;;;AAKA;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAKP,SAAS,uCAAuC;AAChD,SAAS,aAAa;AAwBtB,IAAM,OAAO;AA0Bb,IAAM,WAAW;AAAA,EACf,iBAAiB,EAAE,SAAS,MAAM,WAAW,KAAK;AAAA,EAClD,eAAe,EAAE,SAAS,MAAM,WAAW,KAAK;AAClD;AAEA,IAAM,eAAe;AAAA,EACnB,iBAAiB;AAAA,EACjB,eAAe;AAAA,IACb,KAAK;AAAA,MACH,gBAAgB;AAAA,MAChB,gBAAgB;AAAA,MAChB,mBAAmB;AAAA,IACrB;AAAA,EACF;AACF;AAMO,IAAM,yBAAN,cAAqC,gCAI1C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,YAAY;AAAA,IACV,iBAAiB;AAAA,IACjB,WAAW;AAAA,IACX;AAAA,IACA;AAAA,I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BAAiB,SACjB,MAAM,QAAQ,SAAS,0CAA0C,IAEnE;AACA,cAAM;AAAA,MACR;AAAA,IACF,UAAE;AACA,UAAI;AACF,aAAK,OAAO,MAAM;AAChB,iBAAO;AAAA,YACL,eAAe;AAAA,cACb,GAAG;AAAA,cACH,CAAC,cAAc,GAAG;AAAA,gBAChB;AAAA,gBACA;AAAA,gBACA;AAAA,cACF;AAAA,YACF;AAAA,YACA;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH,UAAE;AACA,oBAAY;AAAA,MACd;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOS,UAAU;AACjB,UAAM,QAAQ;AACd,SAAK,eAAe;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,aAAa,iBAAiD;AAClE,UAAM,gBAAgB,KAAK,gBAAgB;AAAA,MACzC;AAAA,MACA;AAAA,IACF;AACA,UAAM,KAAK,mBAAmB,cAAc,cAAc,MAAM;AAAA,EAClE;AACF;AAEA,IAAO,iCAAQ;","names":["fetchExchangeRate"]}
@@ -1,7 +1,7 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
3
 
4
- var _chunkLS6R3HQLjs = require('./chunk-LS6R3HQL.js');
4
+ var _chunkNEXY7SE2js = require('./chunk-NEXY7SE2.js');
5
5
 
6
6
  // src/Standards/NftStandards/ERC1155/ERC1155Standard.ts
7
7
  var _contracts = require('@ethersproject/contracts');
@@ -73,7 +73,7 @@ var ERC1155Standard = class {
73
73
  async getBalanceOf(contractAddress, address, tokenId) {
74
74
  const contract = new (0, _contracts.Contract)(contractAddress, _metamaskethabis.abiERC1155, this.provider);
75
75
  const balance = await contract.balanceOf(address, tokenId);
76
- return _chunkLS6R3HQLjs.ethersBigNumberToBN.call(void 0, balance);
76
+ return _chunkNEXY7SE2js.ethersBigNumberToBN.call(void 0, balance);
77
77
  }
78
78
  /**
79
79
  * Transfer single ERC1155 token.
@@ -184,7 +184,7 @@ var ERC1155Standard = class {
184
184
  _controllerutils.safelyExecute.call(void 0, () => this.getAssetName(address)),
185
185
  tokenId ? _controllerutils.safelyExecute.call(void 0,
186
186
  () => this.getTokenURI(address, tokenId).then(
187
- (uri) => uri.startsWith("ipfs://") ? _chunkLS6R3HQLjs.getFormattedIpfsUrl.call(void 0, ipfsGateway, uri, true) : uri
187
+ (uri) => uri.startsWith("ipfs://") ? _chunkNEXY7SE2js.getFormattedIpfsUrl.call(void 0, ipfsGateway, uri, true) : uri
188
188
  )
189
189
  ) : void 0
190
190
  ]);
@@ -194,7 +194,7 @@ var ERC1155Standard = class {
194
194
  const object = await response.json();
195
195
  image = object?.image;
196
196
  if (image?.startsWith("ipfs://")) {
197
- image = _chunkLS6R3HQLjs.getFormattedIpfsUrl.call(void 0, ipfsGateway, image, true);
197
+ image = _chunkNEXY7SE2js.getFormattedIpfsUrl.call(void 0, ipfsGateway, image, true);
198
198
  }
199
199
  } catch {
200
200
  }
@@ -212,4 +212,4 @@ var ERC1155Standard = class {
212
212
 
213
213
 
214
214
  exports.ERC1155Standard = ERC1155Standard;
215
- //# sourceMappingURL=chunk-3ZHN4GFT.js.map
215
+ //# sourceMappingURL=chunk-BOTVAG4A.js.map
@@ -0,0 +1,66 @@
1
+ // src/crypto-compare-service/crypto-compare.ts
2
+ import { handleFetch } from "@metamask/controller-utils";
3
+ var nativeSymbolOverrides = /* @__PURE__ */ new Map([["MNT", "MANTLE"]]);
4
+ var CRYPTO_COMPARE_DOMAIN = "https://min-api.cryptocompare.com";
5
+ function getPricingURL(currentCurrency, nativeCurrency, includeUSDRate) {
6
+ nativeCurrency = nativeCurrency.toUpperCase();
7
+ const fsym = nativeSymbolOverrides.get(nativeCurrency) ?? nativeCurrency;
8
+ return `${CRYPTO_COMPARE_DOMAIN}/data/price?fsym=${fsym}&tsyms=${currentCurrency.toUpperCase()}${includeUSDRate && currentCurrency.toUpperCase() !== "USD" ? ",USD" : ""}`;
9
+ }
10
+ function getMultiPricingURL(fsyms, tsyms, includeUSDRate = false) {
11
+ const updatedTsyms = includeUSDRate && !tsyms.includes("USD") ? `${tsyms},USD` : tsyms;
12
+ const params = new URLSearchParams();
13
+ params.append("fsyms", fsyms);
14
+ params.append("tsyms", updatedTsyms);
15
+ const url = new URL(`${CRYPTO_COMPARE_DOMAIN}/data/pricemulti`);
16
+ url.search = params.toString();
17
+ return url.toString();
18
+ }
19
+ function handleErrorResponse(json) {
20
+ if (json.Response === "Error") {
21
+ throw new Error(json.Message);
22
+ }
23
+ }
24
+ async function fetchExchangeRate(currency, nativeCurrency, includeUSDRate) {
25
+ const json = await handleFetch(
26
+ getPricingURL(currency, nativeCurrency, includeUSDRate)
27
+ );
28
+ handleErrorResponse(json);
29
+ const conversionRate = Number(json[currency.toUpperCase()]);
30
+ const usdConversionRate = Number(json.USD);
31
+ if (!Number.isFinite(conversionRate)) {
32
+ throw new Error(
33
+ `Invalid response for ${currency.toUpperCase()}: ${json[currency.toUpperCase()]}`
34
+ );
35
+ }
36
+ if (includeUSDRate && !Number.isFinite(usdConversionRate)) {
37
+ throw new Error(`Invalid response for usdConversionRate: ${json.USD}`);
38
+ }
39
+ return {
40
+ conversionRate,
41
+ usdConversionRate
42
+ };
43
+ }
44
+ async function fetchMultiExchangeRate(fiatCurrency, cryptocurrencies, includeUSDRate) {
45
+ const url = getMultiPricingURL(
46
+ Object.values(cryptocurrencies).join(","),
47
+ fiatCurrency,
48
+ includeUSDRate
49
+ );
50
+ const response = await handleFetch(url);
51
+ handleErrorResponse(response);
52
+ const rates = {};
53
+ for (const [cryptocurrency, values] of Object.entries(response)) {
54
+ rates[cryptocurrency.toLowerCase()] = {
55
+ [fiatCurrency.toLowerCase()]: values[fiatCurrency.toUpperCase()],
56
+ ...includeUSDRate && { usd: values.USD }
57
+ };
58
+ }
59
+ return rates;
60
+ }
61
+
62
+ export {
63
+ fetchExchangeRate,
64
+ fetchMultiExchangeRate
65
+ };
66
+ //# sourceMappingURL=chunk-CNKVITJO.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/crypto-compare-service/crypto-compare.ts"],"sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\n\n/**\n * A map from native currency symbol to CryptoCompare identifier.\n * This is only needed when the values don't match.\n */\nconst nativeSymbolOverrides = new Map([['MNT', 'MANTLE']]);\n\nconst CRYPTO_COMPARE_DOMAIN = 'https://min-api.cryptocompare.com';\n\n/**\n * Get the CryptoCompare API URL for getting the conversion rate from the given native currency to\n * the given currency. Optionally, the conversion rate from the native currency to USD can also be\n * included in the response.\n *\n * @param currentCurrency - The currency to get a conversion rate for.\n * @param nativeCurrency - The native currency to convert from.\n * @param includeUSDRate - Whether or not the native currency to USD conversion rate should be\n * included in the response as well.\n * @returns The API URL for getting the conversion rate.\n */\nfunction getPricingURL(\n currentCurrency: string,\n nativeCurrency: string,\n includeUSDRate?: boolean,\n) {\n nativeCurrency = nativeCurrency.toUpperCase();\n const fsym = nativeSymbolOverrides.get(nativeCurrency) ?? nativeCurrency;\n return (\n `${CRYPTO_COMPARE_DOMAIN}/data/price?fsym=` +\n `${fsym}&tsyms=${currentCurrency.toUpperCase()}` +\n `${includeUSDRate && currentCurrency.toUpperCase() !== 'USD' ? ',USD' : ''}`\n );\n}\n\n/**\n * Get the CryptoCompare API URL for getting the conversion rate from a given array of native currencies\n * to the given currency. Optionally, the conversion rate from the native currency to USD can also be\n * included in the response.\n *\n * @param fsyms - The native currencies to get conversion rates for.\n * @param tsyms - The currency to convert to.\n * @param includeUSDRate - Whether or not the native currency to USD conversion rate should be included.\n * @returns The API URL for getting the conversion rates.\n */\nfunction getMultiPricingURL(\n fsyms: string,\n tsyms: string,\n includeUSDRate = false,\n) {\n const updatedTsyms =\n includeUSDRate && !tsyms.includes('USD') ? `${tsyms},USD` : tsyms;\n\n const params = new URLSearchParams();\n params.append('fsyms', fsyms);\n params.append('tsyms', updatedTsyms);\n\n const url = new URL(`${CRYPTO_COMPARE_DOMAIN}/data/pricemulti`);\n url.search = params.toString();\n\n return url.toString();\n}\n\n/**\n * Handles an error response from the CryptoCompare API.\n * Expected error response format\n * { Response: \"Error\", Message: \"...\", HasWarning: false }\n *\n * @param json - The JSON response from the CryptoCompare API.\n * @param json.Response - The response status.\n * @param json.Message - The error message.\n */\nfunction handleErrorResponse(json: { Response?: string; Message?: string }) {\n if (json.Response === 'Error') {\n throw new Error(json.Message);\n }\n}\n\n/**\n * Fetches the exchange rate for a given currency.\n *\n * @param currency - ISO 4217 currency code.\n * @param nativeCurrency - Symbol for base asset.\n * @param includeUSDRate - Whether to add the USD rate to the fetch.\n * @returns Promise resolving to exchange rate for given currency.\n */\nexport async function fetchExchangeRate(\n currency: string,\n nativeCurrency: string,\n includeUSDRate?: boolean,\n): Promise<{\n conversionRate: number;\n usdConversionRate: number;\n}> {\n const json = await handleFetch(\n getPricingURL(currency, nativeCurrency, includeUSDRate),\n );\n\n handleErrorResponse(json);\n const conversionRate = Number(json[currency.toUpperCase()]);\n\n const usdConversionRate = Number(json.USD);\n if (!Number.isFinite(conversionRate)) {\n throw new Error(\n `Invalid response for ${currency.toUpperCase()}: ${\n json[currency.toUpperCase()]\n }`,\n );\n }\n\n if (includeUSDRate && !Number.isFinite(usdConversionRate)) {\n throw new Error(`Invalid response for usdConversionRate: ${json.USD}`);\n }\n\n return {\n conversionRate,\n usdConversionRate,\n };\n}\n\n/**\n * Fetches the exchange rates for multiple currencies.\n *\n * @param fiatCurrency - The currency of the rates (ISO 4217).\n * @param cryptocurrencies - The cryptocurrencies to get conversion rates for. Min length: 1. Max length: 300.\n * @param includeUSDRate - Whether to add the USD rate to the fetch.\n * @returns Promise resolving to exchange rates for given currencies.\n */\nexport async function fetchMultiExchangeRate(\n fiatCurrency: string,\n cryptocurrencies: string[],\n includeUSDRate: boolean,\n): Promise<Record<string, Record<string, string>>> {\n const url = getMultiPricingURL(\n Object.values(cryptocurrencies).join(','),\n fiatCurrency,\n includeUSDRate,\n );\n const response = await handleFetch(url);\n handleErrorResponse(response);\n\n const rates: Record<string, Record<string, string>> = {};\n for (const [cryptocurrency, values] of Object.entries(response) as [\n string,\n Record<string, string>,\n ][]) {\n rates[cryptocurrency.toLowerCase()] = {\n [fiatCurrency.toLowerCase()]: values[fiatCurrency.toUpperCase()],\n ...(includeUSDRate && { usd: values.USD }),\n };\n }\n\n return rates;\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;AAM5B,IAAM,wBAAwB,oBAAI,IAAI,CAAC,CAAC,OAAO,QAAQ,CAAC,CAAC;AAEzD,IAAM,wBAAwB;AAa9B,SAAS,cACP,iBACA,gBACA,gBACA;AACA,mBAAiB,eAAe,YAAY;AAC5C,QAAM,OAAO,sBAAsB,IAAI,cAAc,KAAK;AAC1D,SACE,GAAG,qBAAqB,oBACrB,IAAI,UAAU,gBAAgB,YAAY,CAAC,GAC3C,kBAAkB,gBAAgB,YAAY,MAAM,QAAQ,SAAS,EAAE;AAE9E;AAYA,SAAS,mBACP,OACA,OACA,iBAAiB,OACjB;AACA,QAAM,eACJ,kBAAkB,CAAC,MAAM,SAAS,KAAK,IAAI,GAAG,KAAK,SAAS;AAE9D,QAAM,SAAS,IAAI,gBAAgB;AACnC,SAAO,OAAO,SAAS,KAAK;AAC5B,SAAO,OAAO,SAAS,YAAY;AAEnC,QAAM,MAAM,IAAI,IAAI,GAAG,qBAAqB,kBAAkB;AAC9D,MAAI,SAAS,OAAO,SAAS;AAE7B,SAAO,IAAI,SAAS;AACtB;AAWA,SAAS,oBAAoB,MAA+C;AAC1E,MAAI,KAAK,aAAa,SAAS;AAC7B,UAAM,IAAI,MAAM,KAAK,OAAO;AAAA,EAC9B;AACF;AAUA,eAAsB,kBACpB,UACA,gBACA,gBAIC;AACD,QAAM,OAAO,MAAM;AAAA,IACjB,cAAc,UAAU,gBAAgB,cAAc;AAAA,EACxD;AAEA,sBAAoB,IAAI;AACxB,QAAM,iBAAiB,OAAO,KAAK,SAAS,YAAY,CAAC,CAAC;AAE1D,QAAM,oBAAoB,OAAO,KAAK,GAAG;AACzC,MAAI,CAAC,OAAO,SAAS,cAAc,GAAG;AACpC,UAAM,IAAI;AAAA,MACR,wBAAwB,SAAS,YAAY,CAAC,KAC5C,KAAK,SAAS,YAAY,CAAC,CAC7B;AAAA,IACF;AAAA,EACF;AAEA,MAAI,kBAAkB,CAAC,OAAO,SAAS,iBAAiB,GAAG;AACzD,UAAM,IAAI,MAAM,2CAA2C,KAAK,GAAG,EAAE;AAAA,EACvE;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,EACF;AACF;AAUA,eAAsB,uBACpB,cACA,kBACA,gBACiD;AACjD,QAAM,MAAM;AAAA,IACV,OAAO,OAAO,gBAAgB,EAAE,KAAK,GAAG;AAAA,IACxC;AAAA,IACA;AAAA,EACF;AACA,QAAM,WAAW,MAAM,YAAY,GAAG;AACtC,sBAAoB,QAAQ;AAE5B,QAAM,QAAgD,CAAC;AACvD,aAAW,CAAC,gBAAgB,MAAM,KAAK,OAAO,QAAQ,QAAQ,GAGzD;AACH,UAAM,eAAe,YAAY,CAAC,IAAI;AAAA,MACpC,CAAC,aAAa,YAAY,CAAC,GAAG,OAAO,aAAa,YAAY,CAAC;AAAA,MAC/D,GAAI,kBAAkB,EAAE,KAAK,OAAO,IAAI;AAAA,IAC1C;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  ethersBigNumberToBN
3
- } from "./chunk-X5PLVMOQ.mjs";
3
+ } from "./chunk-Q5JRBGWO.mjs";
4
4
 
5
5
  // src/Standards/ERC20Standard.ts
6
6
  import { toUtf8 } from "@ethereumjs/util";
@@ -112,4 +112,4 @@ var ERC20Standard = class {
112
112
  export {
113
113
  ERC20Standard
114
114
  };
115
- //# sourceMappingURL=chunk-LLYYJY7H.mjs.map
115
+ //# sourceMappingURL=chunk-D3K5MPMW.mjs.map
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunkDYH5P3VYjs = require('./chunk-DYH5P3VY.js');
3
+ var _chunkWB6KJX4Njs = require('./chunk-WB6KJX4N.js');
4
4
 
5
5
  // src/CurrencyRateController.ts
6
6
 
@@ -40,7 +40,7 @@ var CurrencyRateController = class extends _pollingcontroller.StaticIntervalPoll
40
40
  interval = 18e4,
41
41
  messenger,
42
42
  state,
43
- fetchExchangeRate: fetchExchangeRate2 = _chunkDYH5P3VYjs.fetchExchangeRate
43
+ fetchExchangeRate: fetchExchangeRate2 = _chunkWB6KJX4Njs.fetchExchangeRate
44
44
  }) {
45
45
  super({
46
46
  name,
@@ -154,4 +154,4 @@ var CurrencyRateController_default = CurrencyRateController;
154
154
 
155
155
 
156
156
  exports.CurrencyRateController = CurrencyRateController; exports.CurrencyRateController_default = CurrencyRateController_default;
157
- //# sourceMappingURL=chunk-LRKDZWS6.js.map
157
+ //# sourceMappingURL=chunk-ELSMS5S7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/CurrencyRateController.ts"],"names":["fetchExchangeRate"],"mappings":";;;;;AAKA;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAKP,SAAS,uCAAuC;AAChD,SAAS,aAAa;AAwBtB,IAAM,OAAO;AA0Bb,IAAM,WAAW;AAAA,EACf,iBAAiB,EAAE,SAAS,MAAM,WAAW,KAAK;AAAA,EAClD,eAAe,EAAE,SAAS,MAAM,WAAW,KAAK;AAClD;AAEA,IAAM,eAAe;AAAA,EACnB,iBAAiB;AAAA,EACjB,eAAe;AAAA,IACb,KAAK;AAAA,MACH,gBAAgB;AAAA,MAChB,gBAAgB;AAAA,MAChB,mBAAmB;AAAA,IACrB;AAAA,EACF;AACF;AAMO,IAAM,yBAAN,cAAqC,gCAI1C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiBA,YAAY;AAAA,IACV,iBAAiB;AAAA,IACjB,WAAW;AAAA,IACX;AAAA,IACA;AAAA,IAC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AAiB,SACjB,MAAM,QAAQ,SAAS,0CAA0C,IAEnE;AACA,cAAM;AAAA,MACR;AAAA,IACF,UAAE;AACA,UAAI;AACF,aAAK,OAAO,MAAM;AAChB,iBAAO;AAAA,YACL,eAAe;AAAA,cACb,GAAG;AAAA,cACH,CAAC,cAAc,GAAG;AAAA,gBAChB;AAAA,gBACA;AAAA,gBACA;AAAA,cACF;AAAA,YACF;AAAA,YACA;AAAA,UACF;AAAA,QACF,CAAC;AAAA,MACH,UAAE;AACA,oBAAY;AAAA,MACd;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOS,UAAU;AACjB,UAAM,QAAQ;AACd,SAAK,eAAe;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,aAAa,iBAAiD;AAClE,UAAM,gBAAgB,KAAK,gBAAgB;AAAA,MACzC;AAAA,MACA;AAAA,IACF;AACA,UAAM,KAAK,mBAAmB,cAAc,cAAc,MAAM;AAAA,EAClE;AACF;AAEA,IAAO,iCAAQ","sourcesContent":["import type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport {\n TESTNET_TICKER_SYMBOLS,\n FALL_BACK_VS_CURRENCY,\n} from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkControllerGetNetworkClientByIdAction,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport { Mutex } from 'async-mutex';\n\nimport { fetchExchangeRate as defaultFetchExchangeRate } from './crypto-compare-service';\n\n/**\n * @type CurrencyRateState\n * @property currencyRates - Object keyed by native currency\n * @property currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch\n * @property currencyRates.conversionRate - Conversion rate from current base asset to the current currency\n * @property currentCurrency - Currently-active ISO 4217 currency code\n * @property usdConversionRate - Conversion rate from usd to the current currency\n */\nexport type CurrencyRateState = {\n currentCurrency: string;\n currencyRates: Record<\n string,\n {\n conversionDate: number | null;\n conversionRate: number | null;\n usdConversionRate: number | null;\n }\n >;\n};\n\nconst name = 'CurrencyRateController';\n\nexport type CurrencyRateStateChange = ControllerStateChangeEvent<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerEvents = CurrencyRateStateChange;\n\nexport type GetCurrencyRateState = ControllerGetStateAction<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerActions = GetCurrencyRateState;\n\ntype AllowedActions = NetworkControllerGetNetworkClientByIdAction;\n\ntype CurrencyRateMessenger = RestrictedControllerMessenger<\n typeof name,\n CurrencyRateControllerActions | AllowedActions,\n CurrencyRateControllerEvents,\n AllowedActions['type'],\n never\n>;\n\nconst metadata = {\n currentCurrency: { persist: true, anonymous: true },\n currencyRates: { persist: true, anonymous: true },\n};\n\nconst defaultState = {\n currentCurrency: 'usd',\n currencyRates: {\n ETH: {\n conversionDate: 0,\n conversionRate: 0,\n usdConversionRate: null,\n },\n },\n};\n\n/**\n * Controller that passively polls on a set interval for an exchange rate from the current network\n * asset to the user's preferred currency.\n */\nexport class CurrencyRateController extends StaticIntervalPollingController<\n typeof name,\n CurrencyRateState,\n CurrencyRateMessenger\n> {\n private readonly mutex = new Mutex();\n\n private readonly fetchExchangeRate;\n\n private readonly includeUsdRate;\n\n /**\n * Creates a CurrencyRateController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.fetchExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n includeUsdRate = false,\n interval = 180000,\n messenger,\n state,\n fetchExchangeRate = defaultFetchExchangeRate,\n }: {\n includeUsdRate?: boolean;\n interval?: number;\n messenger: CurrencyRateMessenger;\n state?: Partial<CurrencyRateState>;\n fetchExchangeRate?: typeof defaultFetchExchangeRate;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.includeUsdRate = includeUsdRate;\n this.setIntervalLength(interval);\n this.fetchExchangeRate = fetchExchangeRate;\n }\n\n /**\n * Sets a currency to track.\n *\n * @param currentCurrency - ISO 4217 currency code.\n */\n async setCurrentCurrency(currentCurrency: string) {\n const releaseLock = await this.mutex.acquire();\n const nativeCurrencies = Object.keys(this.state.currencyRates);\n try {\n this.update(() => {\n return {\n ...defaultState,\n currentCurrency,\n };\n });\n } finally {\n releaseLock();\n }\n nativeCurrencies.forEach(this.updateExchangeRate.bind(this));\n }\n\n /**\n * Updates the exchange rate for the current currency and native currency pair.\n *\n * @param nativeCurrency - The ticker symbol for the chain.\n */\n async updateExchangeRate(nativeCurrency: string): Promise<void> {\n const releaseLock = await this.mutex.acquire();\n const { currentCurrency, currencyRates } = this.state;\n\n let conversionDate: number | null = null;\n let conversionRate: number | null = null;\n let usdConversionRate: number | null = null;\n\n // For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.\n const nativeCurrencyForExchangeRate = Object.values(\n TESTNET_TICKER_SYMBOLS,\n ).includes(nativeCurrency)\n ? FALL_BACK_VS_CURRENCY // ETH\n : nativeCurrency;\n\n try {\n if (\n currentCurrency &&\n nativeCurrency &&\n // if either currency is an empty string we can skip the comparison\n // because it will result in an error from the api and ultimately\n // a null conversionRate either way.\n currentCurrency !== '' &&\n nativeCurrency !== ''\n ) {\n const fetchExchangeRateResponse = await this.fetchExchangeRate(\n currentCurrency,\n nativeCurrencyForExchangeRate,\n this.includeUsdRate,\n );\n conversionRate = fetchExchangeRateResponse.conversionRate;\n usdConversionRate = fetchExchangeRateResponse.usdConversionRate;\n conversionDate = Date.now() / 1000;\n }\n } catch (error) {\n if (\n !(\n error instanceof Error &&\n error.message.includes('market does not exist for this coin pair')\n )\n ) {\n throw error;\n }\n } finally {\n try {\n this.update(() => {\n return {\n currencyRates: {\n ...currencyRates,\n [nativeCurrency]: {\n conversionDate,\n conversionRate,\n usdConversionRate,\n },\n },\n currentCurrency,\n };\n });\n } finally {\n releaseLock();\n }\n }\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.stopAllPolling();\n }\n\n /**\n * Updates exchange rate for the current currency.\n *\n * @param networkClientId - The network client ID used to get a ticker value.\n * @returns The controller state.\n */\n async _executePoll(networkClientId: NetworkClientId): Promise<void> {\n const networkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n await this.updateExchangeRate(networkClient.configuration.ticker);\n }\n}\n\nexport default CurrencyRateController;\n"]}
@@ -79,10 +79,12 @@ var NftDetectionController = class extends _pollingcontroller.StaticIntervalPoll
79
79
  }
80
80
  }
81
81
  });
82
- onNetworkStateChange(({ providerConfig }) => {
83
- this.configure({
84
- chainId: providerConfig.chainId
85
- });
82
+ onNetworkStateChange(({ selectedNetworkClientId }) => {
83
+ const selectedNetworkClient = getNetworkClientById(
84
+ selectedNetworkClientId
85
+ );
86
+ const { chainId } = selectedNetworkClient.configuration;
87
+ this.configure({ chainId });
86
88
  });
87
89
  this.getOpenSeaApiKey = getOpenSeaApiKey;
88
90
  this.addNft = addNft;
@@ -232,4 +234,4 @@ var NftDetectionController_default = NftDetectionController;
232
234
 
233
235
 
234
236
  exports.BlockaidResultType = BlockaidResultType; exports.NftDetectionController = NftDetectionController; exports.NftDetectionController_default = NftDetectionController_default;
235
- //# sourceMappingURL=chunk-X2MMIBYW.js.map
237
+ //# sourceMappingURL=chunk-FMZML3V5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/NftDetectionController.ts"],"names":["BlockaidResultType"],"mappings":";AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAOP,SAAS,yCAAyC;AAWlD,IAAM,mBAAmB;AA2IlB,IAAK,qBAAL,kBAAKA,wBAAL;AACL,EAAAA,oBAAA,YAAS;AAC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AE,YAAY;AAAA,UAC7B,aAAa,EAAE,OAAO,UAAU;AAAA,UAChC,uBAAuB,EAAE,gBAAgB,oBAAoB;AAAA,UAC7D,sBAAsB,EAAE,eAAe,mBAAmB;AAAA,UAC1D,QAAQ,EAAE,UAAU,KAAK,YAAY,EAAE;AAAA,UACvC,YAAY,EAAE,SAAS;AAAA,UACvB,cAAc,EAAE,WAAW;AAAA,UAC3B,UAAU,EAAE,OAAO;AAAA,UACnB,cAAc,EAAE,WAAW;AAAA,UAC3B,eAAe,EAAE,YAAY;AAAA,UAC7B,cAAc,EAAE,WAAW;AAAA,QAC7B;AAEA,cAAM,KAAK,OAAO,UAAU,UAAU;AAAA,UACpC;AAAA,UACA;AAAA,UACA;AAAA,UACA;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF,CAAC;AACD,UAAM,QAAQ,IAAI,cAAc;AAAA,EAClC;AACF;AAEA,IAAO,iCAAQ","sourcesContent":["import type { BaseConfig, BaseState } from '@metamask/base-controller';\nimport {\n fetchWithErrorHandling,\n toChecksumHexAddress,\n ChainId,\n NFT_API_BASE_URL,\n} from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkController,\n NetworkState,\n NetworkClient,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingControllerV1 } from '@metamask/polling-controller';\nimport type { PreferencesState } from '@metamask/preferences-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport { Source } from './constants';\nimport {\n type NftController,\n type NftState,\n type NftMetadata,\n} from './NftController';\n\nconst DEFAULT_INTERVAL = 180000;\n\n/**\n * @type ApiNft\n *\n * NFT object coming from OpenSea api\n * @property token_id - The NFT identifier\n * @property num_sales - Number of sales\n * @property background_color - The background color to be displayed with the item\n * @property image_url - URI of an image associated with this NFT\n * @property image_preview_url - URI of a smaller image associated with this NFT\n * @property image_thumbnail_url - URI of a thumbnail image associated with this NFT\n * @property image_original_url - URI of the original image associated with this NFT\n * @property animation_url - URI of a animation associated with this NFT\n * @property animation_original_url - URI of the original animation associated with this NFT\n * @property name - The NFT name\n * @property description - The NFT description\n * @property external_link - External link containing additional information\n * @property assetContract - The NFT contract information object\n * @property creator - The NFT owner information object\n * @property lastSale - When this item was last sold\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface ApiNft {\n token_id: string;\n num_sales: number | null;\n background_color: string | null;\n image_url: string | null;\n image_preview_url: string | null;\n image_thumbnail_url: string | null;\n image_original_url: string | null;\n animation_url: string | null;\n animation_original_url: string | null;\n name: string | null;\n description: string | null;\n external_link: string | null;\n asset_contract: ApiNftContract;\n creator: ApiNftCreator;\n last_sale: ApiNftLastSale | null;\n}\n\n/**\n * @type ApiNftContract\n *\n * NFT contract object coming from OpenSea api\n * @property address - Address of the NFT contract\n * @property asset_contract_type - The NFT type, it could be `semi-fungible` or `non-fungible`\n * @property created_date - Creation date\n * @property collection - Object containing the contract name and URI of an image associated\n * @property schema_name - The schema followed by the contract, it could be `ERC721` or `ERC1155`\n * @property symbol - The NFT contract symbol\n * @property total_supply - Total supply of NFTs\n * @property description - The NFT contract description\n * @property external_link - External link containing additional information\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface ApiNftContract {\n address: string;\n asset_contract_type: string | null;\n created_date: string | null;\n schema_name: string | null;\n symbol: string | null;\n total_supply: string | null;\n description: string | null;\n external_link: string | null;\n collection: {\n name: string | null;\n image_url?: string | null;\n tokenCount?: string | null;\n };\n}\n\n/**\n * @type ApiNftLastSale\n *\n * NFT sale object coming from OpenSea api\n * @property event_timestamp - Object containing a `username`\n * @property total_price - URI of NFT image associated with this owner\n * @property transaction - Object containing transaction_hash and block_hash\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface ApiNftLastSale {\n event_timestamp: string;\n total_price: string;\n transaction: { transaction_hash: string; block_hash: string };\n}\n\n/**\n * @type ApiNftCreator\n *\n * NFT creator object coming from OpenSea api\n * @property user - Object containing a `username`\n * @property profile_img_url - URI of NFT image associated with this owner\n * @property address - The owner address\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface ApiNftCreator {\n user: { username: string };\n profile_img_url: string;\n address: string;\n}\n\n/**\n * @type NftDetectionConfig\n *\n * NftDetection configuration\n * @property interval - Polling interval used to fetch new token rates\n * @property chainId - Current chain ID\n * @property selectedAddress - Vault selected address\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface NftDetectionConfig extends BaseConfig {\n interval: number;\n chainId: Hex;\n selectedAddress: string;\n}\n\nexport type ReservoirResponse = {\n tokens: TokensResponse[];\n continuation?: string;\n};\n\nexport type TokensResponse = {\n token: TokenResponse;\n ownership: Ownership;\n market?: Market;\n blockaidResult?: Blockaid;\n};\n\nexport enum BlockaidResultType {\n Benign = 'Benign',\n Spam = 'Spam',\n Warning = 'Warning',\n Malicious = 'Malicious',\n}\n\nexport type Blockaid = {\n contract: string;\n chainId: number;\n result_type: BlockaidResultType;\n malicious_score: string;\n attack_types: object;\n};\n\nexport type Market = {\n floorAsk?: FloorAsk;\n topBid?: TopBid;\n};\n\nexport type TokenResponse = {\n chainId: number;\n contract: string;\n tokenId: string;\n kind?: string;\n name?: string;\n image?: string;\n imageSmall?: string;\n imageLarge?: string;\n metadata?: Metadata;\n description?: string;\n supply?: number;\n remainingSupply?: number;\n rarityScore?: number;\n rarity?: number;\n rarityRank?: number;\n media?: string;\n isFlagged?: boolean;\n isSpam?: boolean;\n isNsfw?: boolean;\n metadataDisabled?: boolean;\n lastFlagUpdate?: string;\n lastFlagChange?: string;\n collection?: Collection;\n lastSale?: LastSale;\n topBid?: TopBid;\n lastAppraisalValue?: number;\n attributes?: Attributes[];\n};\n\nexport type TopBid = {\n id?: string;\n price?: Price;\n source?: {\n id?: string;\n domain?: string;\n name?: string;\n icon?: string;\n url?: string;\n };\n};\n\nexport type LastSale = {\n saleId?: string;\n token?: {\n contract?: string;\n tokenId?: string;\n name?: string;\n image?: string;\n collection?: {\n id?: string;\n name?: string;\n };\n };\n orderSource?: string;\n orderSide?: 'ask' | 'bid';\n orderKind?: string;\n orderId?: string;\n from?: string;\n to?: string;\n amount?: string;\n fillSource?: string;\n block?: number;\n txHash?: string;\n logIndex?: number;\n batchIndex?: number;\n timestamp?: number;\n price?: Price;\n washTradingScore?: number;\n royaltyFeeBps?: number;\n marketplaceFeeBps?: number;\n paidFullRoyalty?: boolean;\n feeBreakdown?: FeeBreakdown[];\n isDeleted?: boolean;\n createdAt?: string;\n updatedAt?: string;\n};\n\nexport type FeeBreakdown = {\n kind?: string;\n bps?: number;\n recipient?: string;\n source?: string;\n rawAmount?: string;\n};\n\nexport type Attributes = {\n key?: string;\n kind?: string;\n value: string;\n tokenCount?: number;\n onSaleCount?: number;\n floorAskPrice?: Price | null;\n topBidValue?: number | null;\n createdAt?: string;\n};\n\nexport type Collection = {\n id?: string;\n name?: string;\n slug?: string;\n symbol?: string;\n imageUrl?: string;\n image?: string;\n isSpam?: boolean;\n isNsfw?: boolean;\n creator?: string;\n tokenCount?: string;\n metadataDisabled?: boolean;\n openseaVerificationStatus?: string;\n floorAskPrice?: Price;\n royaltiesBps?: number;\n royalties?: Royalties[];\n};\n\nexport type Royalties = {\n bps?: number;\n recipient?: string;\n};\n\nexport type Ownership = {\n tokenCount?: string;\n onSaleCount?: string;\n floorAsk?: FloorAsk;\n acquiredAt?: string;\n};\n\nexport type FloorAsk = {\n id?: string;\n price?: Price;\n maker?: string;\n kind?: string;\n validFrom?: number;\n validUntil?: number;\n source?: Source;\n rawData?: Metadata;\n isNativeOffChainCancellable?: boolean;\n};\n\nexport type Price = {\n currency?: {\n contract?: string;\n name?: string;\n symbol?: string;\n decimals?: number;\n chainId?: number;\n };\n amount?: {\n raw?: string;\n decimal?: number;\n usd?: number;\n native?: number;\n };\n netAmount?: {\n raw?: string;\n decimal?: number;\n usd?: number;\n native?: number;\n };\n};\n\nexport type Metadata = {\n imageOriginal?: string;\n tokenURI?: string;\n};\n\n/**\n * Controller that passively polls on a set interval for NFT auto detection\n */\nexport class NftDetectionController extends StaticIntervalPollingControllerV1<\n NftDetectionConfig,\n BaseState\n> {\n private intervalId?: ReturnType<typeof setTimeout>;\n\n private getOwnerNftApi({\n address,\n next,\n }: {\n address: string;\n next?: string;\n }) {\n return `${NFT_API_BASE_URL}/users/${address}/tokens?chainIds=1&limit=50&includeTopBid=true&continuation=${\n next ?? ''\n }`;\n }\n\n private async getOwnerNfts(address: string) {\n let nftApiResponse: ReservoirResponse;\n let nfts: TokensResponse[] = [];\n let next;\n\n do {\n nftApiResponse = await fetchWithErrorHandling({\n url: this.getOwnerNftApi({ address, next }),\n options: {\n headers: {\n Version: '1',\n },\n },\n timeout: 15000,\n });\n\n if (!nftApiResponse) {\n return nfts;\n }\n\n const newNfts = nftApiResponse.tokens.filter(\n (elm) =>\n elm.token.isSpam === false &&\n (elm.blockaidResult?.result_type\n ? elm.blockaidResult?.result_type === BlockaidResultType.Benign\n : true),\n );\n\n nfts = [...nfts, ...newNfts];\n } while ((next = nftApiResponse.continuation));\n\n return nfts;\n }\n\n /**\n * Name of this controller used during composition\n */\n override name = 'NftDetectionController';\n\n private readonly getOpenSeaApiKey: () => string | undefined;\n\n private readonly addNft: NftController['addNft'];\n\n private readonly getNftApi: NftController['getNftApi'];\n\n private readonly getNftState: () => NftState;\n\n private readonly getNetworkClientById: NetworkController['getNetworkClientById'];\n\n /**\n * Creates an NftDetectionController instance.\n *\n * @param options - The controller options.\n * @param options.chainId - The chain ID of the current network.\n * @param options.onNftsStateChange - Allows subscribing to assets controller state changes.\n * @param options.onPreferencesStateChange - Allows subscribing to preferences controller state changes.\n * @param options.onNetworkStateChange - Allows subscribing to network controller state changes.\n * @param options.getOpenSeaApiKey - Gets the OpenSea API key, if one is set.\n * @param options.addNft - Add an NFT.\n * @param options.getNftApi - Gets the URL to fetch an NFT from OpenSea.\n * @param options.getNftState - Gets the current state of the Assets controller.\n * @param options.disabled - Represents previous value of useNftDetection. Used to detect changes of useNftDetection. Default value is true.\n * @param options.selectedAddress - Represents current selected address.\n * @param options.getNetworkClientById - Gets the network client by ID, from the NetworkController.\n * @param config - Initial options used to configure this controller.\n * @param state - Initial state to set on this controller.\n */\n constructor(\n {\n chainId: initialChainId,\n getNetworkClientById,\n onPreferencesStateChange,\n onNetworkStateChange,\n getOpenSeaApiKey,\n addNft,\n getNftApi,\n getNftState,\n disabled: initialDisabled,\n selectedAddress: initialSelectedAddress,\n }: {\n chainId: Hex;\n getNetworkClientById: NetworkController['getNetworkClientById'];\n onNftsStateChange: (listener: (nftsState: NftState) => void) => void;\n onPreferencesStateChange: (\n listener: (preferencesState: PreferencesState) => void,\n ) => void;\n onNetworkStateChange: (\n listener: (networkState: NetworkState) => void,\n ) => void;\n getOpenSeaApiKey: () => string | undefined;\n addNft: NftController['addNft'];\n getNftApi: NftController['getNftApi'];\n getNftState: () => NftState;\n disabled: boolean;\n selectedAddress: string;\n },\n config?: Partial<NftDetectionConfig>,\n state?: Partial<BaseState>,\n ) {\n super(config, state);\n this.defaultConfig = {\n interval: DEFAULT_INTERVAL,\n chainId: initialChainId,\n selectedAddress: initialSelectedAddress,\n disabled: initialDisabled,\n };\n this.initialize();\n this.getNftState = getNftState;\n this.getNetworkClientById = getNetworkClientById;\n onPreferencesStateChange(({ selectedAddress, useNftDetection }) => {\n const { selectedAddress: previouslySelectedAddress, disabled } =\n this.config;\n\n if (\n selectedAddress !== previouslySelectedAddress ||\n !useNftDetection !== disabled\n ) {\n this.configure({ selectedAddress, disabled: !useNftDetection });\n if (useNftDetection) {\n this.start();\n } else {\n this.stop();\n }\n }\n });\n\n onNetworkStateChange(({ selectedNetworkClientId }) => {\n const selectedNetworkClient = getNetworkClientById(\n selectedNetworkClientId,\n );\n const { chainId } = selectedNetworkClient.configuration;\n\n this.configure({ chainId });\n });\n this.getOpenSeaApiKey = getOpenSeaApiKey;\n this.addNft = addNft;\n this.getNftApi = getNftApi;\n this.setIntervalLength(this.config.interval);\n }\n\n async _executePoll(\n networkClientId: string,\n options: { address: string },\n ): Promise<void> {\n await this.detectNfts({ networkClientId, userAddress: options.address });\n }\n\n /**\n * Start polling for the currency rate.\n */\n async start() {\n if (!this.isMainnet() || this.disabled) {\n return;\n }\n\n await this.startPolling();\n }\n\n /**\n * Stop polling for the currency rate.\n */\n stop() {\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 * @param interval - An interval on which to poll.\n */\n private async startPolling(interval?: number): Promise<void> {\n interval && this.configure({ interval }, false, false);\n this.stopPolling();\n await this.detectNfts();\n this.intervalId = setInterval(async () => {\n await this.detectNfts();\n }, this.config.interval);\n }\n\n /**\n * Checks whether network is mainnet or not.\n *\n * @returns Whether current network is mainnet.\n */\n isMainnet = (): boolean => this.config.chainId === ChainId.mainnet;\n\n isMainnetByNetworkClientId = (networkClient: NetworkClient): boolean => {\n return networkClient.configuration.chainId === ChainId.mainnet;\n };\n\n /**\n * Triggers asset ERC721 token auto detection on mainnet. Any newly detected NFTs are\n * added.\n *\n * @param options - Options bag.\n * @param options.networkClientId - The network client ID to detect NFTs on.\n * @param options.userAddress - The address to detect NFTs for.\n */\n async detectNfts(\n {\n networkClientId,\n userAddress,\n }: {\n networkClientId?: NetworkClientId;\n userAddress: string;\n } = { userAddress: this.config.selectedAddress },\n ) {\n /* istanbul ignore if */\n if (!this.isMainnet() || this.disabled) {\n return;\n }\n /* istanbul ignore else */\n if (!userAddress) {\n return;\n }\n\n const apiNfts = await this.getOwnerNfts(userAddress);\n const addNftPromises = apiNfts.map(async (nft) => {\n const {\n tokenId: token_id,\n contract,\n kind,\n image: image_url,\n imageSmall: image_thumbnail_url,\n metadata: { imageOriginal: image_original_url } = {},\n name,\n description,\n attributes,\n topBid,\n lastSale,\n rarityRank,\n rarityScore,\n collection,\n } = nft.token;\n\n let ignored;\n /* istanbul ignore else */\n const { ignoredNfts } = this.getNftState();\n if (ignoredNfts.length) {\n ignored = ignoredNfts.find((c) => {\n /* istanbul ignore next */\n return (\n c.address === toChecksumHexAddress(contract) &&\n c.tokenId === token_id\n );\n });\n }\n\n /* istanbul ignore else */\n if (!ignored) {\n /* istanbul ignore next */\n const nftMetadata: NftMetadata = Object.assign(\n {},\n { name },\n description && { description },\n image_url && { image: image_url },\n image_thumbnail_url && { imageThumbnail: image_thumbnail_url },\n image_original_url && { imageOriginal: image_original_url },\n kind && { standard: kind.toUpperCase() },\n lastSale && { lastSale },\n attributes && { attributes },\n topBid && { topBid },\n rarityRank && { rarityRank },\n rarityScore && { rarityScore },\n collection && { collection },\n );\n\n await this.addNft(contract, token_id, {\n nftMetadata,\n userAddress,\n source: Source.Detected,\n networkClientId,\n });\n }\n });\n await Promise.all(addNftPromises);\n }\n}\n\nexport default NftDetectionController;\n"]}
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2
2
 
3
- var _chunkLS6R3HQLjs = require('./chunk-LS6R3HQL.js');
3
+ var _chunkNEXY7SE2js = require('./chunk-NEXY7SE2.js');
4
4
 
5
5
 
6
6
 
@@ -99,7 +99,7 @@ var TokenDetectionController = class extends _pollingcontroller.StaticIntervalPo
99
99
  _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _networkClientId, networkClientId);
100
100
  const { useTokenDetection: defaultUseTokenDetection } = this.messagingSystem.call("PreferencesController:getState");
101
101
  _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _isDetectionEnabledFromPreferences, defaultUseTokenDetection);
102
- _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _isDetectionEnabledForNetwork, _chunkLS6R3HQLjs.isTokenDetectionSupportedForNetwork.call(void 0, chainId));
102
+ _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _isDetectionEnabledForNetwork, _chunkNEXY7SE2js.isTokenDetectionSupportedForNetwork.call(void 0, chainId));
103
103
  _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _getBalancesInSingleCall, getBalancesInSingleCall);
104
104
  _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _trackMetaMetricsEvent, trackMetaMetricsEvent);
105
105
  const { isUnlocked } = this.messagingSystem.call(
@@ -169,7 +169,7 @@ var TokenDetectionController = class extends _pollingcontroller.StaticIntervalPo
169
169
  const { chainId, networkClientId: selectedNetworkClientId } = _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getCorrectChainIdAndNetworkClientId, getCorrectChainIdAndNetworkClientId_fn).call(this, networkClientId);
170
170
  const chainIdAgainstWhichToDetect = chainId;
171
171
  const networkClientIdAgainstWhichToDetect = selectedNetworkClientId;
172
- if (!_chunkLS6R3HQLjs.isTokenDetectionSupportedForNetwork.call(void 0, chainIdAgainstWhichToDetect)) {
172
+ if (!_chunkNEXY7SE2js.isTokenDetectionSupportedForNetwork.call(void 0, chainIdAgainstWhichToDetect)) {
173
173
  return;
174
174
  }
175
175
  if (!_chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _isDetectionEnabledFromPreferences) && chainIdAgainstWhichToDetect !== _controllerutils.ChainId.mainnet) {
@@ -253,7 +253,7 @@ registerEventListeners_fn = function() {
253
253
  async ({ selectedNetworkClientId }) => {
254
254
  const isNetworkClientIdChanged = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _networkClientId) !== selectedNetworkClientId;
255
255
  const { chainId: newChainId } = _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getCorrectChainIdAndNetworkClientId, getCorrectChainIdAndNetworkClientId_fn).call(this, selectedNetworkClientId);
256
- _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _isDetectionEnabledForNetwork, _chunkLS6R3HQLjs.isTokenDetectionSupportedForNetwork.call(void 0, newChainId));
256
+ _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _isDetectionEnabledForNetwork, _chunkNEXY7SE2js.isTokenDetectionSupportedForNetwork.call(void 0, newChainId));
257
257
  if (isNetworkClientIdChanged && _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _isDetectionEnabledForNetwork)) {
258
258
  _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _networkClientId, selectedNetworkClientId);
259
259
  await _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _restartTokenDetection, restartTokenDetection_fn).call(this, {
@@ -408,4 +408,4 @@ var TokenDetectionController_default = TokenDetectionController;
408
408
 
409
409
 
410
410
  exports.isEqualCaseInsensitive = isEqualCaseInsensitive; exports.STATIC_MAINNET_TOKEN_LIST = STATIC_MAINNET_TOKEN_LIST; exports.controllerName = controllerName; exports.TokenDetectionController = TokenDetectionController; exports.TokenDetectionController_default = TokenDetectionController_default;
411
- //# sourceMappingURL=chunk-I53XGBU3.js.map
411
+ //# sourceMappingURL=chunk-HDI4L2DD.js.map
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=chunk-JYHAAA6W.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}