@metamask/assets-controllers 83.1.0 → 85.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 (164) hide show
  1. package/CHANGELOG.md +39 -2
  2. package/dist/AccountTrackerController.cjs +20 -21
  3. package/dist/AccountTrackerController.cjs.map +1 -1
  4. package/dist/AccountTrackerController.d.cts +4 -3
  5. package/dist/AccountTrackerController.d.cts.map +1 -1
  6. package/dist/AccountTrackerController.d.mts +4 -3
  7. package/dist/AccountTrackerController.d.mts.map +1 -1
  8. package/dist/AccountTrackerController.mjs +20 -21
  9. package/dist/AccountTrackerController.mjs.map +1 -1
  10. package/dist/AssetsContractController.cjs +10 -10
  11. package/dist/AssetsContractController.cjs.map +1 -1
  12. package/dist/AssetsContractController.d.cts +3 -3
  13. package/dist/AssetsContractController.d.cts.map +1 -1
  14. package/dist/AssetsContractController.d.mts +3 -3
  15. package/dist/AssetsContractController.d.mts.map +1 -1
  16. package/dist/AssetsContractController.mjs +10 -10
  17. package/dist/AssetsContractController.mjs.map +1 -1
  18. package/dist/CurrencyRateController.cjs +68 -15
  19. package/dist/CurrencyRateController.cjs.map +1 -1
  20. package/dist/CurrencyRateController.d.cts +18 -10
  21. package/dist/CurrencyRateController.d.cts.map +1 -1
  22. package/dist/CurrencyRateController.d.mts +18 -10
  23. package/dist/CurrencyRateController.d.mts.map +1 -1
  24. package/dist/CurrencyRateController.mjs +68 -15
  25. package/dist/CurrencyRateController.mjs.map +1 -1
  26. package/dist/DeFiPositionsController/DeFiPositionsController.cjs +7 -7
  27. package/dist/DeFiPositionsController/DeFiPositionsController.cjs.map +1 -1
  28. package/dist/DeFiPositionsController/DeFiPositionsController.d.cts +3 -2
  29. package/dist/DeFiPositionsController/DeFiPositionsController.d.cts.map +1 -1
  30. package/dist/DeFiPositionsController/DeFiPositionsController.d.mts +3 -2
  31. package/dist/DeFiPositionsController/DeFiPositionsController.d.mts.map +1 -1
  32. package/dist/DeFiPositionsController/DeFiPositionsController.mjs +7 -7
  33. package/dist/DeFiPositionsController/DeFiPositionsController.mjs.map +1 -1
  34. package/dist/MultichainAssetsController/MultichainAssetsController.cjs +54 -22
  35. package/dist/MultichainAssetsController/MultichainAssetsController.cjs.map +1 -1
  36. package/dist/MultichainAssetsController/MultichainAssetsController.d.cts +18 -3
  37. package/dist/MultichainAssetsController/MultichainAssetsController.d.cts.map +1 -1
  38. package/dist/MultichainAssetsController/MultichainAssetsController.d.mts +18 -3
  39. package/dist/MultichainAssetsController/MultichainAssetsController.d.mts.map +1 -1
  40. package/dist/MultichainAssetsController/MultichainAssetsController.mjs +54 -22
  41. package/dist/MultichainAssetsController/MultichainAssetsController.mjs.map +1 -1
  42. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.cjs +13 -13
  43. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.cjs.map +1 -1
  44. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.cts +4 -3
  45. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.cts.map +1 -1
  46. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.mts +4 -3
  47. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.mts.map +1 -1
  48. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.mjs +13 -13
  49. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.mjs.map +1 -1
  50. package/dist/MultichainBalancesController/MultichainBalancesController.cjs +9 -9
  51. package/dist/MultichainBalancesController/MultichainBalancesController.cjs.map +1 -1
  52. package/dist/MultichainBalancesController/MultichainBalancesController.d.cts +3 -2
  53. package/dist/MultichainBalancesController/MultichainBalancesController.d.cts.map +1 -1
  54. package/dist/MultichainBalancesController/MultichainBalancesController.d.mts +3 -2
  55. package/dist/MultichainBalancesController/MultichainBalancesController.d.mts.map +1 -1
  56. package/dist/MultichainBalancesController/MultichainBalancesController.mjs +9 -9
  57. package/dist/MultichainBalancesController/MultichainBalancesController.mjs.map +1 -1
  58. package/dist/NftController.cjs +25 -25
  59. package/dist/NftController.cjs.map +1 -1
  60. package/dist/NftController.d.cts +3 -3
  61. package/dist/NftController.d.cts.map +1 -1
  62. package/dist/NftController.d.mts +3 -3
  63. package/dist/NftController.d.mts.map +1 -1
  64. package/dist/NftController.mjs +25 -25
  65. package/dist/NftController.mjs.map +1 -1
  66. package/dist/NftDetectionController.cjs +5 -6
  67. package/dist/NftDetectionController.cjs.map +1 -1
  68. package/dist/NftDetectionController.d.cts +5 -5
  69. package/dist/NftDetectionController.d.cts.map +1 -1
  70. package/dist/NftDetectionController.d.mts +5 -5
  71. package/dist/NftDetectionController.d.mts.map +1 -1
  72. package/dist/NftDetectionController.mjs +5 -6
  73. package/dist/NftDetectionController.mjs.map +1 -1
  74. package/dist/RatesController/RatesController.cjs +5 -5
  75. package/dist/RatesController/RatesController.cjs.map +1 -1
  76. package/dist/RatesController/RatesController.d.cts.map +1 -1
  77. package/dist/RatesController/RatesController.d.mts.map +1 -1
  78. package/dist/RatesController/RatesController.mjs +5 -5
  79. package/dist/RatesController/RatesController.mjs.map +1 -1
  80. package/dist/RatesController/types.cjs.map +1 -1
  81. package/dist/RatesController/types.d.cts +3 -2
  82. package/dist/RatesController/types.d.cts.map +1 -1
  83. package/dist/RatesController/types.d.mts +3 -2
  84. package/dist/RatesController/types.d.mts.map +1 -1
  85. package/dist/RatesController/types.mjs.map +1 -1
  86. package/dist/TokenBalancesController.cjs +22 -22
  87. package/dist/TokenBalancesController.cjs.map +1 -1
  88. package/dist/TokenBalancesController.d.cts +3 -2
  89. package/dist/TokenBalancesController.d.cts.map +1 -1
  90. package/dist/TokenBalancesController.d.mts +3 -2
  91. package/dist/TokenBalancesController.d.mts.map +1 -1
  92. package/dist/TokenBalancesController.mjs +22 -22
  93. package/dist/TokenBalancesController.mjs.map +1 -1
  94. package/dist/TokenDetectionController.cjs +24 -24
  95. package/dist/TokenDetectionController.cjs.map +1 -1
  96. package/dist/TokenDetectionController.d.cts +4 -3
  97. package/dist/TokenDetectionController.d.cts.map +1 -1
  98. package/dist/TokenDetectionController.d.mts +4 -3
  99. package/dist/TokenDetectionController.d.mts.map +1 -1
  100. package/dist/TokenDetectionController.mjs +24 -24
  101. package/dist/TokenDetectionController.mjs.map +1 -1
  102. package/dist/TokenListController.cjs +4 -4
  103. package/dist/TokenListController.cjs.map +1 -1
  104. package/dist/TokenListController.d.cts +3 -2
  105. package/dist/TokenListController.d.cts.map +1 -1
  106. package/dist/TokenListController.d.mts +3 -2
  107. package/dist/TokenListController.d.mts.map +1 -1
  108. package/dist/TokenListController.mjs +4 -4
  109. package/dist/TokenListController.mjs.map +1 -1
  110. package/dist/TokenRatesController.cjs +6 -6
  111. package/dist/TokenRatesController.cjs.map +1 -1
  112. package/dist/TokenRatesController.d.cts +3 -2
  113. package/dist/TokenRatesController.d.cts.map +1 -1
  114. package/dist/TokenRatesController.d.mts +3 -2
  115. package/dist/TokenRatesController.d.mts.map +1 -1
  116. package/dist/TokenRatesController.mjs +6 -6
  117. package/dist/TokenRatesController.mjs.map +1 -1
  118. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.cjs +4 -4
  119. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.cjs.map +1 -1
  120. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.cts +3 -2
  121. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.cts.map +1 -1
  122. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.mts +3 -2
  123. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.mts.map +1 -1
  124. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.mjs +4 -4
  125. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.mjs.map +1 -1
  126. package/dist/TokensController.cjs +17 -17
  127. package/dist/TokensController.cjs.map +1 -1
  128. package/dist/TokensController.d.cts +3 -2
  129. package/dist/TokensController.d.cts.map +1 -1
  130. package/dist/TokensController.d.mts +3 -2
  131. package/dist/TokensController.d.mts.map +1 -1
  132. package/dist/TokensController.mjs +17 -17
  133. package/dist/TokensController.mjs.map +1 -1
  134. package/dist/balances.cjs +20 -12
  135. package/dist/balances.cjs.map +1 -1
  136. package/dist/balances.d.cts +7 -3
  137. package/dist/balances.d.cts.map +1 -1
  138. package/dist/balances.d.mts +7 -3
  139. package/dist/balances.d.mts.map +1 -1
  140. package/dist/balances.mjs +20 -12
  141. package/dist/balances.mjs.map +1 -1
  142. package/dist/selectors/token-selectors.cjs +5 -1
  143. package/dist/selectors/token-selectors.cjs.map +1 -1
  144. package/dist/selectors/token-selectors.d.cts +21 -14
  145. package/dist/selectors/token-selectors.d.cts.map +1 -1
  146. package/dist/selectors/token-selectors.d.mts +21 -14
  147. package/dist/selectors/token-selectors.d.mts.map +1 -1
  148. package/dist/selectors/token-selectors.mjs +5 -1
  149. package/dist/selectors/token-selectors.mjs.map +1 -1
  150. package/dist/token-prices-service/abstract-token-prices-service.cjs.map +1 -1
  151. package/dist/token-prices-service/abstract-token-prices-service.d.cts +30 -0
  152. package/dist/token-prices-service/abstract-token-prices-service.d.cts.map +1 -1
  153. package/dist/token-prices-service/abstract-token-prices-service.d.mts +30 -0
  154. package/dist/token-prices-service/abstract-token-prices-service.d.mts.map +1 -1
  155. package/dist/token-prices-service/abstract-token-prices-service.mjs.map +1 -1
  156. package/dist/token-prices-service/codefi-v2.cjs +75 -0
  157. package/dist/token-prices-service/codefi-v2.cjs.map +1 -1
  158. package/dist/token-prices-service/codefi-v2.d.cts +15 -1
  159. package/dist/token-prices-service/codefi-v2.d.cts.map +1 -1
  160. package/dist/token-prices-service/codefi-v2.d.mts +15 -1
  161. package/dist/token-prices-service/codefi-v2.d.mts.map +1 -1
  162. package/dist/token-prices-service/codefi-v2.mjs +75 -0
  163. package/dist/token-prices-service/codefi-v2.mjs.map +1 -1
  164. package/package.json +26 -25
@@ -1,13 +1,18 @@
1
- import type { RestrictedMessenger, ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
1
+ import type { ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
2
+ import type { Messenger } from "@metamask/messenger";
2
3
  import type { NetworkControllerGetNetworkClientByIdAction } from "@metamask/network-controller";
3
4
  import { fetchMultiExchangeRate as defaultFetchMultiExchangeRate } from "./crypto-compare-service/index.cjs";
5
+ import type { AbstractTokenPricesService } from "./token-prices-service/abstract-token-prices-service.cjs";
4
6
  /**
5
- * @type CurrencyRateState
6
- * @property currencyRates - Object keyed by native currency
7
- * @property currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch
8
- * @property currencyRates.conversionRate - Conversion rate from current base asset to the current currency
9
- * @property currentCurrency - Currently-active ISO 4217 currency code
10
- * @property usdConversionRate - Conversion rate from usd to the current currency
7
+ * currencyRates - Object keyed by native currency
8
+ *
9
+ * currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch
10
+ *
11
+ * currencyRates.conversionRate - Conversion rate from current base asset to the current currency
12
+ *
13
+ * currentCurrency - Currently-active ISO 4217 currency code
14
+ *
15
+ * usdConversionRate - Conversion rate from usd to the current currency
11
16
  */
12
17
  export type CurrencyRateState = {
13
18
  currentCurrency: string;
@@ -23,7 +28,7 @@ export type CurrencyRateControllerEvents = CurrencyRateStateChange;
23
28
  export type GetCurrencyRateState = ControllerGetStateAction<typeof name, CurrencyRateState>;
24
29
  export type CurrencyRateControllerActions = GetCurrencyRateState;
25
30
  type AllowedActions = NetworkControllerGetNetworkClientByIdAction;
26
- type CurrencyRateMessenger = RestrictedMessenger<typeof name, CurrencyRateControllerActions | AllowedActions, CurrencyRateControllerEvents, AllowedActions['type'], never>;
31
+ export type CurrencyRateMessenger = Messenger<typeof name, CurrencyRateControllerActions | AllowedActions, CurrencyRateControllerEvents>;
27
32
  /** The input to start polling for the {@link CurrencyRateController} */
28
33
  type CurrencyRatePollingInput = {
29
34
  nativeCurrencies: string[];
@@ -48,6 +53,7 @@ declare const CurrencyRateController_base: (abstract new (...args: any[]) => {
48
53
  * asset to the user's preferred currency.
49
54
  */
50
55
  export declare class CurrencyRateController extends CurrencyRateController_base<typeof name, CurrencyRateState, CurrencyRateMessenger> {
56
+ #private;
51
57
  private readonly mutex;
52
58
  private readonly fetchMultiExchangeRate;
53
59
  private readonly includeUsdRate;
@@ -58,18 +64,20 @@ export declare class CurrencyRateController extends CurrencyRateController_base<
58
64
  * @param options - Constructor options.
59
65
  * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.
60
66
  * @param options.interval - The polling interval, in milliseconds.
61
- * @param options.messenger - A reference to the messaging system.
67
+ * @param options.messenger - A reference to the messenger.
62
68
  * @param options.state - Initial state to set on this controller.
63
69
  * @param options.useExternalServices - Feature Switch for using external services (default: true)
64
70
  * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
71
+ * @param options.tokenPricesService - An object in charge of retrieving token prices
65
72
  */
66
- constructor({ includeUsdRate, interval, useExternalServices, messenger, state, fetchMultiExchangeRate, }: {
73
+ constructor({ includeUsdRate, interval, useExternalServices, messenger, state, fetchMultiExchangeRate, tokenPricesService, }: {
67
74
  includeUsdRate?: boolean;
68
75
  interval?: number;
69
76
  messenger: CurrencyRateMessenger;
70
77
  state?: Partial<CurrencyRateState>;
71
78
  useExternalServices?: () => boolean;
72
79
  fetchMultiExchangeRate?: typeof defaultFetchMultiExchangeRate;
80
+ tokenPricesService: AbstractTokenPricesService;
73
81
  });
74
82
  /**
75
83
  * Sets a currency to track.
@@ -1 +1 @@
1
- {"version":3,"file":"CurrencyRateController.d.cts","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AAKnC,OAAO,KAAK,EAAE,2CAA2C,EAAE,qCAAqC;AAIhG,OAAO,E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ACS,EACV,cAAsB,EACtB,QAAiB,EACjB,mBAAgC,EAChC,SAAS,EACT,KAAK,EACL,sBAAsD,GACvD,EAAE;QACD,cAAc,CAAC,EAAE,OAAO,CAAC;QACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,qBAAqB,CAAC;QACjC,KAAK,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC,CAAC;QACnC,mBAAmB,CAAC,EAAE,MAAM,OAAO,CAAC;QACpC,sBAAsB,CAAC,EAAE,OAAO,6BAA6B,CAAC;KAC/D;IAaD;;;;OAIG;IACG,kBAAkB,CAAC,eAAe,EAAE,MAAM;IAkBhD;;;;OAIG;IACG,kBAAkB,CACtB,gBAAgB,EAAE,CAAC,MAAM,GAAG,SAAS,CAAC,EAAE,GACvC,OAAO,CAAC,IAAI,CAAC;IA2DhB;;;;OAIG;IACM,OAAO;IAKhB;;;;;OAKG;IACG,YAAY,CAAC,EACjB,gBAAgB,GACjB,EAAE,wBAAwB,GAAG,OAAO,CAAC,IAAI,CAAC;CAG5C;AAED,eAAe,sBAAsB,CAAC"}
1
+ {"version":3,"file":"CurrencyRateController.d.cts","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AAKnC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,2CAA2C,EAAE,qCAAqC;AAIhG,OAAO,EAAE,sBAAsB,IAAI,6BAA6B,EAAE,2CAAiC;AACnG,OAAO,KAAK,EAAE,0BAA0B,EAAE,iEAA6D;AAEvG;;;;;;;;;;GAUG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,eAAe,EAAE,MAAM,CAAC;IACxB,aAAa,EAAE,MAAM,CACnB,MAAM,EACN;QACE,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;QAC9B,cAAc,EAAE,MAAM,GAAG,IAAI,C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,CAAC,EAAE,MAAM,OAAO,CAAC;QACpC,sBAAsB,CAAC,EAAE,OAAO,6BAA6B,CAAC;QAC9D,kBAAkB,EAAE,0BAA0B,CAAC;KAChD;IAcD;;;;OAIG;IACG,kBAAkB,CAAC,eAAe,EAAE,MAAM;IAqFhD;;;;OAIG;IACG,kBAAkB,CACtB,gBAAgB,EAAE,CAAC,MAAM,GAAG,SAAS,CAAC,EAAE,GACvC,OAAO,CAAC,IAAI,CAAC;IA0ChB;;;;OAIG;IACM,OAAO;IAKhB;;;;;OAKG;IACG,YAAY,CAAC,EACjB,gBAAgB,GACjB,EAAE,wBAAwB,GAAG,OAAO,CAAC,IAAI,CAAC;CAG5C;AAED,eAAe,sBAAsB,CAAC"}
@@ -1,13 +1,18 @@
1
- import type { RestrictedMessenger, ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
1
+ import type { ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
2
+ import type { Messenger } from "@metamask/messenger";
2
3
  import type { NetworkControllerGetNetworkClientByIdAction } from "@metamask/network-controller";
3
4
  import { fetchMultiExchangeRate as defaultFetchMultiExchangeRate } from "./crypto-compare-service/index.mjs";
5
+ import type { AbstractTokenPricesService } from "./token-prices-service/abstract-token-prices-service.mjs";
4
6
  /**
5
- * @type CurrencyRateState
6
- * @property currencyRates - Object keyed by native currency
7
- * @property currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch
8
- * @property currencyRates.conversionRate - Conversion rate from current base asset to the current currency
9
- * @property currentCurrency - Currently-active ISO 4217 currency code
10
- * @property usdConversionRate - Conversion rate from usd to the current currency
7
+ * currencyRates - Object keyed by native currency
8
+ *
9
+ * currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch
10
+ *
11
+ * currencyRates.conversionRate - Conversion rate from current base asset to the current currency
12
+ *
13
+ * currentCurrency - Currently-active ISO 4217 currency code
14
+ *
15
+ * usdConversionRate - Conversion rate from usd to the current currency
11
16
  */
12
17
  export type CurrencyRateState = {
13
18
  currentCurrency: string;
@@ -23,7 +28,7 @@ export type CurrencyRateControllerEvents = CurrencyRateStateChange;
23
28
  export type GetCurrencyRateState = ControllerGetStateAction<typeof name, CurrencyRateState>;
24
29
  export type CurrencyRateControllerActions = GetCurrencyRateState;
25
30
  type AllowedActions = NetworkControllerGetNetworkClientByIdAction;
26
- type CurrencyRateMessenger = RestrictedMessenger<typeof name, CurrencyRateControllerActions | AllowedActions, CurrencyRateControllerEvents, AllowedActions['type'], never>;
31
+ export type CurrencyRateMessenger = Messenger<typeof name, CurrencyRateControllerActions | AllowedActions, CurrencyRateControllerEvents>;
27
32
  /** The input to start polling for the {@link CurrencyRateController} */
28
33
  type CurrencyRatePollingInput = {
29
34
  nativeCurrencies: string[];
@@ -48,6 +53,7 @@ declare const CurrencyRateController_base: (abstract new (...args: any[]) => {
48
53
  * asset to the user's preferred currency.
49
54
  */
50
55
  export declare class CurrencyRateController extends CurrencyRateController_base<typeof name, CurrencyRateState, CurrencyRateMessenger> {
56
+ #private;
51
57
  private readonly mutex;
52
58
  private readonly fetchMultiExchangeRate;
53
59
  private readonly includeUsdRate;
@@ -58,18 +64,20 @@ export declare class CurrencyRateController extends CurrencyRateController_base<
58
64
  * @param options - Constructor options.
59
65
  * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.
60
66
  * @param options.interval - The polling interval, in milliseconds.
61
- * @param options.messenger - A reference to the messaging system.
67
+ * @param options.messenger - A reference to the messenger.
62
68
  * @param options.state - Initial state to set on this controller.
63
69
  * @param options.useExternalServices - Feature Switch for using external services (default: true)
64
70
  * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
71
+ * @param options.tokenPricesService - An object in charge of retrieving token prices
65
72
  */
66
- constructor({ includeUsdRate, interval, useExternalServices, messenger, state, fetchMultiExchangeRate, }: {
73
+ constructor({ includeUsdRate, interval, useExternalServices, messenger, state, fetchMultiExchangeRate, tokenPricesService, }: {
67
74
  includeUsdRate?: boolean;
68
75
  interval?: number;
69
76
  messenger: CurrencyRateMessenger;
70
77
  state?: Partial<CurrencyRateState>;
71
78
  useExternalServices?: () => boolean;
72
79
  fetchMultiExchangeRate?: typeof defaultFetchMultiExchangeRate;
80
+ tokenPricesService: AbstractTokenPricesService;
73
81
  });
74
82
  /**
75
83
  * Sets a currency to track.
@@ -1 +1 @@
1
- {"version":3,"file":"CurrencyRateController.d.mts","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,mBAAmB,EACnB,wBAAwB,EACxB,0BAA0B,EAC3B,kCAAkC;AAKnC,OAAO,KAAK,EAAE,2CAA2C,EAAE,qCAAqC;AAIhG,OAAO,EAAE,sBAAsB,IAAI,6BAA6B,EAAE,2CAAiC;AAEnG;;;;;;;GAOG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,eAAe,EAAE,MAAM,CAAC;IACxB,aAAa,EAAE,MAAM,CACnB,MAAM,EACN;QACE,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;QAC9B,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;QAC9B,iBAAiB,EAAE,MAAM,GAAG,IAAI,CAAC;KAClC,CACF,CAAC;CACH,CAAC;AAEF,QAAA,MAAM,IAAI,2BAA2B,CAAC;AAEtC,MAAM,MAAM,uBAAuB,GAAG,0BAA0B,CAC9D,OAAO,IAAI,EACX,iBAAiB,CAClB,CAAC;AAEF,MAAM,MAAM,4BAA4B,GAAG,uBAAuB,CAAC;AAEnE,MAAM,MAAM,oBAAoB,GAAG,wBAAwB,CACzD,OAAO,IAAI,EACX,iBAAiB,CAClB,CAAC;AAEF,MAAM,MAAM,6BAA6B,GAAG,oBAAoB,CAAC;AAEjE,KAAK,cAAc,GAAG,2CAA2C,CAAC;AAElE,KAAK,qBAAqB,GAAG,mBAAmB,CAC9C,OAAO,IAAI,EACX,6BAA6B,GAAG,cAAc,EAC9C,4BAA4B,EAC5B,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AAC,KAAK,CAAe;IAErC,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAC;IAExC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAC;IAEhC,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAgB;IAIpD;;;;;;;;;;;OAWG;gBACS,EACV,cAAsB,EACtB,QAAiB,EACjB,mBAAgC,EAChC,SAAS,EACT,KAAK,EACL,sBAAsD,EACtD,kBAAkB,GACnB,EAAE;QACD,cAAc,CAAC,EAAE,OAAO,CAAC;QACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,qBAAqB,CAAC;QACjC,KAAK,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC,CAAC;QACnC,mBAAmB,CAAC,EAAE,MAAM,OAAO,CAAC;QACpC,sBAAsB,CAAC,EAAE,OAAO,6BAA6B,CAAC;QAC9D,kBAAkB,EAAE,0BAA0B,CAAC;KAChD;IAcD;;;;OAIG;IACG,kBAAkB,CAAC,eAAe,EAAE,MAAM;IAqFhD;;;;OAIG;IACG,kBAAkB,CACtB,gBAAgB,EAAE,CAAC,MAAM,GAAG,SAAS,CAAC,EAAE,GACvC,OAAO,CAAC,IAAI,CAAC;IA0ChB;;;;OAIG;IACM,OAAO;IAKhB;;;;;OAKG;IACG,YAAY,CAAC,EACjB,gBAAgB,GACjB,EAAE,wBAAwB,GAAG,OAAO,CAAC,IAAI,CAAC;CAG5C;AAED,eAAe,sBAAsB,CAAC"}
@@ -1,3 +1,15 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ 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");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ 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");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _CurrencyRateController_instances, _CurrencyRateController_tokenPricesService, _CurrencyRateController_fetchExchangeRatesWithFallback;
1
13
  import { TESTNET_TICKER_SYMBOLS, FALL_BACK_VS_CURRENCY } from "@metamask/controller-utils";
2
14
  import { StaticIntervalPollingController } from "@metamask/polling-controller";
3
15
  import { Mutex } from "async-mutex";
@@ -7,13 +19,13 @@ const metadata = {
7
19
  currentCurrency: {
8
20
  includeInStateLogs: true,
9
21
  persist: true,
10
- anonymous: true,
22
+ includeInDebugSnapshot: true,
11
23
  usedInUi: true,
12
24
  },
13
25
  currencyRates: {
14
26
  includeInStateLogs: true,
15
27
  persist: true,
16
- anonymous: true,
28
+ includeInDebugSnapshot: true,
17
29
  usedInUi: true,
18
30
  },
19
31
  };
@@ -38,23 +50,27 @@ export class CurrencyRateController extends StaticIntervalPollingController() {
38
50
  * @param options - Constructor options.
39
51
  * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.
40
52
  * @param options.interval - The polling interval, in milliseconds.
41
- * @param options.messenger - A reference to the messaging system.
53
+ * @param options.messenger - A reference to the messenger.
42
54
  * @param options.state - Initial state to set on this controller.
43
55
  * @param options.useExternalServices - Feature Switch for using external services (default: true)
44
56
  * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
57
+ * @param options.tokenPricesService - An object in charge of retrieving token prices
45
58
  */
46
- constructor({ includeUsdRate = false, interval = 180000, useExternalServices = () => true, messenger, state, fetchMultiExchangeRate = defaultFetchMultiExchangeRate, }) {
59
+ constructor({ includeUsdRate = false, interval = 180000, useExternalServices = () => true, messenger, state, fetchMultiExchangeRate = defaultFetchMultiExchangeRate, tokenPricesService, }) {
47
60
  super({
48
61
  name,
49
62
  metadata,
50
63
  messenger,
51
64
  state: { ...defaultState, ...state },
52
65
  });
66
+ _CurrencyRateController_instances.add(this);
53
67
  this.mutex = new Mutex();
68
+ _CurrencyRateController_tokenPricesService.set(this, void 0);
54
69
  this.includeUsdRate = includeUsdRate;
55
70
  this.useExternalServices = useExternalServices;
56
71
  this.setIntervalLength(interval);
57
72
  this.fetchMultiExchangeRate = fetchMultiExchangeRate;
73
+ __classPrivateFieldSet(this, _CurrencyRateController_tokenPricesService, tokenPricesService, "f");
58
74
  }
59
75
  /**
60
76
  * Sets a currency to track.
@@ -90,7 +106,6 @@ export class CurrencyRateController extends StaticIntervalPollingController() {
90
106
  }
91
107
  const releaseLock = await this.mutex.acquire();
92
108
  try {
93
- const { currentCurrency } = this.state;
94
109
  // For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.
95
110
  // Map each native currency to the symbol we want to fetch for it.
96
111
  const testnetSymbols = Object.values(TESTNET_TICKER_SYMBOLS);
@@ -103,16 +118,7 @@ export class CurrencyRateController extends StaticIntervalPollingController() {
103
118
  : nativeCurrency;
104
119
  return acc;
105
120
  }, {});
106
- const fetchExchangeRateResponse = await this.fetchMultiExchangeRate(currentCurrency, [...new Set(Object.values(nativeCurrenciesToFetch))], this.includeUsdRate);
107
- const rates = Object.entries(nativeCurrenciesToFetch).reduce((acc, [nativeCurrency, fetchedCurrency]) => {
108
- const rate = fetchExchangeRateResponse[fetchedCurrency.toLowerCase()];
109
- acc[nativeCurrency] = {
110
- conversionDate: rate !== undefined ? Date.now() / 1000 : null,
111
- conversionRate: rate?.[currentCurrency.toLowerCase()] ?? null,
112
- usdConversionRate: rate?.usd ?? null,
113
- };
114
- return acc;
115
- }, {});
121
+ const rates = await __classPrivateFieldGet(this, _CurrencyRateController_instances, "m", _CurrencyRateController_fetchExchangeRatesWithFallback).call(this, nativeCurrenciesToFetch);
116
122
  this.update((state) => {
117
123
  state.currencyRates = {
118
124
  ...state.currencyRates,
@@ -147,5 +153,52 @@ export class CurrencyRateController extends StaticIntervalPollingController() {
147
153
  await this.updateExchangeRate(nativeCurrencies);
148
154
  }
149
155
  }
156
+ _CurrencyRateController_tokenPricesService = new WeakMap(), _CurrencyRateController_instances = new WeakSet(), _CurrencyRateController_fetchExchangeRatesWithFallback = async function _CurrencyRateController_fetchExchangeRatesWithFallback(nativeCurrenciesToFetch) {
157
+ const { currentCurrency } = this.state;
158
+ try {
159
+ const priceApiExchangeRatesResponse = await __classPrivateFieldGet(this, _CurrencyRateController_tokenPricesService, "f").fetchExchangeRates({
160
+ baseCurrency: currentCurrency,
161
+ includeUsdRate: this.includeUsdRate,
162
+ cryptocurrencies: [
163
+ ...new Set(Object.values(nativeCurrenciesToFetch)),
164
+ ],
165
+ });
166
+ const ratesPriceApi = Object.entries(nativeCurrenciesToFetch).reduce((acc, [nativeCurrency, fetchedCurrency]) => {
167
+ const rate = priceApiExchangeRatesResponse[fetchedCurrency.toLowerCase()];
168
+ acc[nativeCurrency] = {
169
+ conversionDate: rate !== undefined ? Date.now() / 1000 : null,
170
+ conversionRate: rate?.value
171
+ ? Number((1 / rate?.value).toFixed(2))
172
+ : null,
173
+ usdConversionRate: rate?.usd
174
+ ? Number((1 / rate?.usd).toFixed(2))
175
+ : null,
176
+ };
177
+ return acc;
178
+ }, {});
179
+ return ratesPriceApi;
180
+ }
181
+ catch (error) {
182
+ console.error('Failed to fetch exchange rates.', error);
183
+ }
184
+ // fallback to crypto compare
185
+ try {
186
+ const fetchExchangeRateResponse = await this.fetchMultiExchangeRate(currentCurrency, [...new Set(Object.values(nativeCurrenciesToFetch))], this.includeUsdRate);
187
+ const rates = Object.entries(nativeCurrenciesToFetch).reduce((acc, [nativeCurrency, fetchedCurrency]) => {
188
+ const rate = fetchExchangeRateResponse[fetchedCurrency.toLowerCase()];
189
+ acc[nativeCurrency] = {
190
+ conversionDate: rate !== undefined ? Date.now() / 1000 : null,
191
+ conversionRate: rate?.[currentCurrency.toLowerCase()] ?? null,
192
+ usdConversionRate: rate?.usd ?? null,
193
+ };
194
+ return acc;
195
+ }, {});
196
+ return rates;
197
+ }
198
+ catch (error) {
199
+ console.error('Failed to fetch exchange rates.', error);
200
+ throw error;
201
+ }
202
+ };
150
203
  export default CurrencyRateController;
151
204
  //# sourceMappingURL=CurrencyRateController.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"CurrencyRateController.mjs","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,sBAAsB,EACtB,qBAAqB,EACtB,mCAAmC;AAEpC,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAC/E,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAEpC,OAAO,EAAE,sBAAsB,IAAI,6BAA6B,EAAE,2CAAiC;AAsBnG,MAAM,IAAI,GAAG,wBAAwB,CAAC;AA0BtC,MAAM,QAAQ,GAAG;IACf,eAAe,EAAE;QACf,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;QACf,QAAQ,EAAE,IAAI;KACf;IACD,aAAa,EAAE;QACb,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,IAAI;QACf,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEF,MAAM,YAAY,GAAG;IACnB,eAAe,EAAE,KAAK;IACtB,aAAa,EAAE;QACb,GAAG,EAAE;YACH,cAAc,EAAE,CAAC;YACjB,cAAc,EAAE,CAAC;YACjB,iBAAiB,EAAE,IAAI;SACxB;KACF;CACF,CAAC;AAOF;;;GAGG;AACH,MAAM,OAAO,sBAAuB,SAAQ,+BAA+B,EAI1E;IASC;;;;;;;;;;OAUG;IACH,YAAY,EACV,cAAc,GAAG,KAAK,EACtB,QAAQ,GAAG,MAAM,EACjB,mBAAmB,GAAG,GAAG,EAAE,CAAC,IAAI,EACh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AAC,aAAa,GAAG;oBACpB,GAAG,KAAK,CAAC,aAAa;oBACtB,GAAG,KAAK;iBACT,CAAC;YACJ,CAAC,CAAC,CAAC;SACJ;QAAC,OAAO,KAAK,EAAE;YACd,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;YACxD,MAAM,KAAK,CAAC;SACb;gBAAS;YACR,WAAW,EAAE,CAAC;SACf;IACH,CAAC;IAED;;;;OAIG;IACM,OAAO;QACd,KAAK,CAAC,OAAO,EAAE,CAAC;QAChB,IAAI,CAAC,cAAc,EAAE,CAAC;IACxB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,YAAY,CAAC,EACjB,gBAAgB,GACS;QACzB,MAAM,IAAI,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,CAAC;IAClD,CAAC;CACF;AAED,eAAe,sBAAsB,CAAC","sourcesContent":["import type {\n RestrictedMessenger,\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 { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport { Mutex } from 'async-mutex';\n\nimport { fetchMultiExchangeRate as defaultFetchMultiExchangeRate } 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 = RestrictedMessenger<\n typeof name,\n CurrencyRateControllerActions | AllowedActions,\n CurrencyRateControllerEvents,\n AllowedActions['type'],\n never\n>;\n\nconst metadata = {\n currentCurrency: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\n currencyRates: {\n includeInStateLogs: true,\n persist: true,\n anonymous: true,\n usedInUi: true,\n },\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/** The input to start polling for the {@link CurrencyRateController} */\ntype CurrencyRatePollingInput = {\n nativeCurrencies: string[];\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<CurrencyRatePollingInput>()<\n typeof name,\n CurrencyRateState,\n CurrencyRateMessenger\n> {\n private readonly mutex = new Mutex();\n\n private readonly fetchMultiExchangeRate;\n\n private readonly includeUsdRate;\n\n private readonly useExternalServices: () => boolean;\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.useExternalServices - Feature Switch for using external services (default: true)\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 includeUsdRate = false,\n interval = 180000,\n useExternalServices = () => true,\n messenger,\n state,\n fetchMultiExchangeRate = defaultFetchMultiExchangeRate,\n }: {\n includeUsdRate?: boolean;\n interval?: number;\n messenger: CurrencyRateMessenger;\n state?: Partial<CurrencyRateState>;\n useExternalServices?: () => boolean;\n fetchMultiExchangeRate?: typeof defaultFetchMultiExchangeRate;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.includeUsdRate = includeUsdRate;\n this.useExternalServices = useExternalServices;\n this.setIntervalLength(interval);\n this.fetchMultiExchangeRate = fetchMultiExchangeRate;\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.updateExchangeRate(nativeCurrencies);\n }\n\n /**\n * Updates the exchange rate for the current currency and native currency pairs.\n *\n * @param nativeCurrencies - The native currency symbols to fetch exchange rates for.\n */\n async updateExchangeRate(\n nativeCurrencies: (string | undefined)[],\n ): Promise<void> {\n if (!this.useExternalServices()) {\n return;\n }\n\n const releaseLock = await this.mutex.acquire();\n try {\n const { currentCurrency } = this.state;\n\n // For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.\n // Map each native currency to the symbol we want to fetch for it.\n const testnetSymbols = Object.values(TESTNET_TICKER_SYMBOLS);\n const nativeCurrenciesToFetch = nativeCurrencies.reduce(\n (acc, nativeCurrency) => {\n if (!nativeCurrency) {\n return acc;\n }\n\n acc[nativeCurrency] = testnetSymbols.includes(nativeCurrency)\n ? FALL_BACK_VS_CURRENCY\n : nativeCurrency;\n return acc;\n },\n {} as Record<string, string>,\n );\n\n const fetchExchangeRateResponse = await this.fetchMultiExchangeRate(\n currentCurrency,\n [...new Set(Object.values(nativeCurrenciesToFetch))],\n this.includeUsdRate,\n );\n\n const rates = Object.entries(nativeCurrenciesToFetch).reduce(\n (acc, [nativeCurrency, fetchedCurrency]) => {\n const rate = fetchExchangeRateResponse[fetchedCurrency.toLowerCase()];\n acc[nativeCurrency] = {\n conversionDate: rate !== undefined ? Date.now() / 1000 : null,\n conversionRate: rate?.[currentCurrency.toLowerCase()] ?? null,\n usdConversionRate: rate?.usd ?? null,\n };\n return acc;\n },\n {} as CurrencyRateState['currencyRates'],\n );\n\n this.update((state) => {\n state.currencyRates = {\n ...state.currencyRates,\n ...rates,\n };\n });\n } catch (error) {\n console.error('Failed to fetch exchange rates.', error);\n throw error;\n } finally {\n releaseLock();\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 input - The input for the poll.\n * @param input.nativeCurrencies - The native currency symbols to poll prices for.\n */\n async _executePoll({\n nativeCurrencies,\n }: CurrencyRatePollingInput): Promise<void> {\n await this.updateExchangeRate(nativeCurrencies);\n }\n}\n\nexport default CurrencyRateController;\n"]}
1
+ {"version":3,"file":"CurrencyRateController.mjs","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAKA,OAAO,EACL,sBAAsB,EACtB,qBAAqB,EACtB,mCAAmC;AAGpC,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAC/E,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAEpC,OAAO,EAAE,sBAAsB,IAAI,6BAA6B,EAAE,2CAAiC;AA0BnG,MAAM,IAAI,GAAG,wBAAwB,CAAC;AAwBtC,MAAM,QAAQ,GAAqC;IACjD,eAAe,EAAE;QACf,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,aAAa,EAAE;QACb,kBAAkB,EAAE,IAAI;QAC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,KAAK,CAAC,CAAC;QACxD,MAAM,KAAK,CAAC;KACb;AACH,CAAC;AA0EH,eAAe,sBAAsB,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport {\n TESTNET_TICKER_SYMBOLS,\n FALL_BACK_VS_CURRENCY,\n} from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport { Mutex } from 'async-mutex';\n\nimport { fetchMultiExchangeRate as defaultFetchMultiExchangeRate } from './crypto-compare-service';\nimport type { AbstractTokenPricesService } from './token-prices-service/abstract-token-prices-service';\n\n/**\n * currencyRates - Object keyed by native currency\n *\n * currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch\n *\n * currencyRates.conversionRate - Conversion rate from current base asset to the current currency\n *\n * currentCurrency - Currently-active ISO 4217 currency code\n *\n * 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\nexport type CurrencyRateMessenger = Messenger<\n typeof name,\n CurrencyRateControllerActions | AllowedActions,\n CurrencyRateControllerEvents\n>;\n\nconst metadata: StateMetadata<CurrencyRateState> = {\n currentCurrency: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n currencyRates: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\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/** The input to start polling for the {@link CurrencyRateController} */\ntype CurrencyRatePollingInput = {\n nativeCurrencies: string[];\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<CurrencyRatePollingInput>()<\n typeof name,\n CurrencyRateState,\n CurrencyRateMessenger\n> {\n private readonly mutex = new Mutex();\n\n private readonly fetchMultiExchangeRate;\n\n private readonly includeUsdRate;\n\n private readonly useExternalServices: () => boolean;\n\n readonly #tokenPricesService: AbstractTokenPricesService;\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 messenger.\n * @param options.state - Initial state to set on this controller.\n * @param options.useExternalServices - Feature Switch for using external services (default: true)\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n * @param options.tokenPricesService - An object in charge of retrieving token prices\n */\n constructor({\n includeUsdRate = false,\n interval = 180000,\n useExternalServices = () => true,\n messenger,\n state,\n fetchMultiExchangeRate = defaultFetchMultiExchangeRate,\n tokenPricesService,\n }: {\n includeUsdRate?: boolean;\n interval?: number;\n messenger: CurrencyRateMessenger;\n state?: Partial<CurrencyRateState>;\n useExternalServices?: () => boolean;\n fetchMultiExchangeRate?: typeof defaultFetchMultiExchangeRate;\n tokenPricesService: AbstractTokenPricesService;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.includeUsdRate = includeUsdRate;\n this.useExternalServices = useExternalServices;\n this.setIntervalLength(interval);\n this.fetchMultiExchangeRate = fetchMultiExchangeRate;\n this.#tokenPricesService = tokenPricesService;\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.updateExchangeRate(nativeCurrencies);\n }\n\n async #fetchExchangeRatesWithFallback(\n nativeCurrenciesToFetch: Record<string, string>,\n ): Promise<CurrencyRateState['currencyRates']> {\n const { currentCurrency } = this.state;\n\n try {\n const priceApiExchangeRatesResponse =\n await this.#tokenPricesService.fetchExchangeRates({\n baseCurrency: currentCurrency,\n includeUsdRate: this.includeUsdRate,\n cryptocurrencies: [\n ...new Set(Object.values(nativeCurrenciesToFetch)),\n ],\n });\n\n const ratesPriceApi = Object.entries(nativeCurrenciesToFetch).reduce(\n (acc, [nativeCurrency, fetchedCurrency]) => {\n const rate =\n priceApiExchangeRatesResponse[fetchedCurrency.toLowerCase()];\n\n acc[nativeCurrency] = {\n conversionDate: rate !== undefined ? Date.now() / 1000 : null,\n conversionRate: rate?.value\n ? Number((1 / rate?.value).toFixed(2))\n : null,\n usdConversionRate: rate?.usd\n ? Number((1 / rate?.usd).toFixed(2))\n : null,\n };\n return acc;\n },\n {} as CurrencyRateState['currencyRates'],\n );\n return ratesPriceApi;\n } catch (error) {\n console.error('Failed to fetch exchange rates.', error);\n }\n\n // fallback to crypto compare\n\n try {\n const fetchExchangeRateResponse = await this.fetchMultiExchangeRate(\n currentCurrency,\n [...new Set(Object.values(nativeCurrenciesToFetch))],\n this.includeUsdRate,\n );\n\n const rates = Object.entries(nativeCurrenciesToFetch).reduce(\n (acc, [nativeCurrency, fetchedCurrency]) => {\n const rate = fetchExchangeRateResponse[fetchedCurrency.toLowerCase()];\n acc[nativeCurrency] = {\n conversionDate: rate !== undefined ? Date.now() / 1000 : null,\n conversionRate: rate?.[currentCurrency.toLowerCase()] ?? null,\n usdConversionRate: rate?.usd ?? null,\n };\n return acc;\n },\n {} as CurrencyRateState['currencyRates'],\n );\n\n return rates;\n } catch (error) {\n console.error('Failed to fetch exchange rates.', error);\n throw error;\n }\n }\n\n /**\n * Updates the exchange rate for the current currency and native currency pairs.\n *\n * @param nativeCurrencies - The native currency symbols to fetch exchange rates for.\n */\n async updateExchangeRate(\n nativeCurrencies: (string | undefined)[],\n ): Promise<void> {\n if (!this.useExternalServices()) {\n return;\n }\n\n const releaseLock = await this.mutex.acquire();\n try {\n // For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.\n // Map each native currency to the symbol we want to fetch for it.\n const testnetSymbols = Object.values(TESTNET_TICKER_SYMBOLS);\n const nativeCurrenciesToFetch = nativeCurrencies.reduce(\n (acc, nativeCurrency) => {\n if (!nativeCurrency) {\n return acc;\n }\n\n acc[nativeCurrency] = testnetSymbols.includes(nativeCurrency)\n ? FALL_BACK_VS_CURRENCY\n : nativeCurrency;\n return acc;\n },\n {} as Record<string, string>,\n );\n\n const rates = await this.#fetchExchangeRatesWithFallback(\n nativeCurrenciesToFetch,\n );\n\n this.update((state) => {\n state.currencyRates = {\n ...state.currencyRates,\n ...rates,\n };\n });\n } catch (error) {\n console.error('Failed to fetch exchange rates.', error);\n throw error;\n } finally {\n releaseLock();\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 input - The input for the poll.\n * @param input.nativeCurrencies - The native currency symbols to poll prices for.\n */\n async _executePoll({\n nativeCurrencies,\n }: CurrencyRatePollingInput): Promise<void> {\n await this.updateExchangeRate(nativeCurrencies);\n }\n}\n\nexport default CurrencyRateController;\n"]}
@@ -25,13 +25,13 @@ const controllerMetadata = {
25
25
  allDeFiPositions: {
26
26
  includeInStateLogs: false,
27
27
  persist: false,
28
- anonymous: false,
28
+ includeInDebugSnapshot: false,
29
29
  usedInUi: true,
30
30
  },
31
31
  allDeFiPositionsCount: {
32
32
  includeInStateLogs: false,
33
33
  persist: false,
34
- anonymous: false,
34
+ includeInDebugSnapshot: false,
35
35
  usedInUi: false,
36
36
  },
37
37
  };
@@ -68,19 +68,19 @@ class DeFiPositionsController extends (0, polling_controller_1.StaticIntervalPol
68
68
  this.setIntervalLength(TEN_MINUTES_IN_MS);
69
69
  __classPrivateFieldSet(this, _DeFiPositionsController_fetchPositions, (0, fetch_positions_1.buildPositionFetcher)(), "f");
70
70
  __classPrivateFieldSet(this, _DeFiPositionsController_isEnabled, isEnabled, "f");
71
- this.messagingSystem.subscribe('KeyringController:unlock', () => {
71
+ this.messenger.subscribe('KeyringController:unlock', () => {
72
72
  this.startPolling(null);
73
73
  });
74
- this.messagingSystem.subscribe('KeyringController:lock', () => {
74
+ this.messenger.subscribe('KeyringController:lock', () => {
75
75
  this.stopAllPolling();
76
76
  });
77
- this.messagingSystem.subscribe('TransactionController:transactionConfirmed', async (transactionMeta) => {
77
+ this.messenger.subscribe('TransactionController:transactionConfirmed', async (transactionMeta) => {
78
78
  if (!__classPrivateFieldGet(this, _DeFiPositionsController_isEnabled, "f").call(this)) {
79
79
  return;
80
80
  }
81
81
  await __classPrivateFieldGet(this, _DeFiPositionsController_instances, "m", _DeFiPositionsController_updateAccountPositions).call(this, transactionMeta.txParams.from);
82
82
  });
83
- this.messagingSystem.subscribe('AccountsController:accountAdded', async (account) => {
83
+ this.messenger.subscribe('AccountsController:accountAdded', async (account) => {
84
84
  if (!__classPrivateFieldGet(this, _DeFiPositionsController_isEnabled, "f").call(this) || !account.type.startsWith('eip155:')) {
85
85
  return;
86
86
  }
@@ -92,7 +92,7 @@ class DeFiPositionsController extends (0, polling_controller_1.StaticIntervalPol
92
92
  if (!__classPrivateFieldGet(this, _DeFiPositionsController_isEnabled, "f").call(this)) {
93
93
  return;
94
94
  }
95
- const accounts = this.messagingSystem.call('AccountsController:listAccounts');
95
+ const accounts = this.messenger.call('AccountsController:listAccounts');
96
96
  const initialResult = [];
97
97
  const results = await (0, assetsUtil_1.reduceInBatchesSerially)({
98
98
  initialResult,
@@ -1 +1 @@
1
- {"version":3,"file":"DeFiPositionsController.cjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAYA,qEAA+E;AAI/E,yEAAwE;AAExE,2DAAyD;AACzD,qEAGgC;AAChC,kDAAwD;AAExD,MAAM,iBAAiB,GAAG,MAAO,CAAC;AAElC,MAAM,0BAA0B,GAAG,EAAE,CAAC;AAEtC,MAAM,cAAc,GAAG,yBAAyB,CAAC;AAuCjD,MAAM,kBAAkB,GAAgD;IACtE,gBAAgB,EAAE;QAChB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,KAAK;QAChB,QAAQ,EAAE,IAAI;KACf;IACD,qBAAqB,EAAE;QACrB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,KAAK;QAChB,QAAQ,EAAE,KAAK;KAChB;CACF,CAAC;AAEK,MAAM,sCAAsC,GACjD,GAAiC,EAAE;IACjC,OAAO;QACL,gBAAgB,EAAE,EAAE;QACpB,qBAAqB,EAAE,EAAE;KAC1B,CAAC;AACJ,CAAC,CAAC;AANS,QAAA,sCAAsC,0CAM/C;AA4CJ;;GAEG;AACH,MAAa,uBAAwB,SAAQ,IAAA,oDAA+B,GAI3E;IASC;;;;;;;OAOG;IACH,YAAY,EACV,SAAS,EACT,SAAS,GAAG,GAAG,EAAE,CAAC,IAAI,EACtB,UAAU,GAKX;QACC,KAAK,CAAC;YACJ,IAAI,EAAE,cAAc;YACpB,QAAQ,EAAE,kBAAkB;YAC5B,SAAS;YACT,KAAK,EAAE,IAAA,8CA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,CAAC,CAAC;QAEH,uBAAA,IAAI,2CAAY,EAAE,KAAlB,IAAI,EAAe,WAAW,CAAC,CAAC;KACjC;AACH,CAAC","sourcesContent":["import type {\n AccountsControllerAccountAddedEvent,\n AccountsControllerListAccountsAction,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type { KeyringControllerUnlockEvent } from '@metamask/keyring-controller';\nimport type { KeyringControllerLockEvent } from '@metamask/keyring-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { TransactionControllerTransactionConfirmedEvent } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport { calculateDeFiPositionMetrics } from './calculate-defi-metrics';\nimport type { DefiPositionResponse } from './fetch-positions';\nimport { buildPositionFetcher } from './fetch-positions';\nimport {\n groupDeFiPositions,\n type GroupedDeFiPositions,\n} from './group-defi-positions';\nimport { reduceInBatchesSerially } from '../assetsUtil';\n\nconst TEN_MINUTES_IN_MS = 600_000;\n\nconst FETCH_POSITIONS_BATCH_SIZE = 10;\n\nconst controllerName = 'DeFiPositionsController';\n\nexport type GroupedDeFiPositionsPerChain = {\n [chain: Hex]: GroupedDeFiPositions;\n};\n\nexport type TrackingEventPayload = {\n event: string;\n category: string;\n properties: {\n totalPositions: number;\n totalMarketValueUSD: number;\n breakdown?: {\n protocolId: string;\n marketValueUSD: number;\n chainId: Hex;\n count: number;\n }[];\n };\n};\n\ntype TrackEventHook = (event: TrackingEventPayload) => void;\n\nexport type DeFiPositionsControllerState = {\n /**\n * Object containing DeFi positions per account and network\n */\n allDeFiPositions: {\n [accountAddress: string]: GroupedDeFiPositionsPerChain | null;\n };\n\n /**\n * Object containing DeFi positions count per account\n */\n allDeFiPositionsCount: {\n [accountAddress: string]: number;\n };\n};\n\nconst controllerMetadata: StateMetadata<DeFiPositionsControllerState> = {\n allDeFiPositions: {\n includeInStateLogs: false,\n persist: false,\n anonymous: false,\n usedInUi: true,\n },\n allDeFiPositionsCount: {\n includeInStateLogs: false,\n persist: false,\n anonymous: false,\n usedInUi: false,\n },\n};\n\nexport const getDefaultDefiPositionsControllerState =\n (): DeFiPositionsControllerState => {\n return {\n allDeFiPositions: {},\n allDeFiPositionsCount: {},\n };\n };\n\nexport type DeFiPositionsControllerActions =\n DeFiPositionsControllerGetStateAction;\n\nexport type DeFiPositionsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n DeFiPositionsControllerState\n>;\n\nexport type DeFiPositionsControllerEvents =\n DeFiPositionsControllerStateChangeEvent;\n\nexport type DeFiPositionsControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n DeFiPositionsControllerState\n >;\n\n/**\n * The external actions available to the {@link DeFiPositionsController}.\n */\nexport type AllowedActions = AccountsControllerListAccountsAction;\n\n/**\n * The external events available to the {@link DeFiPositionsController}.\n */\nexport type AllowedEvents =\n | KeyringControllerUnlockEvent\n | KeyringControllerLockEvent\n | TransactionControllerTransactionConfirmedEvent\n | AccountsControllerAccountAddedEvent;\n\n/**\n * The messenger of the {@link DeFiPositionsController}.\n */\nexport type DeFiPositionsControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n DeFiPositionsControllerActions | AllowedActions,\n DeFiPositionsControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Controller that stores assets and exposes convenience methods\n */\nexport class DeFiPositionsController extends StaticIntervalPollingController()<\n typeof controllerName,\n DeFiPositionsControllerState,\n DeFiPositionsControllerMessenger\n> {\n readonly #fetchPositions: (\n accountAddress: string,\n ) => Promise<DefiPositionResponse[]>;\n\n readonly #isEnabled: () => boolean;\n\n readonly #trackEvent?: TrackEventHook;\n\n /**\n * DeFiPositionsController constuctor\n *\n * @param options - Constructor options.\n * @param options.messenger - The controller messenger.\n * @param options.isEnabled - Function that returns whether the controller is enabled. (default: () => true)\n * @param options.trackEvent - Function to track events. (default: undefined)\n */\n constructor({\n messenger,\n isEnabled = () => true,\n trackEvent,\n }: {\n messenger: DeFiPositionsControllerMessenger;\n isEnabled?: () => boolean;\n trackEvent?: TrackEventHook;\n }) {\n super({\n name: controllerName,\n metadata: controllerMetadata,\n messenger,\n state: getDefaultDefiPositionsControllerState(),\n });\n\n this.setIntervalLength(TEN_MINUTES_IN_MS);\n\n this.#fetchPositions = buildPositionFetcher();\n this.#isEnabled = isEnabled;\n\n this.messagingSystem.subscribe('KeyringController:unlock', () => {\n this.startPolling(null);\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.stopAllPolling();\n });\n\n this.messagingSystem.subscribe(\n 'TransactionController:transactionConfirmed',\n async (transactionMeta) => {\n if (!this.#isEnabled()) {\n return;\n }\n\n await this.#updateAccountPositions(transactionMeta.txParams.from);\n },\n );\n\n this.messagingSystem.subscribe(\n 'AccountsController:accountAdded',\n async (account) => {\n if (!this.#isEnabled() || !account.type.startsWith('eip155:')) {\n return;\n }\n\n await this.#updateAccountPositions(account.address);\n },\n );\n\n this.#trackEvent = trackEvent;\n }\n\n async _executePoll(): Promise<void> {\n if (!this.#isEnabled()) {\n return;\n }\n\n const accounts = this.messagingSystem.call(\n 'AccountsController:listAccounts',\n );\n\n const initialResult: {\n accountAddress: string;\n positions: GroupedDeFiPositionsPerChain | null;\n }[] = [];\n\n const results = await reduceInBatchesSerially({\n initialResult,\n values: accounts,\n batchSize: FETCH_POSITIONS_BATCH_SIZE,\n eachBatch: async (workingResult, batch) => {\n const batchResults = (\n await Promise.all(\n batch.map(async ({ address: accountAddress, type }) => {\n if (type.startsWith('eip155:')) {\n const positions =\n await this.#fetchAccountPositions(accountAddress);\n\n return {\n accountAddress,\n positions,\n };\n }\n\n return undefined;\n }),\n )\n ).filter(Boolean) as {\n accountAddress: string;\n positions: GroupedDeFiPositionsPerChain | null;\n }[];\n\n return [...workingResult, ...batchResults];\n },\n });\n\n const allDefiPositions = results.reduce(\n (acc, { accountAddress, positions }) => {\n acc[accountAddress] = positions;\n return acc;\n },\n {} as DeFiPositionsControllerState['allDeFiPositions'],\n );\n\n this.update((state) => {\n state.allDeFiPositions = allDefiPositions;\n });\n }\n\n async #updateAccountPositions(accountAddress: string): Promise<void> {\n const accountPositionsPerChain =\n await this.#fetchAccountPositions(accountAddress);\n\n this.update((state) => {\n state.allDeFiPositions[accountAddress] = accountPositionsPerChain;\n });\n }\n\n async #fetchAccountPositions(\n accountAddress: string,\n ): Promise<GroupedDeFiPositionsPerChain | null> {\n try {\n const defiPositionsResponse = await this.#fetchPositions(accountAddress);\n\n const groupedDeFiPositions = groupDeFiPositions(defiPositionsResponse);\n\n try {\n this.#updatePositionsCountMetrics(groupedDeFiPositions, accountAddress);\n } catch (error) {\n console.error(\n `Failed to update positions count for account ${accountAddress}:`,\n error,\n );\n }\n\n return groupedDeFiPositions;\n } catch {\n return null;\n }\n }\n\n #updatePositionsCountMetrics(\n groupedDeFiPositions: GroupedDeFiPositionsPerChain,\n accountAddress: string,\n ) {\n // If no track event passed then skip the metrics update\n if (!this.#trackEvent) {\n return;\n }\n\n const defiMetrics = calculateDeFiPositionMetrics(groupedDeFiPositions);\n const { totalPositions } = defiMetrics.properties;\n\n if (totalPositions !== this.state.allDeFiPositionsCount[accountAddress]) {\n this.update((state) => {\n state.allDeFiPositionsCount[accountAddress] = totalPositions;\n });\n\n this.#trackEvent?.(defiMetrics);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"DeFiPositionsController.cjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAYA,qEAA+E;AAI/E,yEAAwE;AAExE,2DAAyD;AACzD,qEAGgC;AAChC,kDAAwD;AAExD,MAAM,iBAAiB,GAAG,MAAO,CAAC;AAElC,MAAM,0BAA0B,GAAG,EAAE,CAAC;AAEtC,MAAM,cAAc,GAAG,yBAAyB,CAAC;AAuCjD,MAAM,kBAAkB,GAAgD;IACtE,gBAAgB,EAAE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,IAAI,EAA8B,oBAAoB,EAAE,cAAc,CAAC,CAAC;SACzE;QAAC,OAAO,KAAK,EAAE;YACd,OAAO,CAAC,KAAK,CACX,gDAAgD,cAAc,GAAG,EACjE,KAAK,CACN,CAAC;SACH;QAED,OAAO,oBAAoB,CAAC;KAC7B;IAAC,MAAM;QACN,OAAO,IAAI,CAAC;KACb;AACH,CAAC,uHAGC,oBAAkD,EAClD,cAAsB;IAEtB,wDAAwD;IACxD,IAAI,CAAC,uBAAA,IAAI,2CAAY,EAAE;QACrB,OAAO;KACR;IAED,MAAM,WAAW,GAAG,IAAA,qDAA4B,EAAC,oBAAoB,CAAC,CAAC;IACvE,MAAM,EAAE,cAAc,EAAE,GAAG,WAAW,CAAC,UAAU,CAAC;IAElD,IAAI,cAAc,KAAK,IAAI,CAAC,KAAK,CAAC,qBAAqB,CAAC,cAAc,CAAC,EAAE;QACvE,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YACpB,KAAK,CAAC,qBAAqB,CAAC,cAAc,CAAC,GAAG,cAAc,CAAC;QAC/D,CAAC,CAAC,CAAC;QAEH,uBAAA,IAAI,2CAAY,EAAE,KAAlB,IAAI,EAAe,WAAW,CAAC,CAAC;KACjC;AACH,CAAC","sourcesContent":["import type {\n AccountsControllerAccountAddedEvent,\n AccountsControllerListAccountsAction,\n} from '@metamask/accounts-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type { KeyringControllerUnlockEvent } from '@metamask/keyring-controller';\nimport type { KeyringControllerLockEvent } from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { TransactionControllerTransactionConfirmedEvent } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport { calculateDeFiPositionMetrics } from './calculate-defi-metrics';\nimport type { DefiPositionResponse } from './fetch-positions';\nimport { buildPositionFetcher } from './fetch-positions';\nimport {\n groupDeFiPositions,\n type GroupedDeFiPositions,\n} from './group-defi-positions';\nimport { reduceInBatchesSerially } from '../assetsUtil';\n\nconst TEN_MINUTES_IN_MS = 600_000;\n\nconst FETCH_POSITIONS_BATCH_SIZE = 10;\n\nconst controllerName = 'DeFiPositionsController';\n\nexport type GroupedDeFiPositionsPerChain = {\n [chain: Hex]: GroupedDeFiPositions;\n};\n\nexport type TrackingEventPayload = {\n event: string;\n category: string;\n properties: {\n totalPositions: number;\n totalMarketValueUSD: number;\n breakdown?: {\n protocolId: string;\n marketValueUSD: number;\n chainId: Hex;\n count: number;\n }[];\n };\n};\n\ntype TrackEventHook = (event: TrackingEventPayload) => void;\n\nexport type DeFiPositionsControllerState = {\n /**\n * Object containing DeFi positions per account and network\n */\n allDeFiPositions: {\n [accountAddress: string]: GroupedDeFiPositionsPerChain | null;\n };\n\n /**\n * Object containing DeFi positions count per account\n */\n allDeFiPositionsCount: {\n [accountAddress: string]: number;\n };\n};\n\nconst controllerMetadata: StateMetadata<DeFiPositionsControllerState> = {\n allDeFiPositions: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n allDeFiPositionsCount: {\n includeInStateLogs: false,\n persist: false,\n includeInDebugSnapshot: false,\n usedInUi: false,\n },\n};\n\nexport const getDefaultDefiPositionsControllerState =\n (): DeFiPositionsControllerState => {\n return {\n allDeFiPositions: {},\n allDeFiPositionsCount: {},\n };\n };\n\nexport type DeFiPositionsControllerActions =\n DeFiPositionsControllerGetStateAction;\n\nexport type DeFiPositionsControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n DeFiPositionsControllerState\n>;\n\nexport type DeFiPositionsControllerEvents =\n DeFiPositionsControllerStateChangeEvent;\n\nexport type DeFiPositionsControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n DeFiPositionsControllerState\n >;\n\n/**\n * The external actions available to the {@link DeFiPositionsController}.\n */\nexport type AllowedActions = AccountsControllerListAccountsAction;\n\n/**\n * The external events available to the {@link DeFiPositionsController}.\n */\nexport type AllowedEvents =\n | KeyringControllerUnlockEvent\n | KeyringControllerLockEvent\n | TransactionControllerTransactionConfirmedEvent\n | AccountsControllerAccountAddedEvent;\n\n/**\n * The messenger of the {@link DeFiPositionsController}.\n */\nexport type DeFiPositionsControllerMessenger = Messenger<\n typeof controllerName,\n DeFiPositionsControllerActions | AllowedActions,\n DeFiPositionsControllerEvents | AllowedEvents\n>;\n\n/**\n * Controller that stores assets and exposes convenience methods\n */\nexport class DeFiPositionsController extends StaticIntervalPollingController()<\n typeof controllerName,\n DeFiPositionsControllerState,\n DeFiPositionsControllerMessenger\n> {\n readonly #fetchPositions: (\n accountAddress: string,\n ) => Promise<DefiPositionResponse[]>;\n\n readonly #isEnabled: () => boolean;\n\n readonly #trackEvent?: TrackEventHook;\n\n /**\n * DeFiPositionsController constuctor\n *\n * @param options - Constructor options.\n * @param options.messenger - The controller messenger.\n * @param options.isEnabled - Function that returns whether the controller is enabled. (default: () => true)\n * @param options.trackEvent - Function to track events. (default: undefined)\n */\n constructor({\n messenger,\n isEnabled = () => true,\n trackEvent,\n }: {\n messenger: DeFiPositionsControllerMessenger;\n isEnabled?: () => boolean;\n trackEvent?: TrackEventHook;\n }) {\n super({\n name: controllerName,\n metadata: controllerMetadata,\n messenger,\n state: getDefaultDefiPositionsControllerState(),\n });\n\n this.setIntervalLength(TEN_MINUTES_IN_MS);\n\n this.#fetchPositions = buildPositionFetcher();\n this.#isEnabled = isEnabled;\n\n this.messenger.subscribe('KeyringController:unlock', () => {\n this.startPolling(null);\n });\n\n this.messenger.subscribe('KeyringController:lock', () => {\n this.stopAllPolling();\n });\n\n this.messenger.subscribe(\n 'TransactionController:transactionConfirmed',\n async (transactionMeta) => {\n if (!this.#isEnabled()) {\n return;\n }\n\n await this.#updateAccountPositions(transactionMeta.txParams.from);\n },\n );\n\n this.messenger.subscribe(\n 'AccountsController:accountAdded',\n async (account) => {\n if (!this.#isEnabled() || !account.type.startsWith('eip155:')) {\n return;\n }\n\n await this.#updateAccountPositions(account.address);\n },\n );\n\n this.#trackEvent = trackEvent;\n }\n\n async _executePoll(): Promise<void> {\n if (!this.#isEnabled()) {\n return;\n }\n\n const accounts = this.messenger.call('AccountsController:listAccounts');\n\n const initialResult: {\n accountAddress: string;\n positions: GroupedDeFiPositionsPerChain | null;\n }[] = [];\n\n const results = await reduceInBatchesSerially({\n initialResult,\n values: accounts,\n batchSize: FETCH_POSITIONS_BATCH_SIZE,\n eachBatch: async (workingResult, batch) => {\n const batchResults = (\n await Promise.all(\n batch.map(async ({ address: accountAddress, type }) => {\n if (type.startsWith('eip155:')) {\n const positions =\n await this.#fetchAccountPositions(accountAddress);\n\n return {\n accountAddress,\n positions,\n };\n }\n\n return undefined;\n }),\n )\n ).filter(Boolean) as {\n accountAddress: string;\n positions: GroupedDeFiPositionsPerChain | null;\n }[];\n\n return [...workingResult, ...batchResults];\n },\n });\n\n const allDefiPositions = results.reduce(\n (acc, { accountAddress, positions }) => {\n acc[accountAddress] = positions;\n return acc;\n },\n {} as DeFiPositionsControllerState['allDeFiPositions'],\n );\n\n this.update((state) => {\n state.allDeFiPositions = allDefiPositions;\n });\n }\n\n async #updateAccountPositions(accountAddress: string): Promise<void> {\n const accountPositionsPerChain =\n await this.#fetchAccountPositions(accountAddress);\n\n this.update((state) => {\n state.allDeFiPositions[accountAddress] = accountPositionsPerChain;\n });\n }\n\n async #fetchAccountPositions(\n accountAddress: string,\n ): Promise<GroupedDeFiPositionsPerChain | null> {\n try {\n const defiPositionsResponse = await this.#fetchPositions(accountAddress);\n\n const groupedDeFiPositions = groupDeFiPositions(defiPositionsResponse);\n\n try {\n this.#updatePositionsCountMetrics(groupedDeFiPositions, accountAddress);\n } catch (error) {\n console.error(\n `Failed to update positions count for account ${accountAddress}:`,\n error,\n );\n }\n\n return groupedDeFiPositions;\n } catch {\n return null;\n }\n }\n\n #updatePositionsCountMetrics(\n groupedDeFiPositions: GroupedDeFiPositionsPerChain,\n accountAddress: string,\n ) {\n // If no track event passed then skip the metrics update\n if (!this.#trackEvent) {\n return;\n }\n\n const defiMetrics = calculateDeFiPositionMetrics(groupedDeFiPositions);\n const { totalPositions } = defiMetrics.properties;\n\n if (totalPositions !== this.state.allDeFiPositionsCount[accountAddress]) {\n this.update((state) => {\n state.allDeFiPositionsCount[accountAddress] = totalPositions;\n });\n\n this.#trackEvent?.(defiMetrics);\n }\n }\n}\n"]}
@@ -1,8 +1,9 @@
1
1
  /// <reference types="node" />
2
2
  import type { AccountsControllerAccountAddedEvent, AccountsControllerListAccountsAction } from "@metamask/accounts-controller";
3
- import type { ControllerGetStateAction, ControllerStateChangeEvent, RestrictedMessenger } from "@metamask/base-controller";
3
+ import type { ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
4
4
  import type { KeyringControllerUnlockEvent } from "@metamask/keyring-controller";
5
5
  import type { KeyringControllerLockEvent } from "@metamask/keyring-controller";
6
+ import type { Messenger } from "@metamask/messenger";
6
7
  import type { TransactionControllerTransactionConfirmedEvent } from "@metamask/transaction-controller";
7
8
  import type { Hex } from "@metamask/utils";
8
9
  import { type GroupedDeFiPositions } from "./group-defi-positions.cjs";
@@ -55,7 +56,7 @@ export type AllowedEvents = KeyringControllerUnlockEvent | KeyringControllerLock
55
56
  /**
56
57
  * The messenger of the {@link DeFiPositionsController}.
57
58
  */
58
- export type DeFiPositionsControllerMessenger = RestrictedMessenger<typeof controllerName, DeFiPositionsControllerActions | AllowedActions, DeFiPositionsControllerEvents | AllowedEvents, AllowedActions['type'], AllowedEvents['type']>;
59
+ export type DeFiPositionsControllerMessenger = Messenger<typeof controllerName, DeFiPositionsControllerActions | AllowedActions, DeFiPositionsControllerEvents | AllowedEvents>;
59
60
  declare const DeFiPositionsController_base: (abstract new (...args: any[]) => {
60
61
  readonly "__#14@#intervalIds": Record<string, NodeJS.Timeout>;
61
62
  "__#14@#intervalLength": number | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"DeFiPositionsController.d.cts","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsController.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EACV,mCAAmC,EACnC,oCAAoC,EACrC,sCAAsC;AACvC,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,mBAAmB,EAEpB,kCAAkC;AACnC,OAAO,KAAK,EAAE,4BAA4B,EAAE,qCAAqC;AACjF,OAAO,KAAK,EAAE,0BAA0B,EAAE,qCAAqC;AAE/E,OAAO,KAAK,EAAE,8CAA8C,EAAE,yCAAyC;AACvG,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAK3C,OAAO,EAEL,KAAK,oBAAoB,EAC1B,mCAA+B;AAOhC,QAAA,MAAM,cAAc,4BAA4B,CAAC;AAEjD,MAAM,MAAM,4BAA4B,GAAG;IACzC,CAAC,KAAK,EAAE,GAAG,GAAG,oBAAoB,CAAC;CACpC,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE;QACV,cAAc,EAAE,MAAM,CAAC;QACvB,mBAAmB,EAAE,MAAM,CAAC;QAC5B,SAAS,CAAC,EAAE;YACV,UAAU,EAAE,MAAM,CAAC;YACnB,cAAc,EAAE,MAAM,CAAC;YACvB,OAAO,EAAE,GAAG,CAAC;YACb,KAAK,EAAE,MAAM,CAAC;SACf,EAAE,CAAC;KACL,CAAC;CACH,CAAC;AAEF,KAAK,cAAc,GAAG,CAAC,KAAK,EAAE,oBAAoB,KAAK,IAAI,CAAC;AAE5D,MAAM,MAAM,4BAA4B,GAAG;IACzC;;OAEG;IACH,gBAAgB,EAAE;QAChB,CAAC,cAAc,EAAE,MAAM,GAAG,4BAA4B,GAAG,IAAI,CAAC;KAC/D,CAAC;IAEF;;OAEG;IACH,qBAAqB,EAAE;QACrB,CAAC,cAAc,EAAE,MAAM,GAAG,MAAM,CAAC;KAClC,CAAC;CACH,CAAC;AAiBF,eAAO,MAAM,sCAAsC,QAC7C,4BAKH,CAAC;AAEJ,MAAM,MAAM,8BAA8B,GACxC,qCAAqC,CAAC;AAExC,MAAM,MAAM,qCAAqC,GAAG,wBAAwB,CAC1E,OAAO,cAAc,EACrB,4BAA4B,CAC7B,CAAC;AAEF,MAAM,MAAM,6BAA6B,GACvC,uCAAuC,CAAC;AAE1C,MAAM,MAAM,uCAAuC,GACjD,0BAA0B,CACxB,OAAO,cAAc,EACrB,4BAA4B,CAC7B,CAAC;AAEJ;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG,oCAAoC,CAAC;AAElE;;GAEG;AACH,MAAM,MAAM,aAAa,GACrB,4BAA4B,GAC5B,0BAA0B,GAC1B,8CAA8C,GAC9C,mCAAmC,CAAC;AAExC;;GAEG;AACH,MAAM,MAAM,gCAAgC,GAAG,mBAAmB,CAChE,OAAO,cAAc,EACrB,8BAA8B,GAAG,cAAc,EAC/C,6BAA6B,GAAG,aAAa,EAC7C,cAAc,CAAC,MAAM,CAAC,EACtB,aAAa,CAAC,MAAM,CAAC,CACtB,CAAC;;;;;;;;;;;;;;;;AAEF;;GAEG;AACH,qBAAa,uBAAwB,SAAQ,6BAC3C,OAAO,cAAc,EACrB,4BAA4B,EAC5B,gCAAgC,CACjC;;IASC;;;;;;;OAOG;gBACS,EACV,SAAS,EACT,SAAsB,EACtB,UAAU,GACX,EAAE;QACD,SAAS,EAAE,gCAAgC,CAAC;QAC5C,SAAS,CAAC,EAAE,MAAM,OAAO,CAAC;QAC1B,UAAU,CAAC,EAAE,cAAc,CAAC;KAC7B;IA8CK,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;CA6GpC"}
1
+ {"version":3,"file":"DeFiPositionsController.d.cts","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsController.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EACV,mCAAmC,EACnC,oCAAoC,EACrC,sCAAsC;AACvC,O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C;AAExC,MAAM,MAAM,qCAAqC,GAAG,wBAAwB,CAC1E,OAAO,cAAc,EACrB,4BAA4B,CAC7B,CAAC;AAEF,MAAM,MAAM,6BAA6B,GACvC,uCAAuC,CAAC;AAE1C,MAAM,MAAM,uCAAuC,GACjD,0BAA0B,CACxB,OAAO,cAAc,EACrB,4BAA4B,CAC7B,CAAC;AAEJ;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG,oCAAoC,CAAC;AAElE;;GAEG;AACH,MAAM,MAAM,aAAa,GACrB,4BAA4B,GAC5B,0BAA0B,GAC1B,8CAA8C,GAC9C,mCAAmC,CAAC;AAExC;;GAEG;AACH,MAAM,MAAM,gCAAgC,GAAG,SAAS,CACtD,OAAO,cAAc,EACrB,8BAA8B,GAAG,cAAc,EAC/C,6BAA6B,GAAG,aAAa,CAC9C,CAAC;;;;;;;;;;;;;;;;AAEF;;GAEG;AACH,qBAAa,uBAAwB,SAAQ,6BAC3C,OAAO,cAAc,EACrB,4BAA4B,EAC5B,gCAAgC,CACjC;;IASC;;;;;;;OAOG;gBACS,EACV,SAAS,EACT,SAAsB,EACtB,UAAU,GACX,EAAE;QACD,SAAS,EAAE,gCAAgC,CAAC;QAC5C,SAAS,CAAC,EAAE,MAAM,OAAO,CAAC;QAC1B,UAAU,CAAC,EAAE,cAAc,CAAC;KAC7B;IA8CK,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;CA2GpC"}
@@ -1,8 +1,9 @@
1
1
  /// <reference types="node" />
2
2
  import type { AccountsControllerAccountAddedEvent, AccountsControllerListAccountsAction } from "@metamask/accounts-controller";
3
- import type { ControllerGetStateAction, ControllerStateChangeEvent, RestrictedMessenger } from "@metamask/base-controller";
3
+ import type { ControllerGetStateAction, ControllerStateChangeEvent } from "@metamask/base-controller";
4
4
  import type { KeyringControllerUnlockEvent } from "@metamask/keyring-controller";
5
5
  import type { KeyringControllerLockEvent } from "@metamask/keyring-controller";
6
+ import type { Messenger } from "@metamask/messenger";
6
7
  import type { TransactionControllerTransactionConfirmedEvent } from "@metamask/transaction-controller";
7
8
  import type { Hex } from "@metamask/utils";
8
9
  import { type GroupedDeFiPositions } from "./group-defi-positions.mjs";
@@ -55,7 +56,7 @@ export type AllowedEvents = KeyringControllerUnlockEvent | KeyringControllerLock
55
56
  /**
56
57
  * The messenger of the {@link DeFiPositionsController}.
57
58
  */
58
- export type DeFiPositionsControllerMessenger = RestrictedMessenger<typeof controllerName, DeFiPositionsControllerActions | AllowedActions, DeFiPositionsControllerEvents | AllowedEvents, AllowedActions['type'], AllowedEvents['type']>;
59
+ export type DeFiPositionsControllerMessenger = Messenger<typeof controllerName, DeFiPositionsControllerActions | AllowedActions, DeFiPositionsControllerEvents | AllowedEvents>;
59
60
  declare const DeFiPositionsController_base: (abstract new (...args: any[]) => {
60
61
  readonly "__#14@#intervalIds": Record<string, NodeJS.Timeout>;
61
62
  "__#14@#intervalLength": number | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"DeFiPositionsController.d.mts","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsController.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EACV,mCAAmC,EACnC,oCAAoC,EACrC,sCAAsC;AACvC,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAC1B,mBAAmB,EAEpB,kCAAkC;AACnC,OAAO,KAAK,EAAE,4BAA4B,EAAE,qCAAqC;AACjF,OAAO,KAAK,EAAE,0BAA0B,EAAE,qCAAqC;AAE/E,OAAO,KAAK,EAAE,8CAA8C,EAAE,yCAAyC;AACvG,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAK3C,OAAO,EAEL,KAAK,oBAAoB,EAC1B,mCAA+B;AAOhC,QAAA,MAAM,cAAc,4BAA4B,CAAC;AAEjD,MAAM,MAAM,4BAA4B,GAAG;IACzC,CAAC,KAAK,EAAE,GAAG,GAAG,oBAAoB,CAAC;CACpC,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC,KAAK,E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C,cAAc,CAAC,MAAM,CAAC,EACtB,aAAa,CAAC,MAAM,CAAC,CACtB,CAAC;;;;;;;;;;;;;;;;AAEF;;GAEG;AACH,qBAAa,uBAAwB,SAAQ,6BAC3C,OAAO,cAAc,EACrB,4BAA4B,EAC5B,gCAAgC,CACjC;;IASC;;;;;;;OAOG;gBACS,EACV,SAAS,EACT,SAAsB,EACtB,UAAU,GACX,EAAE;QACD,SAAS,EAAE,gCAAgC,CAAC;QAC5C,SAAS,CAAC,EAAE,MAAM,OAAO,CAAC;QAC1B,UAAU,CAAC,EAAE,cAAc,CAAC;KAC7B;IA8CK,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;CA6GpC"}
1
+ {"version":3,"file":"DeFiPositionsController.d.mts","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsController.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EACV,mCAAmC,EACnC,oCAAoC,EACrC,sCAAsC;AACvC,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AACnC,OAAO,KAAK,EAAE,4BAA4B,EAAE,qCAAqC;AACjF,OAAO,KAAK,EAAE,0BAA0B,EAAE,qCAAqC;AAC/E,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAErD,OAAO,KAAK,EAAE,8CAA8C,EAAE,yCAAyC;AACvG,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAK3C,OAAO,EAEL,KAAK,oBAAoB,EAC1B,mCAA+B;AAOhC,QAAA,MAAM,cAAc,4BAA4B,CAAC;AAEjD,MAAM,MAAM,4BAA4B,GAAG;IACzC,CAAC,KAAK,EAAE,GAAG,GAAG,oBAAoB,CAAC;CACpC,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE;QACV,cAAc,EAAE,MAAM,CAAC;QACvB,mBAAmB,EAAE,MAAM,CA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IASC;;;;;;;OAOG;gBACS,EACV,SAAS,EACT,SAAsB,EACtB,UAAU,GACX,EAAE;QACD,SAAS,EAAE,gCAAgC,CAAC;QAC5C,SAAS,CAAC,EAAE,MAAM,OAAO,CAAC;QAC1B,UAAU,CAAC,EAAE,cAAc,CAAC;KAC7B;IA8CK,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;CA2GpC"}
@@ -22,13 +22,13 @@ const controllerMetadata = {
22
22
  allDeFiPositions: {
23
23
  includeInStateLogs: false,
24
24
  persist: false,
25
- anonymous: false,
25
+ includeInDebugSnapshot: false,
26
26
  usedInUi: true,
27
27
  },
28
28
  allDeFiPositionsCount: {
29
29
  includeInStateLogs: false,
30
30
  persist: false,
31
- anonymous: false,
31
+ includeInDebugSnapshot: false,
32
32
  usedInUi: false,
33
33
  },
34
34
  };
@@ -64,19 +64,19 @@ export class DeFiPositionsController extends StaticIntervalPollingController() {
64
64
  this.setIntervalLength(TEN_MINUTES_IN_MS);
65
65
  __classPrivateFieldSet(this, _DeFiPositionsController_fetchPositions, buildPositionFetcher(), "f");
66
66
  __classPrivateFieldSet(this, _DeFiPositionsController_isEnabled, isEnabled, "f");
67
- this.messagingSystem.subscribe('KeyringController:unlock', () => {
67
+ this.messenger.subscribe('KeyringController:unlock', () => {
68
68
  this.startPolling(null);
69
69
  });
70
- this.messagingSystem.subscribe('KeyringController:lock', () => {
70
+ this.messenger.subscribe('KeyringController:lock', () => {
71
71
  this.stopAllPolling();
72
72
  });
73
- this.messagingSystem.subscribe('TransactionController:transactionConfirmed', async (transactionMeta) => {
73
+ this.messenger.subscribe('TransactionController:transactionConfirmed', async (transactionMeta) => {
74
74
  if (!__classPrivateFieldGet(this, _DeFiPositionsController_isEnabled, "f").call(this)) {
75
75
  return;
76
76
  }
77
77
  await __classPrivateFieldGet(this, _DeFiPositionsController_instances, "m", _DeFiPositionsController_updateAccountPositions).call(this, transactionMeta.txParams.from);
78
78
  });
79
- this.messagingSystem.subscribe('AccountsController:accountAdded', async (account) => {
79
+ this.messenger.subscribe('AccountsController:accountAdded', async (account) => {
80
80
  if (!__classPrivateFieldGet(this, _DeFiPositionsController_isEnabled, "f").call(this) || !account.type.startsWith('eip155:')) {
81
81
  return;
82
82
  }
@@ -88,7 +88,7 @@ export class DeFiPositionsController extends StaticIntervalPollingController() {
88
88
  if (!__classPrivateFieldGet(this, _DeFiPositionsController_isEnabled, "f").call(this)) {
89
89
  return;
90
90
  }
91
- const accounts = this.messagingSystem.call('AccountsController:listAccounts');
91
+ const accounts = this.messenger.call('AccountsController:listAccounts');
92
92
  const initialResult = [];
93
93
  const results = await reduceInBatchesSerially({
94
94
  initialResult,