@metamask/assets-controllers 110.0.0 → 110.0.1

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 (275) hide show
  1. package/CHANGELOG.md +15 -1
  2. package/dist/AccountTrackerController-method-action-types.cjs.map +1 -1
  3. package/dist/AccountTrackerController-method-action-types.d.cts.map +1 -1
  4. package/dist/AccountTrackerController-method-action-types.d.mts.map +1 -1
  5. package/dist/AccountTrackerController-method-action-types.mjs.map +1 -1
  6. package/dist/AccountTrackerController.cjs +8 -8
  7. package/dist/AccountTrackerController.cjs.map +1 -1
  8. package/dist/AccountTrackerController.d.cts.map +1 -1
  9. package/dist/AccountTrackerController.d.mts.map +1 -1
  10. package/dist/AccountTrackerController.mjs.map +1 -1
  11. package/dist/AssetsContractController-method-action-types.cjs.map +1 -1
  12. package/dist/AssetsContractController-method-action-types.d.cts.map +1 -1
  13. package/dist/AssetsContractController-method-action-types.d.mts.map +1 -1
  14. package/dist/AssetsContractController-method-action-types.mjs.map +1 -1
  15. package/dist/AssetsContractController.cjs +33 -33
  16. package/dist/AssetsContractController.cjs.map +1 -1
  17. package/dist/AssetsContractController.d.cts.map +1 -1
  18. package/dist/AssetsContractController.d.mts.map +1 -1
  19. package/dist/AssetsContractController.mjs.map +1 -1
  20. package/dist/CurrencyRateController-method-action-types.cjs.map +1 -1
  21. package/dist/CurrencyRateController-method-action-types.d.cts.map +1 -1
  22. package/dist/CurrencyRateController-method-action-types.d.mts.map +1 -1
  23. package/dist/CurrencyRateController-method-action-types.mjs.map +1 -1
  24. package/dist/CurrencyRateController.cjs +2 -2
  25. package/dist/CurrencyRateController.cjs.map +1 -1
  26. package/dist/CurrencyRateController.d.cts.map +1 -1
  27. package/dist/CurrencyRateController.d.mts.map +1 -1
  28. package/dist/CurrencyRateController.mjs.map +1 -1
  29. package/dist/DeFiPositionsController/DeFiPositionsController.cjs +6 -6
  30. package/dist/DeFiPositionsController/DeFiPositionsController.cjs.map +1 -1
  31. package/dist/DeFiPositionsController/DeFiPositionsController.d.cts.map +1 -1
  32. package/dist/DeFiPositionsController/DeFiPositionsController.d.mts.map +1 -1
  33. package/dist/DeFiPositionsController/DeFiPositionsController.mjs.map +1 -1
  34. package/dist/DeFiPositionsController/DeFiPositionsControllerV2-method-action-types.cjs.map +1 -1
  35. package/dist/DeFiPositionsController/DeFiPositionsControllerV2-method-action-types.d.cts.map +1 -1
  36. package/dist/DeFiPositionsController/DeFiPositionsControllerV2-method-action-types.d.mts.map +1 -1
  37. package/dist/DeFiPositionsController/DeFiPositionsControllerV2-method-action-types.mjs.map +1 -1
  38. package/dist/DeFiPositionsController/DeFiPositionsControllerV2.cjs +4 -4
  39. package/dist/DeFiPositionsController/DeFiPositionsControllerV2.cjs.map +1 -1
  40. package/dist/DeFiPositionsController/DeFiPositionsControllerV2.d.cts.map +1 -1
  41. package/dist/DeFiPositionsController/DeFiPositionsControllerV2.d.mts.map +1 -1
  42. package/dist/DeFiPositionsController/DeFiPositionsControllerV2.mjs.map +1 -1
  43. package/dist/DeFiPositionsController/calculate-defi-metrics.cjs.map +1 -1
  44. package/dist/DeFiPositionsController/calculate-defi-metrics.d.cts.map +1 -1
  45. package/dist/DeFiPositionsController/calculate-defi-metrics.d.mts.map +1 -1
  46. package/dist/DeFiPositionsController/calculate-defi-metrics.mjs.map +1 -1
  47. package/dist/DeFiPositionsController/fetch-positions.cjs +2 -2
  48. package/dist/DeFiPositionsController/fetch-positions.cjs.map +1 -1
  49. package/dist/DeFiPositionsController/fetch-positions.mjs.map +1 -1
  50. package/dist/DeFiPositionsController/group-defi-positions-v6.cjs +1 -1
  51. package/dist/DeFiPositionsController/group-defi-positions-v6.cjs.map +1 -1
  52. package/dist/DeFiPositionsController/group-defi-positions-v6.d.cts +1 -1
  53. package/dist/DeFiPositionsController/group-defi-positions-v6.d.cts.map +1 -1
  54. package/dist/DeFiPositionsController/group-defi-positions-v6.d.mts +1 -1
  55. package/dist/DeFiPositionsController/group-defi-positions-v6.d.mts.map +1 -1
  56. package/dist/DeFiPositionsController/group-defi-positions-v6.mjs +1 -1
  57. package/dist/DeFiPositionsController/group-defi-positions-v6.mjs.map +1 -1
  58. package/dist/DeFiPositionsController/group-defi-positions.cjs.map +1 -1
  59. package/dist/DeFiPositionsController/group-defi-positions.d.cts.map +1 -1
  60. package/dist/DeFiPositionsController/group-defi-positions.d.mts.map +1 -1
  61. package/dist/DeFiPositionsController/group-defi-positions.mjs.map +1 -1
  62. package/dist/DeFiPositionsController/merge-positions-for-accounts.cjs.map +1 -1
  63. package/dist/DeFiPositionsController/merge-positions-for-accounts.d.cts.map +1 -1
  64. package/dist/DeFiPositionsController/merge-positions-for-accounts.d.mts.map +1 -1
  65. package/dist/DeFiPositionsController/merge-positions-for-accounts.mjs.map +1 -1
  66. package/dist/MultichainAssetsController/MultichainAssetsController-method-action-types.cjs.map +1 -1
  67. package/dist/MultichainAssetsController/MultichainAssetsController-method-action-types.d.cts.map +1 -1
  68. package/dist/MultichainAssetsController/MultichainAssetsController-method-action-types.d.mts.map +1 -1
  69. package/dist/MultichainAssetsController/MultichainAssetsController-method-action-types.mjs.map +1 -1
  70. package/dist/MultichainAssetsController/MultichainAssetsController.cjs +2 -2
  71. package/dist/MultichainAssetsController/MultichainAssetsController.cjs.map +1 -1
  72. package/dist/MultichainAssetsController/MultichainAssetsController.d.cts.map +1 -1
  73. package/dist/MultichainAssetsController/MultichainAssetsController.d.mts.map +1 -1
  74. package/dist/MultichainAssetsController/MultichainAssetsController.mjs.map +1 -1
  75. package/dist/MultichainAssetsController/index.cjs +3 -3
  76. package/dist/MultichainAssetsController/index.cjs.map +1 -1
  77. package/dist/MultichainAssetsController/index.d.cts.map +1 -1
  78. package/dist/MultichainAssetsController/index.d.mts.map +1 -1
  79. package/dist/MultichainAssetsController/index.mjs.map +1 -1
  80. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController-method-action-types.cjs.map +1 -1
  81. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController-method-action-types.d.cts.map +1 -1
  82. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController-method-action-types.d.mts.map +1 -1
  83. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController-method-action-types.mjs.map +1 -1
  84. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.cjs +3 -3
  85. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.cjs.map +1 -1
  86. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.cts.map +1 -1
  87. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.mts.map +1 -1
  88. package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.mjs.map +1 -1
  89. package/dist/MultichainAssetsRatesController/index.cjs +5 -5
  90. package/dist/MultichainAssetsRatesController/index.cjs.map +1 -1
  91. package/dist/MultichainAssetsRatesController/index.d.cts.map +1 -1
  92. package/dist/MultichainAssetsRatesController/index.d.mts.map +1 -1
  93. package/dist/MultichainAssetsRatesController/index.mjs.map +1 -1
  94. package/dist/MultichainBalancesController/MultichainBalancesController.cjs.map +1 -1
  95. package/dist/MultichainBalancesController/MultichainBalancesController.d.cts.map +1 -1
  96. package/dist/MultichainBalancesController/MultichainBalancesController.d.mts.map +1 -1
  97. package/dist/MultichainBalancesController/MultichainBalancesController.mjs.map +1 -1
  98. package/dist/MultichainBalancesController/index.cjs +2 -2
  99. package/dist/MultichainBalancesController/index.cjs.map +1 -1
  100. package/dist/MultichainBalancesController/index.d.cts.map +1 -1
  101. package/dist/MultichainBalancesController/index.d.mts.map +1 -1
  102. package/dist/MultichainBalancesController/index.mjs.map +1 -1
  103. package/dist/NftController.cjs +14 -14
  104. package/dist/NftController.cjs.map +1 -1
  105. package/dist/NftController.d.cts.map +1 -1
  106. package/dist/NftController.d.mts.map +1 -1
  107. package/dist/NftController.mjs.map +1 -1
  108. package/dist/NftDetectionController.cjs +2 -2
  109. package/dist/NftDetectionController.cjs.map +1 -1
  110. package/dist/NftDetectionController.d.cts.map +1 -1
  111. package/dist/NftDetectionController.d.mts.map +1 -1
  112. package/dist/NftDetectionController.mjs.map +1 -1
  113. package/dist/RatesController/RatesController.cjs +2 -2
  114. package/dist/RatesController/RatesController.cjs.map +1 -1
  115. package/dist/RatesController/RatesController.d.cts.map +1 -1
  116. package/dist/RatesController/RatesController.d.mts.map +1 -1
  117. package/dist/RatesController/RatesController.mjs.map +1 -1
  118. package/dist/RatesController/index.cjs +3 -3
  119. package/dist/RatesController/index.cjs.map +1 -1
  120. package/dist/RatesController/index.d.cts.map +1 -1
  121. package/dist/RatesController/index.d.mts.map +1 -1
  122. package/dist/RatesController/index.mjs.map +1 -1
  123. package/dist/RatesController/types.cjs.map +1 -1
  124. package/dist/RatesController/types.d.cts.map +1 -1
  125. package/dist/RatesController/types.d.mts.map +1 -1
  126. package/dist/RatesController/types.mjs.map +1 -1
  127. package/dist/Standards/ERC20Standard.cjs +2 -2
  128. package/dist/Standards/ERC20Standard.cjs.map +1 -1
  129. package/dist/Standards/ERC20Standard.mjs.map +1 -1
  130. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.cjs +4 -4
  131. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.cjs.map +1 -1
  132. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.d.cts.map +1 -1
  133. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.d.mts.map +1 -1
  134. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.mjs.map +1 -1
  135. package/dist/Standards/NftStandards/ERC721/ERC721Standard.cjs +3 -3
  136. package/dist/Standards/NftStandards/ERC721/ERC721Standard.cjs.map +1 -1
  137. package/dist/Standards/NftStandards/ERC721/ERC721Standard.mjs.map +1 -1
  138. package/dist/TokenBalancesController-method-action-types.cjs.map +1 -1
  139. package/dist/TokenBalancesController-method-action-types.d.cts.map +1 -1
  140. package/dist/TokenBalancesController-method-action-types.d.mts.map +1 -1
  141. package/dist/TokenBalancesController-method-action-types.mjs.map +1 -1
  142. package/dist/TokenBalancesController.cjs +12 -12
  143. package/dist/TokenBalancesController.cjs.map +1 -1
  144. package/dist/TokenBalancesController.d.cts +1 -1
  145. package/dist/TokenBalancesController.d.cts.map +1 -1
  146. package/dist/TokenBalancesController.d.mts +1 -1
  147. package/dist/TokenBalancesController.d.mts.map +1 -1
  148. package/dist/TokenBalancesController.mjs.map +1 -1
  149. package/dist/TokenDetectionController-method-action-types.cjs.map +1 -1
  150. package/dist/TokenDetectionController-method-action-types.d.cts.map +1 -1
  151. package/dist/TokenDetectionController-method-action-types.d.mts.map +1 -1
  152. package/dist/TokenDetectionController-method-action-types.mjs.map +1 -1
  153. package/dist/TokenDetectionController.cjs +17 -17
  154. package/dist/TokenDetectionController.cjs.map +1 -1
  155. package/dist/TokenDetectionController.d.cts +1 -1
  156. package/dist/TokenDetectionController.d.cts.map +1 -1
  157. package/dist/TokenDetectionController.d.mts +1 -1
  158. package/dist/TokenDetectionController.d.mts.map +1 -1
  159. package/dist/TokenDetectionController.mjs.map +1 -1
  160. package/dist/TokenListController.cjs +6 -6
  161. package/dist/TokenListController.cjs.map +1 -1
  162. package/dist/TokenListController.d.cts.map +1 -1
  163. package/dist/TokenListController.d.mts.map +1 -1
  164. package/dist/TokenListController.mjs.map +1 -1
  165. package/dist/TokenListService.cjs +5 -5
  166. package/dist/TokenListService.cjs.map +1 -1
  167. package/dist/TokenListService.d.cts.map +1 -1
  168. package/dist/TokenListService.d.mts.map +1 -1
  169. package/dist/TokenListService.mjs.map +1 -1
  170. package/dist/TokenRatesController.cjs +6 -6
  171. package/dist/TokenRatesController.cjs.map +1 -1
  172. package/dist/TokenRatesController.d.cts.map +1 -1
  173. package/dist/TokenRatesController.d.mts.map +1 -1
  174. package/dist/TokenRatesController.mjs.map +1 -1
  175. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.cjs +5 -5
  176. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.cjs.map +1 -1
  177. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.cts.map +1 -1
  178. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.mts.map +1 -1
  179. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.mjs.map +1 -1
  180. package/dist/TokenSearchDiscoveryDataController/index.cjs.map +1 -1
  181. package/dist/TokenSearchDiscoveryDataController/index.d.cts.map +1 -1
  182. package/dist/TokenSearchDiscoveryDataController/index.d.mts.map +1 -1
  183. package/dist/TokenSearchDiscoveryDataController/index.mjs.map +1 -1
  184. package/dist/TokenSearchDiscoveryDataController/types.cjs.map +1 -1
  185. package/dist/TokenSearchDiscoveryDataController/types.d.cts.map +1 -1
  186. package/dist/TokenSearchDiscoveryDataController/types.d.mts.map +1 -1
  187. package/dist/TokenSearchDiscoveryDataController/types.mjs.map +1 -1
  188. package/dist/TokensController-method-action-types.cjs.map +1 -1
  189. package/dist/TokensController-method-action-types.d.cts.map +1 -1
  190. package/dist/TokensController-method-action-types.d.mts.map +1 -1
  191. package/dist/TokensController-method-action-types.mjs.map +1 -1
  192. package/dist/TokensController.cjs +10 -10
  193. package/dist/TokensController.cjs.map +1 -1
  194. package/dist/TokensController.d.cts.map +1 -1
  195. package/dist/TokensController.d.mts.map +1 -1
  196. package/dist/TokensController.mjs.map +1 -1
  197. package/dist/assetsUtil.cjs +2 -2
  198. package/dist/assetsUtil.cjs.map +1 -1
  199. package/dist/assetsUtil.d.cts.map +1 -1
  200. package/dist/assetsUtil.d.mts.map +1 -1
  201. package/dist/assetsUtil.mjs.map +1 -1
  202. package/dist/balances.cjs +4 -4
  203. package/dist/balances.cjs.map +1 -1
  204. package/dist/balances.d.cts.map +1 -1
  205. package/dist/balances.d.mts.map +1 -1
  206. package/dist/balances.mjs.map +1 -1
  207. package/dist/crypto-compare-service/crypto-compare.cjs +2 -2
  208. package/dist/crypto-compare-service/crypto-compare.cjs.map +1 -1
  209. package/dist/crypto-compare-service/crypto-compare.mjs.map +1 -1
  210. package/dist/crypto-compare-service/index.cjs +3 -3
  211. package/dist/crypto-compare-service/index.cjs.map +1 -1
  212. package/dist/crypto-compare-service/index.d.cts.map +1 -1
  213. package/dist/crypto-compare-service/index.d.mts.map +1 -1
  214. package/dist/crypto-compare-service/index.mjs.map +1 -1
  215. package/dist/index.cjs +76 -76
  216. package/dist/index.cjs.map +1 -1
  217. package/dist/index.d.cts +1 -1
  218. package/dist/index.d.cts.map +1 -1
  219. package/dist/index.d.mts +1 -1
  220. package/dist/index.d.mts.map +1 -1
  221. package/dist/index.mjs.map +1 -1
  222. package/dist/multi-chain-accounts-service/api-balance-fetcher.cjs +13 -13
  223. package/dist/multi-chain-accounts-service/api-balance-fetcher.cjs.map +1 -1
  224. package/dist/multi-chain-accounts-service/api-balance-fetcher.mjs.map +1 -1
  225. package/dist/multi-chain-accounts-service/index.cjs +3 -3
  226. package/dist/multi-chain-accounts-service/index.cjs.map +1 -1
  227. package/dist/multi-chain-accounts-service/index.d.cts.map +1 -1
  228. package/dist/multi-chain-accounts-service/index.d.mts.map +1 -1
  229. package/dist/multi-chain-accounts-service/index.mjs.map +1 -1
  230. package/dist/multi-chain-accounts-service/mocks/mock-get-balances.cjs.map +1 -1
  231. package/dist/multi-chain-accounts-service/mocks/mock-get-balances.d.cts.map +1 -1
  232. package/dist/multi-chain-accounts-service/mocks/mock-get-balances.d.mts.map +1 -1
  233. package/dist/multi-chain-accounts-service/mocks/mock-get-balances.mjs.map +1 -1
  234. package/dist/multi-chain-accounts-service/mocks/mock-get-supported-networks.cjs.map +1 -1
  235. package/dist/multi-chain-accounts-service/mocks/mock-get-supported-networks.d.cts.map +1 -1
  236. package/dist/multi-chain-accounts-service/mocks/mock-get-supported-networks.d.mts.map +1 -1
  237. package/dist/multi-chain-accounts-service/mocks/mock-get-supported-networks.mjs.map +1 -1
  238. package/dist/multi-chain-accounts-service/multi-chain-accounts.cjs.map +1 -1
  239. package/dist/multi-chain-accounts-service/multi-chain-accounts.d.cts.map +1 -1
  240. package/dist/multi-chain-accounts-service/multi-chain-accounts.d.mts.map +1 -1
  241. package/dist/multi-chain-accounts-service/multi-chain-accounts.mjs.map +1 -1
  242. package/dist/multicall.cjs +10 -10
  243. package/dist/multicall.cjs.map +1 -1
  244. package/dist/multicall.mjs.map +1 -1
  245. package/dist/rpc-service/rpc-balance-fetcher.cjs +6 -6
  246. package/dist/rpc-service/rpc-balance-fetcher.cjs.map +1 -1
  247. package/dist/rpc-service/rpc-balance-fetcher.d.cts.map +1 -1
  248. package/dist/rpc-service/rpc-balance-fetcher.d.mts.map +1 -1
  249. package/dist/rpc-service/rpc-balance-fetcher.mjs.map +1 -1
  250. package/dist/selectors/token-selectors.cjs +8 -8
  251. package/dist/selectors/token-selectors.cjs.map +1 -1
  252. package/dist/selectors/token-selectors.d.cts.map +1 -1
  253. package/dist/selectors/token-selectors.d.mts.map +1 -1
  254. package/dist/selectors/token-selectors.mjs.map +1 -1
  255. package/dist/token-prices-service/abstract-token-prices-service.cjs.map +1 -1
  256. package/dist/token-prices-service/abstract-token-prices-service.d.cts.map +1 -1
  257. package/dist/token-prices-service/abstract-token-prices-service.d.mts.map +1 -1
  258. package/dist/token-prices-service/abstract-token-prices-service.mjs.map +1 -1
  259. package/dist/token-prices-service/codefi-v2.cjs +1 -1
  260. package/dist/token-prices-service/codefi-v2.cjs.map +1 -1
  261. package/dist/token-prices-service/codefi-v2.d.cts +1 -1
  262. package/dist/token-prices-service/codefi-v2.d.cts.map +1 -1
  263. package/dist/token-prices-service/codefi-v2.d.mts +1 -1
  264. package/dist/token-prices-service/codefi-v2.d.mts.map +1 -1
  265. package/dist/token-prices-service/codefi-v2.mjs +1 -1
  266. package/dist/token-prices-service/codefi-v2.mjs.map +1 -1
  267. package/dist/token-prices-service/index.cjs +9 -9
  268. package/dist/token-prices-service/index.cjs.map +1 -1
  269. package/dist/token-prices-service/index.d.cts.map +1 -1
  270. package/dist/token-prices-service/index.d.mts.map +1 -1
  271. package/dist/token-prices-service/index.mjs.map +1 -1
  272. package/dist/token-service.cjs +2 -2
  273. package/dist/token-service.cjs.map +1 -1
  274. package/dist/token-service.mjs.map +1 -1
  275. package/package.json +9 -9
@@ -1 +1 @@
1
- {"version":3,"file":"CurrencyRateController.d.mts","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,EACV,2CAA2C,EAC3C,+BAA+B,EAEhC,qCAAqC;AAKtC,OAAO,KAAK,EAAE,mCAAmC,EAAE,yDAAqD;AACxG,OAAO,KAAK,EAAE,0BAA0B,EAAE,iEAA6D;AAGvG;;;;;;;;;;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,CAAC;QAC9B,iBAAiB,EAAE,MAAM,GAAG,IAAI,CAAC;KAClC,CACF,CAAC;CACH,CAAC;AAEF,QAAA,MAAM,IAAI,2BAA2B,CAAC;AAOtC,MAAM,MAAM,uBAAuB,GAAG,0BAA0B,CAC9D,OAAO,IAAI,EACX,iBAAiB,CAClB,CAAC;AAEF,MAAM,MAAM,4BAA4B,GAAG,uBAAuB,CAAC;AAEnE,MAAM,MAAM,oCAAoC,GAAG,wBAAwB,CACzE,OAAO,IAAI,EACX,iBAAiB,CAClB,CAAC;AAEF,MAAM,MAAM,6BAA6B,GACrC,oCAAoC,GACpC,mCAAmC,CAAC;AAExC,KAAK,cAAc,GACf,2CAA2C,GAC3C,+BAA+B,CAAC;AAEpC,MAAM,MAAM,qBAAqB,GAAG,SAAS,CAC3C,OAAO,IAAI,EACX,6BAA6B,GAAG,cAAc,EAC9C,4BAA4B,CAC7B,CAAC;AA4BF,wEAAwE;AACxE,KAAK,wBAAwB,GAAG;IAC9B,gBAAgB,EAAE,MAAM,EAAE,CAAC;CAC5B,CAAC;;;;;;;;;;;;;;;;AAiBF;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,4BAC1C,OAAO,IAAI,EACX,iBAAiB,EACjB,qBAAqB,CACtB;;IAWC;;;;;;;;;;;;;;;;OAgBG;gBACS,EACV,cAAsB,EACtB,QAAiB,EACjB,mBAAgC,EAChC,YAAmC,EACnC,SAAS,EACT,KAAK,EACL,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,YAAY,CAAC,EAAE,MAAM,OAAO,CAAC;QAC7B,kBAAkB,EAAE,0BAA0B,CAAC;KAChD;IAwCD;;;;OAIG;IACG,kBAAkB,CAAC,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAiPhE;;;;OAIG;IACG,kBAAkB,CACtB,gBAAgB,EAAE,CAAC,MAAM,GAAG,SAAS,CAAC,EAAE,GACvC,OAAO,CAAC,IAAI,CAAC;IA8ChB;;;;OAIG;IACM,OAAO,IAAI,IAAI;IAKxB;;;;;OAKG;IACG,YAAY,CAAC,EACjB,gBAAgB,GACjB,EAAE,wBAAwB,GAAG,OAAO,CAAC,IAAI,CAAC;CAQ5C;AAED,eAAe,sBAAsB,CAAC"}
1
+ {"version":3,"file":"CurrencyRateController.d.mts","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,EACV,2CAA2C,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AC,KAAK,CAAC;IAEvC,iDAAiD;IACjD,MAAM,EACJ,KAAK,EAAE,aAAa,EACpB,gBAAgB,EAAE,4BAA4B,GAC/C,GAAG,MAAM,uBAAA,IAAI,yFAAwB,MAA5B,IAAI,EACZ,uBAAuB,EACvB,eAAe,CAChB,CAAC;IAEF,oDAAoD;IACpD,IAAI,MAAM,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC3D,OAAO,aAAa,CAAC;IACvB,CAAC;IAED,oEAAoE;IACpE,MAAM,EACJ,KAAK,EAAE,iBAAiB,EACxB,gBAAgB,EAAE,4BAA4B,GAC/C,GAAG,MAAM,uBAAA,IAAI,mGAAkC,MAAtC,IAAI,EACZ,4BAA4B,EAC5B,eAAe,CAChB,CAAC;IAEF,uEAAuE;IACvE,MAAM,SAAS,GAAG,uBAAA,IAAI,+FAA8B,MAAlC,IAAI,EACpB,MAAM,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAC1C,CAAC;IAEF,4FAA4F;IAC5F,OAAO;QACL,GAAG,SAAS;QACZ,GAAG,iBAAiB;QACpB,GAAG,aAAa;KACjB,CAAC;AACJ,CAAC;AAmFH,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 {\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetStateAction,\n NetworkConfiguration,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { Hex } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\n\nimport type { CurrencyRateControllerMethodActions } from './CurrencyRateController-method-action-types';\nimport type { AbstractTokenPricesService } from './token-prices-service/abstract-token-prices-service';\nimport { getNativeTokenAddress } from './token-prices-service/codefi-v2';\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\nconst MESSENGER_EXPOSED_METHODS = [\n 'setCurrentCurrency',\n 'updateExchangeRate',\n] as const;\n\nexport type CurrencyRateStateChange = ControllerStateChangeEvent<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerEvents = CurrencyRateStateChange;\n\nexport type CurrencyRateControllerGetStateAction = ControllerGetStateAction<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerActions =\n | CurrencyRateControllerGetStateAction\n | CurrencyRateControllerMethodActions;\n\ntype AllowedActions =\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetStateAction;\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\nconst boundedPrecisionNumber = (value: number, precision = 9): number =>\n Number(value.toFixed(precision));\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 */\n/** Result from attempting to fetch rates from an API */\ntype FetchRatesResult = {\n /** Successfully fetched rates */\n rates: CurrencyRateState['currencyRates'];\n /** Currencies that failed and need fallback or null state */\n failedCurrencies: Record<string, 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 readonly #mutex = new Mutex();\n\n readonly #includeUsdRate: boolean;\n\n readonly #useExternalServices: () => boolean;\n\n readonly #tokenPricesService: AbstractTokenPricesService;\n\n readonly #isDeprecated: () => 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 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.tokenPricesService - An object in charge of retrieving token prices\n * @param options.isDeprecated - Optional function that returns true to completely\n * disable this controller (no requests, no state updates). When it returns\n * `true`, `currencyRates` is reset to `{}` at construction and at every entry point,\n * so no stale rates remain in state. The function is evaluated dynamically\n * on each entry point so it can be toggled at runtime. Intended for use when\n * a higher-level controller (e.g. AssetsController) supersedes this one.\n */\n constructor({\n includeUsdRate = false,\n interval = 180000,\n useExternalServices = () => true,\n isDeprecated = (): boolean => false,\n messenger,\n state,\n tokenPricesService,\n }: {\n includeUsdRate?: boolean;\n interval?: number;\n messenger: CurrencyRateMessenger;\n state?: Partial<CurrencyRateState>;\n useExternalServices?: () => boolean;\n isDeprecated?: () => boolean;\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.#tokenPricesService = tokenPricesService;\n this.#isDeprecated = isDeprecated;\n\n if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n }\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Clears all persisted `currencyRates` so that no stale rates remain in state.\n *\n * Called from every entry point when `isDeprecated()` is true so that a\n * runtime toggle propagates to state immediately, even if the controller was\n * originally constructed while it was enabled. The update is skipped when\n * `currencyRates` is already empty to avoid emitting redundant state changes.\n */\n #enforceDisabledState(): void {\n if (Object.keys(this.state.currencyRates).length === 0) {\n return;\n }\n this.update((state) => {\n state.currencyRates = {};\n });\n }\n\n /**\n * Sets a currency to track.\n *\n * @param currentCurrency - ISO 4217 currency code.\n */\n async setCurrentCurrency(currentCurrency: string): Promise<void> {\n if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n return;\n }\n\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 * Attempts to fetch exchange rates from the primary Price API.\n *\n * @param nativeCurrenciesToFetch - Map of native currency to the currency symbol to fetch.\n * @param currentCurrency - The current fiat currency to get rates for.\n * @returns Object containing successful rates and currencies that failed.\n */\n async #fetchRatesFromPriceApi(\n nativeCurrenciesToFetch: Record<string, string>,\n currentCurrency: string,\n ): Promise<FetchRatesResult> {\n const rates: CurrencyRateState['currencyRates'] = {};\n let failedCurrencies: Record<string, string> = {};\n\n try {\n const response = await this.#tokenPricesService.fetchExchangeRates({\n baseCurrency: currentCurrency,\n includeUsdRate: this.#includeUsdRate,\n cryptocurrencies: [...new Set(Object.values(nativeCurrenciesToFetch))],\n });\n\n Object.entries(nativeCurrenciesToFetch).forEach(\n ([nativeCurrency, fetchedCurrency]) => {\n const rate = response[fetchedCurrency.toLowerCase()];\n\n if (rate?.value) {\n rates[nativeCurrency] = {\n conversionDate: Date.now() / 1000,\n conversionRate: boundedPrecisionNumber(1 / rate.value),\n usdConversionRate: rate?.usd\n ? boundedPrecisionNumber(1 / rate.usd)\n : null,\n };\n } else {\n failedCurrencies[nativeCurrency] = fetchedCurrency;\n }\n },\n );\n } catch (error) {\n console.error('Failed to fetch exchange rates.', error);\n failedCurrencies = { ...nativeCurrenciesToFetch };\n }\n\n return { rates, failedCurrencies };\n }\n\n /**\n * Fetches exchange rates from the token prices service as a fallback.\n * This method is designed to never throw - all errors are handled internally\n * and result in currencies being marked as failed.\n *\n * @param currenciesToFetch - Map of native currencies that need fallback fetching.\n * @param currentCurrency - The current fiat currency to get rates for.\n * @returns Object containing successful rates and currencies that failed.\n */\n async #fetchRatesFromTokenPricesService(\n currenciesToFetch: Record<string, string>,\n currentCurrency: string,\n ): Promise<FetchRatesResult> {\n try {\n const rates: CurrencyRateState['currencyRates'] = {};\n const failedCurrencies: Record<string, string> = {};\n\n const networkControllerState = this.messenger.call(\n 'NetworkController:getState',\n );\n const networkConfigurations =\n networkControllerState.networkConfigurationsByChainId;\n\n // Build a map of nativeCurrency -> chainId for currencies to fetch\n const currencyToChainIds = Object.entries(currenciesToFetch).reduce<\n Record<string, { fetchedCurrency: string; chainId: Hex }>\n >((acc, [nativeCurrency, fetchedCurrency]) => {\n const matchingEntry = (\n Object.entries(networkConfigurations) as [Hex, NetworkConfiguration][]\n ).find(\n ([, config]) =>\n config.nativeCurrency.toUpperCase() ===\n fetchedCurrency.toUpperCase(),\n );\n\n if (matchingEntry) {\n acc[nativeCurrency] = { fetchedCurrency, chainId: matchingEntry[0] };\n } else {\n // No matching network configuration - mark as failed\n failedCurrencies[nativeCurrency] = fetchedCurrency;\n }\n return acc;\n }, {});\n\n const currencyToChainIdsEntries = Object.entries(currencyToChainIds);\n const ratesResults = await Promise.allSettled(\n currencyToChainIdsEntries.map(async ([nativeCurrency, { chainId }]) => {\n const nativeTokenAddress = getNativeTokenAddress(chainId);\n const tokenPrices = await this.#tokenPricesService.fetchTokenPrices({\n assets: [{ chainId, tokenAddress: nativeTokenAddress }],\n currency: currentCurrency,\n });\n\n const tokenPrice = tokenPrices.find(\n (item) =>\n item.tokenAddress.toLowerCase() ===\n nativeTokenAddress.toLowerCase(),\n );\n\n return {\n nativeCurrency,\n conversionDate: tokenPrice ? Date.now() / 1000 : null,\n conversionRate: tokenPrice?.price\n ? boundedPrecisionNumber(tokenPrice.price)\n : null,\n usdConversionRate: null,\n };\n }),\n );\n\n ratesResults.forEach((result, index) => {\n const [nativeCurrency, { fetchedCurrency, chainId }] =\n currencyToChainIdsEntries[index];\n\n if (result.status === 'fulfilled' && result.value.conversionRate) {\n rates[nativeCurrency] = {\n conversionDate: result.value.conversionDate,\n conversionRate: result.value.conversionRate,\n usdConversionRate: result.value.usdConversionRate,\n };\n } else {\n if (result.status === 'rejected') {\n console.error(\n `Failed to fetch token price for ${nativeCurrency} on chain ${chainId}`,\n result.reason,\n );\n }\n failedCurrencies[nativeCurrency] = fetchedCurrency;\n }\n });\n\n return { rates, failedCurrencies };\n } catch (error) {\n console.error(\n 'Failed to fetch exchange rates from token prices service.',\n error,\n );\n // Return all currencies as failed\n return { rates: {}, failedCurrencies: { ...currenciesToFetch } };\n }\n }\n\n /**\n * Creates null rate entries for currencies that couldn't be fetched.\n *\n * @param currencies - Array of currency symbols to create null entries for.\n * @returns Null rate entries for all provided currencies.\n */\n #createNullRatesForCurrencies(\n currencies: string[],\n ): CurrencyRateState['currencyRates'] {\n return currencies.reduce<CurrencyRateState['currencyRates']>(\n (acc, nativeCurrency) => {\n acc[nativeCurrency] = {\n conversionDate: null,\n conversionRate: null,\n usdConversionRate: null,\n };\n return acc;\n },\n {},\n );\n }\n\n /**\n * Fetches exchange rates with fallback logic.\n * First tries the Price API, then falls back to token prices service for any failed currencies.\n *\n * @param nativeCurrenciesToFetch - Map of native currency to the currency symbol to fetch.\n * @returns Exchange rates for all requested currencies.\n */\n async #fetchExchangeRatesWithFallback(\n nativeCurrenciesToFetch: Record<string, string>,\n ): Promise<CurrencyRateState['currencyRates']> {\n const { currentCurrency } = this.state;\n\n // Step 1: Try the Price API exchange rates first\n const {\n rates: ratesPriceApi,\n failedCurrencies: failedCurrenciesFromPriceApi,\n } = await this.#fetchRatesFromPriceApi(\n nativeCurrenciesToFetch,\n currentCurrency,\n );\n\n // Step 2: If all currencies succeeded, return early\n if (Object.keys(failedCurrenciesFromPriceApi).length === 0) {\n return ratesPriceApi;\n }\n\n // Step 3: Fallback using token prices service for failed currencies\n const {\n rates: ratesFromFallback,\n failedCurrencies: failedCurrenciesFromFallback,\n } = await this.#fetchRatesFromTokenPricesService(\n failedCurrenciesFromPriceApi,\n currentCurrency,\n );\n\n // Step 4: Create null rates for currencies that failed both approaches\n const nullRates = this.#createNullRatesForCurrencies(\n Object.keys(failedCurrenciesFromFallback),\n );\n\n // Step 5: Merge all results - Price API rates take priority, then fallback, then null rates\n return {\n ...nullRates,\n ...ratesFromFallback,\n ...ratesPriceApi,\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.#isDeprecated()) {\n this.#enforceDisabledState();\n return;\n }\n\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 Record<string, string>\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\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(): void {\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 if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n return;\n }\n\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;AAOpC,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAE/E,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAIpC,OAAO,EAAE,qBAAqB,EAAE,6CAA4C;AAyB5E,MAAM,IAAI,GAAG,wBAAwB,CAAC;AAEtC,MAAM,yBAAyB,GAAG;IAChC,oBAAoB;IACpB,oBAAoB;CACZ,CAAC;AA4BX,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;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEF,MAA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B,IAAI,EACZ,uBAAuB,EACvB,eAAe,CAChB,CAAC;IAEF,oDAAoD;IACpD,IAAI,MAAM,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC3D,OAAO,aAAa,CAAC;IACvB,CAAC;IAED,oEAAoE;IACpE,MAAM,EACJ,KAAK,EAAE,iBAAiB,EACxB,gBAAgB,EAAE,4BAA4B,GAC/C,GAAG,MAAM,uBAAA,IAAI,mGAAkC,MAAtC,IAAI,EACZ,4BAA4B,EAC5B,eAAe,CAChB,CAAC;IAEF,uEAAuE;IACvE,MAAM,SAAS,GAAG,uBAAA,IAAI,+FAA8B,MAAlC,IAAI,EACpB,MAAM,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAC1C,CAAC;IAEF,4FAA4F;IAC5F,OAAO;QACL,GAAG,SAAS;QACZ,GAAG,iBAAiB;QACpB,GAAG,aAAa;KACjB,CAAC;AACJ,CAAC;AAmFH,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 {\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetStateAction,\n NetworkConfiguration,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type { Hex } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\n\nimport type { CurrencyRateControllerMethodActions } from './CurrencyRateController-method-action-types.js';\nimport type { AbstractTokenPricesService } from './token-prices-service/abstract-token-prices-service.js';\nimport { getNativeTokenAddress } from './token-prices-service/codefi-v2.js';\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\nconst MESSENGER_EXPOSED_METHODS = [\n 'setCurrentCurrency',\n 'updateExchangeRate',\n] as const;\n\nexport type CurrencyRateStateChange = ControllerStateChangeEvent<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerEvents = CurrencyRateStateChange;\n\nexport type CurrencyRateControllerGetStateAction = ControllerGetStateAction<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerActions =\n | CurrencyRateControllerGetStateAction\n | CurrencyRateControllerMethodActions;\n\ntype AllowedActions =\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetStateAction;\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\nconst boundedPrecisionNumber = (value: number, precision = 9): number =>\n Number(value.toFixed(precision));\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 */\n/** Result from attempting to fetch rates from an API */\ntype FetchRatesResult = {\n /** Successfully fetched rates */\n rates: CurrencyRateState['currencyRates'];\n /** Currencies that failed and need fallback or null state */\n failedCurrencies: Record<string, 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 readonly #mutex = new Mutex();\n\n readonly #includeUsdRate: boolean;\n\n readonly #useExternalServices: () => boolean;\n\n readonly #tokenPricesService: AbstractTokenPricesService;\n\n readonly #isDeprecated: () => 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 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.tokenPricesService - An object in charge of retrieving token prices\n * @param options.isDeprecated - Optional function that returns true to completely\n * disable this controller (no requests, no state updates). When it returns\n * `true`, `currencyRates` is reset to `{}` at construction and at every entry point,\n * so no stale rates remain in state. The function is evaluated dynamically\n * on each entry point so it can be toggled at runtime. Intended for use when\n * a higher-level controller (e.g. AssetsController) supersedes this one.\n */\n constructor({\n includeUsdRate = false,\n interval = 180000,\n useExternalServices = () => true,\n isDeprecated = (): boolean => false,\n messenger,\n state,\n tokenPricesService,\n }: {\n includeUsdRate?: boolean;\n interval?: number;\n messenger: CurrencyRateMessenger;\n state?: Partial<CurrencyRateState>;\n useExternalServices?: () => boolean;\n isDeprecated?: () => boolean;\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.#tokenPricesService = tokenPricesService;\n this.#isDeprecated = isDeprecated;\n\n if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n }\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Clears all persisted `currencyRates` so that no stale rates remain in state.\n *\n * Called from every entry point when `isDeprecated()` is true so that a\n * runtime toggle propagates to state immediately, even if the controller was\n * originally constructed while it was enabled. The update is skipped when\n * `currencyRates` is already empty to avoid emitting redundant state changes.\n */\n #enforceDisabledState(): void {\n if (Object.keys(this.state.currencyRates).length === 0) {\n return;\n }\n this.update((state) => {\n state.currencyRates = {};\n });\n }\n\n /**\n * Sets a currency to track.\n *\n * @param currentCurrency - ISO 4217 currency code.\n */\n async setCurrentCurrency(currentCurrency: string): Promise<void> {\n if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n return;\n }\n\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 * Attempts to fetch exchange rates from the primary Price API.\n *\n * @param nativeCurrenciesToFetch - Map of native currency to the currency symbol to fetch.\n * @param currentCurrency - The current fiat currency to get rates for.\n * @returns Object containing successful rates and currencies that failed.\n */\n async #fetchRatesFromPriceApi(\n nativeCurrenciesToFetch: Record<string, string>,\n currentCurrency: string,\n ): Promise<FetchRatesResult> {\n const rates: CurrencyRateState['currencyRates'] = {};\n let failedCurrencies: Record<string, string> = {};\n\n try {\n const response = await this.#tokenPricesService.fetchExchangeRates({\n baseCurrency: currentCurrency,\n includeUsdRate: this.#includeUsdRate,\n cryptocurrencies: [...new Set(Object.values(nativeCurrenciesToFetch))],\n });\n\n Object.entries(nativeCurrenciesToFetch).forEach(\n ([nativeCurrency, fetchedCurrency]) => {\n const rate = response[fetchedCurrency.toLowerCase()];\n\n if (rate?.value) {\n rates[nativeCurrency] = {\n conversionDate: Date.now() / 1000,\n conversionRate: boundedPrecisionNumber(1 / rate.value),\n usdConversionRate: rate?.usd\n ? boundedPrecisionNumber(1 / rate.usd)\n : null,\n };\n } else {\n failedCurrencies[nativeCurrency] = fetchedCurrency;\n }\n },\n );\n } catch (error) {\n console.error('Failed to fetch exchange rates.', error);\n failedCurrencies = { ...nativeCurrenciesToFetch };\n }\n\n return { rates, failedCurrencies };\n }\n\n /**\n * Fetches exchange rates from the token prices service as a fallback.\n * This method is designed to never throw - all errors are handled internally\n * and result in currencies being marked as failed.\n *\n * @param currenciesToFetch - Map of native currencies that need fallback fetching.\n * @param currentCurrency - The current fiat currency to get rates for.\n * @returns Object containing successful rates and currencies that failed.\n */\n async #fetchRatesFromTokenPricesService(\n currenciesToFetch: Record<string, string>,\n currentCurrency: string,\n ): Promise<FetchRatesResult> {\n try {\n const rates: CurrencyRateState['currencyRates'] = {};\n const failedCurrencies: Record<string, string> = {};\n\n const networkControllerState = this.messenger.call(\n 'NetworkController:getState',\n );\n const networkConfigurations =\n networkControllerState.networkConfigurationsByChainId;\n\n // Build a map of nativeCurrency -> chainId for currencies to fetch\n const currencyToChainIds = Object.entries(currenciesToFetch).reduce<\n Record<string, { fetchedCurrency: string; chainId: Hex }>\n >((acc, [nativeCurrency, fetchedCurrency]) => {\n const matchingEntry = (\n Object.entries(networkConfigurations) as [Hex, NetworkConfiguration][]\n ).find(\n ([, config]) =>\n config.nativeCurrency.toUpperCase() ===\n fetchedCurrency.toUpperCase(),\n );\n\n if (matchingEntry) {\n acc[nativeCurrency] = { fetchedCurrency, chainId: matchingEntry[0] };\n } else {\n // No matching network configuration - mark as failed\n failedCurrencies[nativeCurrency] = fetchedCurrency;\n }\n return acc;\n }, {});\n\n const currencyToChainIdsEntries = Object.entries(currencyToChainIds);\n const ratesResults = await Promise.allSettled(\n currencyToChainIdsEntries.map(async ([nativeCurrency, { chainId }]) => {\n const nativeTokenAddress = getNativeTokenAddress(chainId);\n const tokenPrices = await this.#tokenPricesService.fetchTokenPrices({\n assets: [{ chainId, tokenAddress: nativeTokenAddress }],\n currency: currentCurrency,\n });\n\n const tokenPrice = tokenPrices.find(\n (item) =>\n item.tokenAddress.toLowerCase() ===\n nativeTokenAddress.toLowerCase(),\n );\n\n return {\n nativeCurrency,\n conversionDate: tokenPrice ? Date.now() / 1000 : null,\n conversionRate: tokenPrice?.price\n ? boundedPrecisionNumber(tokenPrice.price)\n : null,\n usdConversionRate: null,\n };\n }),\n );\n\n ratesResults.forEach((result, index) => {\n const [nativeCurrency, { fetchedCurrency, chainId }] =\n currencyToChainIdsEntries[index];\n\n if (result.status === 'fulfilled' && result.value.conversionRate) {\n rates[nativeCurrency] = {\n conversionDate: result.value.conversionDate,\n conversionRate: result.value.conversionRate,\n usdConversionRate: result.value.usdConversionRate,\n };\n } else {\n if (result.status === 'rejected') {\n console.error(\n `Failed to fetch token price for ${nativeCurrency} on chain ${chainId}`,\n result.reason,\n );\n }\n failedCurrencies[nativeCurrency] = fetchedCurrency;\n }\n });\n\n return { rates, failedCurrencies };\n } catch (error) {\n console.error(\n 'Failed to fetch exchange rates from token prices service.',\n error,\n );\n // Return all currencies as failed\n return { rates: {}, failedCurrencies: { ...currenciesToFetch } };\n }\n }\n\n /**\n * Creates null rate entries for currencies that couldn't be fetched.\n *\n * @param currencies - Array of currency symbols to create null entries for.\n * @returns Null rate entries for all provided currencies.\n */\n #createNullRatesForCurrencies(\n currencies: string[],\n ): CurrencyRateState['currencyRates'] {\n return currencies.reduce<CurrencyRateState['currencyRates']>(\n (acc, nativeCurrency) => {\n acc[nativeCurrency] = {\n conversionDate: null,\n conversionRate: null,\n usdConversionRate: null,\n };\n return acc;\n },\n {},\n );\n }\n\n /**\n * Fetches exchange rates with fallback logic.\n * First tries the Price API, then falls back to token prices service for any failed currencies.\n *\n * @param nativeCurrenciesToFetch - Map of native currency to the currency symbol to fetch.\n * @returns Exchange rates for all requested currencies.\n */\n async #fetchExchangeRatesWithFallback(\n nativeCurrenciesToFetch: Record<string, string>,\n ): Promise<CurrencyRateState['currencyRates']> {\n const { currentCurrency } = this.state;\n\n // Step 1: Try the Price API exchange rates first\n const {\n rates: ratesPriceApi,\n failedCurrencies: failedCurrenciesFromPriceApi,\n } = await this.#fetchRatesFromPriceApi(\n nativeCurrenciesToFetch,\n currentCurrency,\n );\n\n // Step 2: If all currencies succeeded, return early\n if (Object.keys(failedCurrenciesFromPriceApi).length === 0) {\n return ratesPriceApi;\n }\n\n // Step 3: Fallback using token prices service for failed currencies\n const {\n rates: ratesFromFallback,\n failedCurrencies: failedCurrenciesFromFallback,\n } = await this.#fetchRatesFromTokenPricesService(\n failedCurrenciesFromPriceApi,\n currentCurrency,\n );\n\n // Step 4: Create null rates for currencies that failed both approaches\n const nullRates = this.#createNullRatesForCurrencies(\n Object.keys(failedCurrenciesFromFallback),\n );\n\n // Step 5: Merge all results - Price API rates take priority, then fallback, then null rates\n return {\n ...nullRates,\n ...ratesFromFallback,\n ...ratesPriceApi,\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.#isDeprecated()) {\n this.#enforceDisabledState();\n return;\n }\n\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 Record<string, string>\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\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(): void {\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 if (this.#isDeprecated()) {\n this.#enforceDisabledState();\n return;\n }\n\n await this.updateExchangeRate(nativeCurrencies);\n }\n}\n\nexport default CurrencyRateController;\n"]}
@@ -15,9 +15,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.DeFiPositionsController = exports.getDefaultDefiPositionsControllerState = void 0;
16
16
  const keyring_api_1 = require("@metamask/keyring-api");
17
17
  const polling_controller_1 = require("@metamask/polling-controller");
18
- const calculate_defi_metrics_1 = require("./calculate-defi-metrics.cjs");
19
- const fetch_positions_1 = require("./fetch-positions.cjs");
20
- const group_defi_positions_1 = require("./group-defi-positions.cjs");
18
+ const calculate_defi_metrics_js_1 = require("./calculate-defi-metrics.cjs");
19
+ const fetch_positions_js_1 = require("./fetch-positions.cjs");
20
+ const group_defi_positions_js_1 = require("./group-defi-positions.cjs");
21
21
  const TEN_MINUTES_IN_MS = 600000;
22
22
  const controllerName = 'DeFiPositionsController';
23
23
  const controllerMetadata = {
@@ -65,7 +65,7 @@ class DeFiPositionsController extends (0, polling_controller_1.StaticIntervalPol
65
65
  _DeFiPositionsController_isEnabled.set(this, void 0);
66
66
  _DeFiPositionsController_trackEvent.set(this, void 0);
67
67
  this.setIntervalLength(TEN_MINUTES_IN_MS);
68
- __classPrivateFieldSet(this, _DeFiPositionsController_fetchPositions, (0, fetch_positions_1.buildPositionFetcher)(), "f");
68
+ __classPrivateFieldSet(this, _DeFiPositionsController_fetchPositions, (0, fetch_positions_js_1.buildPositionFetcher)(), "f");
69
69
  __classPrivateFieldSet(this, _DeFiPositionsController_isEnabled, isEnabled, "f");
70
70
  this.messenger.subscribe('KeyringController:lock', () => {
71
71
  this.stopAllPolling();
@@ -113,7 +113,7 @@ _DeFiPositionsController_fetchPositions = new WeakMap(), _DeFiPositionsControlle
113
113
  }, _DeFiPositionsController_fetchAccountPositions = async function _DeFiPositionsController_fetchAccountPositions(accountAddress) {
114
114
  try {
115
115
  const defiPositionsResponse = await __classPrivateFieldGet(this, _DeFiPositionsController_fetchPositions, "f").call(this, accountAddress);
116
- const groupedDeFiPositions = (0, group_defi_positions_1.groupDeFiPositions)(defiPositionsResponse);
116
+ const groupedDeFiPositions = (0, group_defi_positions_js_1.groupDeFiPositions)(defiPositionsResponse);
117
117
  try {
118
118
  __classPrivateFieldGet(this, _DeFiPositionsController_instances, "m", _DeFiPositionsController_updatePositionsCountMetrics).call(this, groupedDeFiPositions, accountAddress);
119
119
  }
@@ -130,7 +130,7 @@ _DeFiPositionsController_fetchPositions = new WeakMap(), _DeFiPositionsControlle
130
130
  if (!__classPrivateFieldGet(this, _DeFiPositionsController_trackEvent, "f")) {
131
131
  return;
132
132
  }
133
- const defiMetrics = (0, calculate_defi_metrics_1.calculateDeFiPositionMetrics)(groupedDeFiPositions);
133
+ const defiMetrics = (0, calculate_defi_metrics_js_1.calculateDeFiPositionMetrics)(groupedDeFiPositions);
134
134
  const { totalPositions } = defiMetrics.properties;
135
135
  if (totalPositions !== this.state.allDeFiPositionsCount[accountAddress]) {
136
136
  this.update((state) => {
@@ -1 +1 @@
1
- {"version":3,"file":"DeFiPositionsController.cjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AASA,uDAAyD;AAIzD,qEAA+E;AAI/E,yEAAwE;AAExE,2DAAyD;AACzD,qEAA4D;AAG5D,MAAM,iBAAiB,GAAG,MAAO,CAAC;AAElC,MAAM,cAAc,GAAG,yBAAyB,CAAC;AA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C/D,CAAC,CAAC,CAAC;QAEH,uBAAA,IAAI,2CAAY,EAAE,KAAlB,IAAI,EAAe,WAAW,CAAC,CAAC;IAClC,CAAC;AACH,CAAC;IAGC,OAAO,IAAI,CAAC,SAAS;SAClB,IAAI,CAAC,2DAA2D,CAAC;SACjE,IAAI,CAAC,CAAC,OAAwB,EAAE,EAAE,CAAC,IAAA,8BAAgB,EAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnE,EAAE,OAAO,CAAC;AACd,CAAC","sourcesContent":["import type {\n AccountTreeControllerGetAccountsFromSelectedAccountGroupAction,\n AccountTreeControllerSelectedAccountGroupChangeEvent,\n} from '@metamask/account-tree-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { isEvmAccountType } from '@metamask/keyring-api';\nimport type { KeyringControllerLockEvent } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\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 { groupDeFiPositions } from './group-defi-positions';\nimport type { GroupedDeFiPositions } from './group-defi-positions';\n\nconst TEN_MINUTES_IN_MS = 600_000;\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 =\n AccountTreeControllerGetAccountsFromSelectedAccountGroupAction;\n\n/**\n * The external events available to the {@link DeFiPositionsController}.\n */\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | TransactionControllerTransactionConfirmedEvent\n | AccountTreeControllerSelectedAccountGroupChangeEvent;\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:lock', () => {\n this.stopAllPolling();\n });\n\n this.messenger.subscribe(\n 'TransactionController:transactionConfirmed',\n async (transactionMeta) => {\n const selectedAddress = this.#getSelectedEvmAdress();\n\n if (\n selectedAddress?.toLowerCase() !==\n transactionMeta.txParams.from.toLowerCase()\n ) {\n return;\n }\n\n await this.#updateAccountPositions(selectedAddress);\n },\n );\n\n this.messenger.subscribe(\n 'AccountTreeController:selectedAccountGroupChange',\n async () => {\n const selectedAddress = this.#getSelectedEvmAdress();\n\n if (!selectedAddress) {\n return;\n }\n\n await this.#updateAccountPositions(selectedAddress);\n },\n );\n\n this.#trackEvent = trackEvent;\n }\n\n async _executePoll(): Promise<void> {\n if (!this.#isEnabled()) {\n return;\n }\n\n const selectedAddress = this.#getSelectedEvmAdress();\n\n if (!selectedAddress) {\n return;\n }\n\n const accountPositions = await this.#fetchAccountPositions(selectedAddress);\n\n this.update((state) => {\n state.allDeFiPositions[selectedAddress] = accountPositions;\n });\n }\n\n async #updateAccountPositions(accountAddress: string): Promise<void> {\n if (!this.#isEnabled()) {\n return;\n }\n\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 #getSelectedEvmAdress(): string | undefined {\n return this.messenger\n .call('AccountTreeController:getAccountsFromSelectedAccountGroup')\n .find((account: InternalAccount) => isEvmAccountType(account.type))\n ?.address;\n }\n}\n"]}
1
+ {"version":3,"file":"DeFiPositionsController.cjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AASA,uDAAyD;AAIzD,qEAA+E;AAI/E,4EAA2E;AAE3E,8DAA4D;AAC5D,wEAA+D;AAG/D,MAAM,iBAAiB,GAAG,MAAO,CAAC;AAElC,MAAM,cAAc,GAAG,yBAAyB,CAAC;AAuCjD,MAAM,kBAAkB,GAAgD;IACtE,gBAAgB,EAAE;QAChB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,KAAK;QACd,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;IACD,qBAAq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AA2D,CAAC;SACjE,IAAI,CAAC,CAAC,OAAwB,EAAE,EAAE,CAAC,IAAA,8BAAgB,EAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnE,EAAE,OAAO,CAAC;AACd,CAAC","sourcesContent":["import type {\n AccountTreeControllerGetAccountsFromSelectedAccountGroupAction,\n AccountTreeControllerSelectedAccountGroupChangeEvent,\n} from '@metamask/account-tree-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { isEvmAccountType } from '@metamask/keyring-api';\nimport type { KeyringControllerLockEvent } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\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.js';\nimport type { DefiPositionResponse } from './fetch-positions.js';\nimport { buildPositionFetcher } from './fetch-positions.js';\nimport { groupDeFiPositions } from './group-defi-positions.js';\nimport type { GroupedDeFiPositions } from './group-defi-positions.js';\n\nconst TEN_MINUTES_IN_MS = 600_000;\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 =\n AccountTreeControllerGetAccountsFromSelectedAccountGroupAction;\n\n/**\n * The external events available to the {@link DeFiPositionsController}.\n */\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | TransactionControllerTransactionConfirmedEvent\n | AccountTreeControllerSelectedAccountGroupChangeEvent;\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:lock', () => {\n this.stopAllPolling();\n });\n\n this.messenger.subscribe(\n 'TransactionController:transactionConfirmed',\n async (transactionMeta) => {\n const selectedAddress = this.#getSelectedEvmAdress();\n\n if (\n selectedAddress?.toLowerCase() !==\n transactionMeta.txParams.from.toLowerCase()\n ) {\n return;\n }\n\n await this.#updateAccountPositions(selectedAddress);\n },\n );\n\n this.messenger.subscribe(\n 'AccountTreeController:selectedAccountGroupChange',\n async () => {\n const selectedAddress = this.#getSelectedEvmAdress();\n\n if (!selectedAddress) {\n return;\n }\n\n await this.#updateAccountPositions(selectedAddress);\n },\n );\n\n this.#trackEvent = trackEvent;\n }\n\n async _executePoll(): Promise<void> {\n if (!this.#isEnabled()) {\n return;\n }\n\n const selectedAddress = this.#getSelectedEvmAdress();\n\n if (!selectedAddress) {\n return;\n }\n\n const accountPositions = await this.#fetchAccountPositions(selectedAddress);\n\n this.update((state) => {\n state.allDeFiPositions[selectedAddress] = accountPositions;\n });\n }\n\n async #updateAccountPositions(accountAddress: string): Promise<void> {\n if (!this.#isEnabled()) {\n return;\n }\n\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 #getSelectedEvmAdress(): string | undefined {\n return this.messenger\n .call('AccountTreeController:getAccountsFromSelectedAccountGroup')\n .find((account: InternalAccount) => isEvmAccountType(account.type))\n ?.address;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"DeFiPositionsController.d.cts","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,8DAA8D,EAC9D,oDAAoD,EACrD,0CAA0C;AAC3C,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AAEnC,OAAO,KAAK,EAAE,0BAA0B,EAAE,qCAAqC;AAE/E,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAErD,OAAO,KAAK,EAAE,8CAA8C,EAAE,yCAAyC;AACvG,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAM3C,OAAO,KAAK,EAAE,oBAAoB,EAAE,mCAA+B;AAInE,QAAA,MAAM,cAAc,4BAA4B,CAAC;AAEjD,MAAM,MAAM,4BAA4B,GAAG;IACzC,CAAC,KAAK,EAAE,GAAG,GAAG,oBAAoB,CAAC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AAG,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;IAiDK,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;CAiFpC"}
1
+ {"version":3,"file":"DeFiPositionsController.d.cts","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,8DAA8D,EAC9D,oDAAoD,EACrD,0CAA0C;AAC3C,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AAEnC,OAAO,KAAK,EAAE,0BAA0B,EAAE,qCAAqC;AAE/E,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAErD,OAAO,KAAK,EAAE,8CAA8C,EAAE,yCAAyC;AACvG,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAM3C,OAAO,KAAK,EAAE,oBAAoB,EAAE,mCAAkC;AAItE,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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AAS,EAAE,gCAAgC,CAAC;QAC5C,SAAS,CAAC,EAAE,MAAM,OAAO,CAAC;QAC1B,UAAU,CAAC,EAAE,cAAc,CAAC;KAC7B;IAiDK,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;CAiFpC"}
@@ -1 +1 @@
1
- {"version":3,"file":"DeFiPositionsController.d.mts","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,8DAA8D,EAC9D,oDAAoD,EACrD,0CAA0C;AAC3C,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AAEnC,OAAO,KAAK,EAAE,0BAA0B,EAAE,qCAAqC;AAE/E,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAErD,OAAO,KAAK,EAAE,8CAA8C,EAAE,yCAAyC;AACvG,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAM3C,OAAO,KAAK,EAAE,oBAAoB,EAAE,mCAA+B;AAInE,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;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KH,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,GACxB,8DAA8D,CAAC;AAEjE;;GAEG;AACH,MAAM,MAAM,aAAa,GACrB,0BAA0B,GAC1B,8CAA8C,GAC9C,oDAAoD,CAAC;AAEzD;;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;IAiDK,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;CAiFpC"}
@@ -1 +1 @@
1
- {"version":3,"file":"DeFiPositionsController.mjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsController.ts"],"names":[],"mappings":";;;;;;;;;;;;AASA,OAAO,EAAE,gBAAgB,EAAE,8BAA8B;AAIzD,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAI/E,OAAO,EAAE,4BAA4B,EAAE,qCAAiC;AAExE,OAAO,EAAE,oBAAoB,EAAE,8BAA0B;AACzD,OAAO,EAAE,kB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BAAqB,CAAC,cAAc,CAAC,GAAG,cAAc,CAAC;QAC/D,CAAC,CAAC,CAAC;QAEH,uBAAA,IAAI,2CAAY,EAAE,KAAlB,IAAI,EAAe,WAAW,CAAC,CAAC;IAClC,CAAC;AACH,CAAC;IAGC,OAAO,IAAI,CAAC,SAAS;SAClB,IAAI,CAAC,2DAA2D,CAAC;SACjE,IAAI,CAAC,CAAC,OAAwB,EAAE,EAAE,CAAC,gBAAgB,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnE,EAAE,OAAO,CAAC;AACd,CAAC","sourcesContent":["import type {\n AccountTreeControllerGetAccountsFromSelectedAccountGroupAction,\n AccountTreeControllerSelectedAccountGroupChangeEvent,\n} from '@metamask/account-tree-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { isEvmAccountType } from '@metamask/keyring-api';\nimport type { KeyringControllerLockEvent } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\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 { groupDeFiPositions } from './group-defi-positions';\nimport type { GroupedDeFiPositions } from './group-defi-positions';\n\nconst TEN_MINUTES_IN_MS = 600_000;\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 =\n AccountTreeControllerGetAccountsFromSelectedAccountGroupAction;\n\n/**\n * The external events available to the {@link DeFiPositionsController}.\n */\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | TransactionControllerTransactionConfirmedEvent\n | AccountTreeControllerSelectedAccountGroupChangeEvent;\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:lock', () => {\n this.stopAllPolling();\n });\n\n this.messenger.subscribe(\n 'TransactionController:transactionConfirmed',\n async (transactionMeta) => {\n const selectedAddress = this.#getSelectedEvmAdress();\n\n if (\n selectedAddress?.toLowerCase() !==\n transactionMeta.txParams.from.toLowerCase()\n ) {\n return;\n }\n\n await this.#updateAccountPositions(selectedAddress);\n },\n );\n\n this.messenger.subscribe(\n 'AccountTreeController:selectedAccountGroupChange',\n async () => {\n const selectedAddress = this.#getSelectedEvmAdress();\n\n if (!selectedAddress) {\n return;\n }\n\n await this.#updateAccountPositions(selectedAddress);\n },\n );\n\n this.#trackEvent = trackEvent;\n }\n\n async _executePoll(): Promise<void> {\n if (!this.#isEnabled()) {\n return;\n }\n\n const selectedAddress = this.#getSelectedEvmAdress();\n\n if (!selectedAddress) {\n return;\n }\n\n const accountPositions = await this.#fetchAccountPositions(selectedAddress);\n\n this.update((state) => {\n state.allDeFiPositions[selectedAddress] = accountPositions;\n });\n }\n\n async #updateAccountPositions(accountAddress: string): Promise<void> {\n if (!this.#isEnabled()) {\n return;\n }\n\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 #getSelectedEvmAdress(): string | undefined {\n return this.messenger\n .call('AccountTreeController:getAccountsFromSelectedAccountGroup')\n .find((account: InternalAccount) => isEvmAccountType(account.type))\n ?.address;\n }\n}\n"]}
1
+ {"version":3,"file":"DeFiPositionsController.mjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsController.ts"],"names":[],"mappings":";;;;;;;;;;;;AASA,OAAO,EAAE,gBAAgB,EAAE,8BAA8B;AAIzD,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAI/E,OAAO,EAAE,4BAA4B,EAAE,qCAAoC;AAE3E,OAAO,EAAE,oBAAoB,EAAE,8BAA6B;AAC5D,OAAO,EAAE,kBAAkB,EAAE,mCAAkC;AAG/D,MAAM,iBAAiB,GAAG,MAAO,CAAC;AAElC,MAAM,cAAc,GAAG,yBAAyB,CAAC;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E,KAAlB,IAAI,EAAe,WAAW,CAAC,CAAC;IAClC,CAAC;AACH,CAAC;IAGC,OAAO,IAAI,CAAC,SAAS;SAClB,IAAI,CAAC,2DAA2D,CAAC;SACjE,IAAI,CAAC,CAAC,OAAwB,EAAE,EAAE,CAAC,gBAAgB,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnE,EAAE,OAAO,CAAC;AACd,CAAC","sourcesContent":["import type {\n AccountTreeControllerGetAccountsFromSelectedAccountGroupAction,\n AccountTreeControllerSelectedAccountGroupChangeEvent,\n} from '@metamask/account-tree-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { isEvmAccountType } from '@metamask/keyring-api';\nimport type { KeyringControllerLockEvent } from '@metamask/keyring-controller';\nimport type { InternalAccount } from '@metamask/keyring-internal-api';\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.js';\nimport type { DefiPositionResponse } from './fetch-positions.js';\nimport { buildPositionFetcher } from './fetch-positions.js';\nimport { groupDeFiPositions } from './group-defi-positions.js';\nimport type { GroupedDeFiPositions } from './group-defi-positions.js';\n\nconst TEN_MINUTES_IN_MS = 600_000;\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 =\n AccountTreeControllerGetAccountsFromSelectedAccountGroupAction;\n\n/**\n * The external events available to the {@link DeFiPositionsController}.\n */\nexport type AllowedEvents =\n | KeyringControllerLockEvent\n | TransactionControllerTransactionConfirmedEvent\n | AccountTreeControllerSelectedAccountGroupChangeEvent;\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:lock', () => {\n this.stopAllPolling();\n });\n\n this.messenger.subscribe(\n 'TransactionController:transactionConfirmed',\n async (transactionMeta) => {\n const selectedAddress = this.#getSelectedEvmAdress();\n\n if (\n selectedAddress?.toLowerCase() !==\n transactionMeta.txParams.from.toLowerCase()\n ) {\n return;\n }\n\n await this.#updateAccountPositions(selectedAddress);\n },\n );\n\n this.messenger.subscribe(\n 'AccountTreeController:selectedAccountGroupChange',\n async () => {\n const selectedAddress = this.#getSelectedEvmAdress();\n\n if (!selectedAddress) {\n return;\n }\n\n await this.#updateAccountPositions(selectedAddress);\n },\n );\n\n this.#trackEvent = trackEvent;\n }\n\n async _executePoll(): Promise<void> {\n if (!this.#isEnabled()) {\n return;\n }\n\n const selectedAddress = this.#getSelectedEvmAdress();\n\n if (!selectedAddress) {\n return;\n }\n\n const accountPositions = await this.#fetchAccountPositions(selectedAddress);\n\n this.update((state) => {\n state.allDeFiPositions[selectedAddress] = accountPositions;\n });\n }\n\n async #updateAccountPositions(accountAddress: string): Promise<void> {\n if (!this.#isEnabled()) {\n return;\n }\n\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 #getSelectedEvmAdress(): string | undefined {\n return this.messenger\n .call('AccountTreeController:getAccountsFromSelectedAccountGroup')\n .find((account: InternalAccount) => isEvmAccountType(account.type))\n ?.address;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"DeFiPositionsControllerV2-method-action-types.cjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2-method-action-types.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { DeFiPositionsControllerV2 } from './DeFiPositionsControllerV2';\n\n/**\n * Fetches DeFi positions for the selected account group. Each account key in\n * a ready response replaces that account's state (other accounts stay).\n * Accounts still indexing (`processingDefiPositions`) are skipped so prior\n * state is kept for them. No-ops when disabled or when the group has no\n * supported accounts. Caching / spam prevention is handled by the apiClient\n * TanStack Query cache (keyed by accounts + query options including\n * `vsCurrency`). Pass `{ forceRefresh: true }` to bypass the cache (e.g.\n * pull-to-refresh).\n *\n * @param options - Optional fetch modifiers.\n * @param options.forceRefresh - When true, bypass the apiClient cache and\n * fetch immediately.\n */\nexport type DeFiPositionsControllerV2FetchDeFiPositionsAction = {\n type: `DeFiPositionsControllerV2:fetchDeFiPositions`;\n handler: DeFiPositionsControllerV2['fetchDeFiPositions'];\n};\n\n/**\n * Union of all DeFiPositionsControllerV2 action types.\n */\nexport type DeFiPositionsControllerV2MethodActions =\n DeFiPositionsControllerV2FetchDeFiPositionsAction;\n"]}
1
+ {"version":3,"file":"DeFiPositionsControllerV2-method-action-types.cjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2-method-action-types.ts"],"names":[],"mappings":";AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { DeFiPositionsControllerV2 } from './DeFiPositionsControllerV2.js';\n\n/**\n * Fetches DeFi positions for the selected account group. Each account key in\n * a ready response replaces that account's state (other accounts stay).\n * Accounts still indexing (`processingDefiPositions`) are skipped so prior\n * state is kept for them. No-ops when disabled or when the group has no\n * supported accounts. Caching / spam prevention is handled by the apiClient\n * TanStack Query cache (keyed by accounts + query options including\n * `vsCurrency`). Pass `{ forceRefresh: true }` to bypass the cache (e.g.\n * pull-to-refresh).\n *\n * @param options - Optional fetch modifiers.\n * @param options.forceRefresh - When true, bypass the apiClient cache and\n * fetch immediately.\n */\nexport type DeFiPositionsControllerV2FetchDeFiPositionsAction = {\n type: `DeFiPositionsControllerV2:fetchDeFiPositions`;\n handler: DeFiPositionsControllerV2['fetchDeFiPositions'];\n};\n\n/**\n * Union of all DeFiPositionsControllerV2 action types.\n */\nexport type DeFiPositionsControllerV2MethodActions =\n DeFiPositionsControllerV2FetchDeFiPositionsAction;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"DeFiPositionsControllerV2-method-action-types.d.cts","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,yBAAyB,EAAE,wCAAoC;AAE7E;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,iDAAiD,GAAG;IAC9D,IAAI,EAAE,8CAA8C,CAAC;IACrD,OAAO,EAAE,yBAAyB,CAAC,oBAAoB,CAAC,CAAC;CAC1D,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,sCAAsC,GAChD,iDAAiD,CAAC"}
1
+ {"version":3,"file":"DeFiPositionsControllerV2-method-action-types.d.cts","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,yBAAyB,EAAE,wCAAuC;AAEhF;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,iDAAiD,GAAG;IAC9D,IAAI,EAAE,8CAA8C,CAAC;IACrD,OAAO,EAAE,yBAAyB,CAAC,oBAAoB,CAAC,CAAC;CAC1D,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,sCAAsC,GAChD,iDAAiD,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"DeFiPositionsControllerV2-method-action-types.d.mts","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,yBAAyB,EAAE,wCAAoC;AAE7E;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,iDAAiD,GAAG;IAC9D,IAAI,EAAE,8CAA8C,CAAC;IACrD,OAAO,EAAE,yBAAyB,CAAC,oBAAoB,CAAC,CAAC;CAC1D,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,sCAAsC,GAChD,iDAAiD,CAAC"}
1
+ {"version":3,"file":"DeFiPositionsControllerV2-method-action-types.d.mts","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,yBAAyB,EAAE,wCAAuC;AAEhF;;;;;;;;;;;;;GAaG;AACH,MAAM,MAAM,iDAAiD,GAAG;IAC9D,IAAI,EAAE,8CAA8C,CAAC;IACrD,OAAO,EAAE,yBAAyB,CAAC,oBAAoB,CAAC,CAAC;CAC1D,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,sCAAsC,GAChD,iDAAiD,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"DeFiPositionsControllerV2-method-action-types.mjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { DeFiPositionsControllerV2 } from './DeFiPositionsControllerV2';\n\n/**\n * Fetches DeFi positions for the selected account group. Each account key in\n * a ready response replaces that account's state (other accounts stay).\n * Accounts still indexing (`processingDefiPositions`) are skipped so prior\n * state is kept for them. No-ops when disabled or when the group has no\n * supported accounts. Caching / spam prevention is handled by the apiClient\n * TanStack Query cache (keyed by accounts + query options including\n * `vsCurrency`). Pass `{ forceRefresh: true }` to bypass the cache (e.g.\n * pull-to-refresh).\n *\n * @param options - Optional fetch modifiers.\n * @param options.forceRefresh - When true, bypass the apiClient cache and\n * fetch immediately.\n */\nexport type DeFiPositionsControllerV2FetchDeFiPositionsAction = {\n type: `DeFiPositionsControllerV2:fetchDeFiPositions`;\n handler: DeFiPositionsControllerV2['fetchDeFiPositions'];\n};\n\n/**\n * Union of all DeFiPositionsControllerV2 action types.\n */\nexport type DeFiPositionsControllerV2MethodActions =\n DeFiPositionsControllerV2FetchDeFiPositionsAction;\n"]}
1
+ {"version":3,"file":"DeFiPositionsControllerV2-method-action-types.mjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2-method-action-types.ts"],"names":[],"mappings":"AAAA;;;GAGG","sourcesContent":["/**\n * This file is auto generated.\n * Do not edit manually.\n */\n\nimport type { DeFiPositionsControllerV2 } from './DeFiPositionsControllerV2.js';\n\n/**\n * Fetches DeFi positions for the selected account group. Each account key in\n * a ready response replaces that account's state (other accounts stay).\n * Accounts still indexing (`processingDefiPositions`) are skipped so prior\n * state is kept for them. No-ops when disabled or when the group has no\n * supported accounts. Caching / spam prevention is handled by the apiClient\n * TanStack Query cache (keyed by accounts + query options including\n * `vsCurrency`). Pass `{ forceRefresh: true }` to bypass the cache (e.g.\n * pull-to-refresh).\n *\n * @param options - Optional fetch modifiers.\n * @param options.forceRefresh - When true, bypass the apiClient cache and\n * fetch immediately.\n */\nexport type DeFiPositionsControllerV2FetchDeFiPositionsAction = {\n type: `DeFiPositionsControllerV2:fetchDeFiPositions`;\n handler: DeFiPositionsControllerV2['fetchDeFiPositions'];\n};\n\n/**\n * Union of all DeFiPositionsControllerV2 action types.\n */\nexport type DeFiPositionsControllerV2MethodActions =\n DeFiPositionsControllerV2FetchDeFiPositionsAction;\n"]}
@@ -14,8 +14,8 @@ var _DeFiPositionsControllerV2_apiClient, _DeFiPositionsControllerV2_isEnabled,
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.DeFiPositionsControllerV2 = exports.getDefaultDeFiPositionsControllerV2State = void 0;
16
16
  const base_controller_1 = require("@metamask/base-controller");
17
- const build_defi_balances_query_1 = require("./build-defi-balances-query.cjs");
18
- const group_defi_positions_v6_1 = require("./group-defi-positions-v6.cjs");
17
+ const build_defi_balances_query_js_1 = require("./build-defi-balances-query.cjs");
18
+ const group_defi_positions_v6_js_1 = require("./group-defi-positions-v6.cjs");
19
19
  const controllerName = 'DeFiPositionsControllerV2';
20
20
  const MESSENGER_EXPOSED_METHODS = ['fetchDeFiPositions'];
21
21
  const controllerMetadata = {
@@ -87,7 +87,7 @@ class DeFiPositionsControllerV2 extends base_controller_1.BaseController {
87
87
  return;
88
88
  }
89
89
  const selectedAccounts = this.messenger.call('AccountTreeController:getAccountsFromSelectedAccountGroup');
90
- const { networks, internalAccountIdByCaip } = (0, build_defi_balances_query_1.buildDeFiBalancesQuery)(selectedAccounts);
90
+ const { networks, internalAccountIdByCaip } = (0, build_defi_balances_query_js_1.buildDeFiBalancesQuery)(selectedAccounts);
91
91
  if (internalAccountIdByCaip.size === 0 || networks.length === 0) {
92
92
  return;
93
93
  }
@@ -109,7 +109,7 @@ class DeFiPositionsControllerV2 extends base_controller_1.BaseController {
109
109
  if (readyAccounts.length === 0) {
110
110
  return;
111
111
  }
112
- const positionsByAccount = (0, group_defi_positions_v6_1.groupDeFiPositionsV6)({ ...response, accounts: readyAccounts }, internalAccountIdByCaip);
112
+ const positionsByAccount = (0, group_defi_positions_v6_js_1.groupDeFiPositionsV6)({ ...response, accounts: readyAccounts }, internalAccountIdByCaip);
113
113
  // Last valid response wins per ready account; processing / other accounts
114
114
  // stay untouched.
115
115
  this.update((state) => {
@@ -1 +1 @@
1
- {"version":3,"file":"DeFiPositionsControllerV2.cjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,+DAA2D;AAS3D,+EAAqE;AAGrE,2EAAiE;AAEjE,MAAM,cAAc,GAAG,2BAA2B,CAAC;AAEnD,MAAM,yBAAyB,GAAG,CAAC,oBAAoB,CAAU,CAAC;AAmBlE,MAAM,kBAAkB,GAAkD;IACxE,kBAAkB,EAAE;QAClB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEK,MAAM,wCAAwC,GACnD,GAAmC,EAAE;IACnC,OAAO;QACL,kBAAkB,EAAE,EAAE;KACvB,CAAC;AACJ,CAAC,CAAC;AALS,QAAA,wCAAwC,4CAKjD;AA0CJ;;;;;;;;GAQG;AACH,MAAa,yBAA0B,SAAQ,gCAI9C;IAOC;;;;;;;OAOG;IACH,YAAY,EACV,SAAS,EACT,SAAS,EACT,SAAS,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AE,IAAI;gBACzB,uBAAuB,EAAE,IAAI;gBAC7B,aAAa,EAAE,IAAI;gBACnB,UAAU;aACX,EACD;gBACE,sEAAsE;gBACtE,GAAG,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aACnD,CACF,CAAC;YAEJ,0EAA0E;YAC1E,MAAM,aAAa,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAC5C,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,uBAAuB,CAC9C,CAAC;YACF,IAAI,aAAa,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC/B,OAAO;YACT,CAAC;YAED,MAAM,kBAAkB,GAAG,IAAA,8CAAoB,EAC7C,EAAE,GAAG,QAAQ,EAAE,QAAQ,EAAE,aAAa,EAAE,EACxC,uBAAuB,CACxB,CAAC;YAEF,0EAA0E;YAC1E,kBAAkB;YAClB,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;gBACpB,KAAK,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,IAAI,MAAM,CAAC,OAAO,CACjD,kBAAkB,CACnB,EAAE,CAAC;oBACF,KAAK,CAAC,kBAAkB,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;gBAClD,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,gCAAgC,EAAE,KAAK,CAAC,CAAC;QACzD,CAAC;IACH,CAAC;CACF;AAlID,8DAkIC","sourcesContent":["import type { AccountTreeControllerGetAccountsFromSelectedAccountGroupAction } from '@metamask/account-tree-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangedEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type { ApiPlatformClient } from '@metamask/core-backend';\nimport type { Messenger } from '@metamask/messenger';\n\nimport { buildDeFiBalancesQuery } from './build-defi-balances-query';\nimport type { DeFiPositionsControllerV2MethodActions } from './DeFiPositionsControllerV2-method-action-types';\nimport type { DeFiPositionsByAccount } from './group-defi-positions-v6';\nimport { groupDeFiPositionsV6 } from './group-defi-positions-v6';\n\nconst controllerName = 'DeFiPositionsControllerV2';\n\nconst MESSENGER_EXPOSED_METHODS = ['fetchDeFiPositions'] as const;\n\nexport type DeFiPositionsControllerV2State = {\n /**\n * DeFi positions keyed by internal MetaMask account ID (`InternalAccount.id`,\n * the same key AssetsController uses). Each account maps to a flat list of\n * protocol groups shown in the DeFi tab, each carrying its own `chainId` for\n * filtering plus the details-page sections embedded inside it. This is\n * exactly the shape the client consumes, so no further transformation is\n * needed on read.\n *\n * Named `allDeFiPositionsV2` (rather than `allDeFiPositions`) so it can live\n * alongside the legacy `DeFiPositionsController` in clients that flatten every\n * controller's state into a single object (e.g. the extension background),\n * without colliding on the shared `allDeFiPositions` key.\n */\n allDeFiPositionsV2: DeFiPositionsByAccount;\n};\n\nconst controllerMetadata: StateMetadata<DeFiPositionsControllerV2State> = {\n allDeFiPositionsV2: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\nexport const getDefaultDeFiPositionsControllerV2State =\n (): DeFiPositionsControllerV2State => {\n return {\n allDeFiPositionsV2: {},\n };\n };\n\nexport type DeFiPositionsControllerV2GetStateAction = ControllerGetStateAction<\n typeof controllerName,\n DeFiPositionsControllerV2State\n>;\n\nexport type DeFiPositionsControllerV2Actions =\n | DeFiPositionsControllerV2GetStateAction\n | DeFiPositionsControllerV2MethodActions;\n\nexport type DeFiPositionsControllerV2StateChangedEvent =\n ControllerStateChangedEvent<\n typeof controllerName,\n DeFiPositionsControllerV2State\n >;\n\nexport type DeFiPositionsControllerV2Events =\n DeFiPositionsControllerV2StateChangedEvent;\n\n/**\n * The external actions available to the {@link DeFiPositionsControllerV2}.\n */\nexport type AllowedActions =\n AccountTreeControllerGetAccountsFromSelectedAccountGroupAction;\n\n/**\n * The external events available to the {@link DeFiPositionsControllerV2}.\n *\n * None yet — clients must call `fetchDeFiPositions` (and optionally\n * `{ forceRefresh: true }`) on their own triggers. Likely future subscriptions:\n * `AccountTreeController:selectedAccountGroupChange`,\n * `TransactionController:transactionConfirmed`, and `KeyringController:lock`.\n */\nexport type AllowedEvents = never;\n\nexport type DeFiPositionsControllerV2Messenger = Messenger<\n typeof controllerName,\n DeFiPositionsControllerV2Actions | AllowedActions,\n DeFiPositionsControllerV2Events | AllowedEvents\n>;\n\n/**\n * Controller that fetches DeFi positions for the selected account group from\n * the Accounts API (v6 multiaccount balances) and stores them in the shape the\n * client consumes directly.\n *\n * Deduplication and freshness are handled by the shared TanStack Query cache on\n * {@link ApiPlatformClient} (balances default `staleTime` is 1 minute). Pass\n * `{ forceRefresh: true }` to bypass that cache for pull-to-refresh.\n */\nexport class DeFiPositionsControllerV2 extends BaseController<\n typeof controllerName,\n DeFiPositionsControllerV2State,\n DeFiPositionsControllerV2Messenger\n> {\n readonly #apiClient: ApiPlatformClient;\n\n readonly #isEnabled: () => boolean;\n\n readonly #getVsCurrency: () => string;\n\n /**\n * @param options - Constructor options.\n * @param options.messenger - The controller messenger.\n * @param options.apiClient - Accounts API client used to fetch balances/positions. Auth is handled by the client.\n * @param options.isEnabled - Returns whether fetching is enabled (default: () => false).\n * @param options.getVsCurrency - Returns the fiat currency for prices (default: () => 'usd').\n * @param options.state - Initial controller state.\n */\n constructor({\n messenger,\n apiClient,\n isEnabled,\n getVsCurrency,\n state,\n }: {\n messenger: DeFiPositionsControllerV2Messenger;\n apiClient: ApiPlatformClient;\n isEnabled: () => boolean;\n getVsCurrency: () => string;\n state?: Partial<DeFiPositionsControllerV2State>;\n }) {\n super({\n name: controllerName,\n metadata: controllerMetadata,\n messenger,\n state: {\n ...getDefaultDeFiPositionsControllerV2State(),\n ...state,\n },\n });\n\n this.#apiClient = apiClient;\n this.#isEnabled = isEnabled;\n this.#getVsCurrency = getVsCurrency;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Fetches DeFi positions for the selected account group. Each account key in\n * a ready response replaces that account's state (other accounts stay).\n * Accounts still indexing (`processingDefiPositions`) are skipped so prior\n * state is kept for them. No-ops when disabled or when the group has no\n * supported accounts. Caching / spam prevention is handled by the apiClient\n * TanStack Query cache (keyed by accounts + query options including\n * `vsCurrency`). Pass `{ forceRefresh: true }` to bypass the cache (e.g.\n * pull-to-refresh).\n *\n * @param options - Optional fetch modifiers.\n * @param options.forceRefresh - When true, bypass the apiClient cache and\n * fetch immediately.\n */\n async fetchDeFiPositions(options?: {\n forceRefresh?: boolean;\n }): Promise<void> {\n if (!this.#isEnabled()) {\n return;\n }\n\n const selectedAccounts = this.messenger.call(\n 'AccountTreeController:getAccountsFromSelectedAccountGroup',\n );\n\n const { networks, internalAccountIdByCaip } =\n buildDeFiBalancesQuery(selectedAccounts);\n\n if (internalAccountIdByCaip.size === 0 || networks.length === 0) {\n return;\n }\n\n const accountIds = [...internalAccountIdByCaip.keys()];\n const vsCurrency = this.#getVsCurrency().toLowerCase();\n\n try {\n const response =\n await this.#apiClient.accounts.fetchV6MultiAccountBalances(\n accountIds,\n {\n networks,\n includeDeFiBalances: true,\n forceFetchDeFiPositions: true,\n includePrices: true,\n vsCurrency,\n },\n {\n // staleTime: 0 makes TanStack treat the cache as stale for this call.\n ...(options?.forceRefresh ? { staleTime: 0 } : {}),\n },\n );\n\n // Skip accounts still indexing — their balances are not a valid snapshot.\n const readyAccounts = response.accounts.filter(\n (account) => !account.processingDefiPositions,\n );\n if (readyAccounts.length === 0) {\n return;\n }\n\n const positionsByAccount = groupDeFiPositionsV6(\n { ...response, accounts: readyAccounts },\n internalAccountIdByCaip,\n );\n\n // Last valid response wins per ready account; processing / other accounts\n // stay untouched.\n this.update((state) => {\n for (const [accountId, positions] of Object.entries(\n positionsByAccount,\n )) {\n state.allDeFiPositionsV2[accountId] = positions;\n }\n });\n } catch (error) {\n console.error('Failed to fetch DeFi positions', error);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"DeFiPositionsControllerV2.cjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,+DAA2D;AAS3D,kFAAwE;AAGxE,8EAAoE;AAEpE,MAAM,cAAc,GAAG,2BAA2B,CAAC;AAEnD,MAAM,yBAAyB,GAAG,CAAC,oBAAoB,CAAU,CAAC;AAmBlE,MAAM,kBAAkB,GAAkD;IACxE,kBAAkB,EAAE;QAClB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEK,MAAM,wCAAwC,GACnD,GAAmC,EAAE;IACnC,OAAO;QACL,kBAAkB,EAAE,EAAE;KACvB,CAAC;AACJ,CAAC,CAAC;AALS,QAAA,wCAAwC,4CAKjD;AA0CJ;;;;;;;;GAQG;AACH,MAAa,yBAA0B,SAAQ,gCAI9C;IAOC;;;;;;;OAOG;IACH,YAAY,EACV,SAAS,EACT,SAAS,EACT,SAAS,EACT,aAAa,EACb,KAAK,GAON;QACC,KAAK,CAAC;YACJ,IAAI,EAAE,cAAc;YACpB,QAAQ,EAAE,kBAAkB;YAC5B,SAAS;YACT,KAAK,EAAE;gBACL,GAAG,IAAA,gDAAwC,GAAE;gBAC7C,GAAG,KAAK;aACT;SACF,CAAC,CAAC;QAnCI,uDAA8B;QAE9B,uDAA0B;QAE1B,2DAA6B;QAiCpC,uBAAA,IAAI,wCAAc,SAAS,MAAA,CAAC;QAC5B,uBAAA,IAAI,wCAAc,SAAS,MAAA,CAAC;QAC5B,uBAAA,IAAI,4CAAkB,aAAa,MAAA,CAAC;QAEpC,IAAI,CAAC,SAAS,CAAC,4BAA4B,CACzC,IAAI,EACJ,yBAAyB,CAC1B,CAAC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ED,MAAM,kBAAkB,GAAG,IAAA,iDAAoB,EAC7C,EAAE,GAAG,QAAQ,EAAE,QAAQ,EAAE,aAAa,EAAE,EACxC,uBAAuB,CACxB,CAAC;YAEF,0EAA0E;YAC1E,kBAAkB;YAClB,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;gBACpB,KAAK,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,IAAI,MAAM,CAAC,OAAO,CACjD,kBAAkB,CACnB,EAAE,CAAC;oBACF,KAAK,CAAC,kBAAkB,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;gBAClD,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,gCAAgC,EAAE,KAAK,CAAC,CAAC;QACzD,CAAC;IACH,CAAC;CACF;AAlID,8DAkIC","sourcesContent":["import type { AccountTreeControllerGetAccountsFromSelectedAccountGroupAction } from '@metamask/account-tree-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangedEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type { ApiPlatformClient } from '@metamask/core-backend';\nimport type { Messenger } from '@metamask/messenger';\n\nimport { buildDeFiBalancesQuery } from './build-defi-balances-query.js';\nimport type { DeFiPositionsControllerV2MethodActions } from './DeFiPositionsControllerV2-method-action-types.js';\nimport type { DeFiPositionsByAccount } from './group-defi-positions-v6.js';\nimport { groupDeFiPositionsV6 } from './group-defi-positions-v6.js';\n\nconst controllerName = 'DeFiPositionsControllerV2';\n\nconst MESSENGER_EXPOSED_METHODS = ['fetchDeFiPositions'] as const;\n\nexport type DeFiPositionsControllerV2State = {\n /**\n * DeFi positions keyed by internal MetaMask account ID (`InternalAccount.id`,\n * the same key AssetsController uses). Each account maps to a flat list of\n * protocol groups shown in the DeFi tab, each carrying its own `chainId` for\n * filtering plus the details-page sections embedded inside it. This is\n * exactly the shape the client consumes, so no further transformation is\n * needed on read.\n *\n * Named `allDeFiPositionsV2` (rather than `allDeFiPositions`) so it can live\n * alongside the legacy `DeFiPositionsController` in clients that flatten every\n * controller's state into a single object (e.g. the extension background),\n * without colliding on the shared `allDeFiPositions` key.\n */\n allDeFiPositionsV2: DeFiPositionsByAccount;\n};\n\nconst controllerMetadata: StateMetadata<DeFiPositionsControllerV2State> = {\n allDeFiPositionsV2: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\nexport const getDefaultDeFiPositionsControllerV2State =\n (): DeFiPositionsControllerV2State => {\n return {\n allDeFiPositionsV2: {},\n };\n };\n\nexport type DeFiPositionsControllerV2GetStateAction = ControllerGetStateAction<\n typeof controllerName,\n DeFiPositionsControllerV2State\n>;\n\nexport type DeFiPositionsControllerV2Actions =\n | DeFiPositionsControllerV2GetStateAction\n | DeFiPositionsControllerV2MethodActions;\n\nexport type DeFiPositionsControllerV2StateChangedEvent =\n ControllerStateChangedEvent<\n typeof controllerName,\n DeFiPositionsControllerV2State\n >;\n\nexport type DeFiPositionsControllerV2Events =\n DeFiPositionsControllerV2StateChangedEvent;\n\n/**\n * The external actions available to the {@link DeFiPositionsControllerV2}.\n */\nexport type AllowedActions =\n AccountTreeControllerGetAccountsFromSelectedAccountGroupAction;\n\n/**\n * The external events available to the {@link DeFiPositionsControllerV2}.\n *\n * None yet — clients must call `fetchDeFiPositions` (and optionally\n * `{ forceRefresh: true }`) on their own triggers. Likely future subscriptions:\n * `AccountTreeController:selectedAccountGroupChange`,\n * `TransactionController:transactionConfirmed`, and `KeyringController:lock`.\n */\nexport type AllowedEvents = never;\n\nexport type DeFiPositionsControllerV2Messenger = Messenger<\n typeof controllerName,\n DeFiPositionsControllerV2Actions | AllowedActions,\n DeFiPositionsControllerV2Events | AllowedEvents\n>;\n\n/**\n * Controller that fetches DeFi positions for the selected account group from\n * the Accounts API (v6 multiaccount balances) and stores them in the shape the\n * client consumes directly.\n *\n * Deduplication and freshness are handled by the shared TanStack Query cache on\n * {@link ApiPlatformClient} (balances default `staleTime` is 1 minute). Pass\n * `{ forceRefresh: true }` to bypass that cache for pull-to-refresh.\n */\nexport class DeFiPositionsControllerV2 extends BaseController<\n typeof controllerName,\n DeFiPositionsControllerV2State,\n DeFiPositionsControllerV2Messenger\n> {\n readonly #apiClient: ApiPlatformClient;\n\n readonly #isEnabled: () => boolean;\n\n readonly #getVsCurrency: () => string;\n\n /**\n * @param options - Constructor options.\n * @param options.messenger - The controller messenger.\n * @param options.apiClient - Accounts API client used to fetch balances/positions. Auth is handled by the client.\n * @param options.isEnabled - Returns whether fetching is enabled (default: () => false).\n * @param options.getVsCurrency - Returns the fiat currency for prices (default: () => 'usd').\n * @param options.state - Initial controller state.\n */\n constructor({\n messenger,\n apiClient,\n isEnabled,\n getVsCurrency,\n state,\n }: {\n messenger: DeFiPositionsControllerV2Messenger;\n apiClient: ApiPlatformClient;\n isEnabled: () => boolean;\n getVsCurrency: () => string;\n state?: Partial<DeFiPositionsControllerV2State>;\n }) {\n super({\n name: controllerName,\n metadata: controllerMetadata,\n messenger,\n state: {\n ...getDefaultDeFiPositionsControllerV2State(),\n ...state,\n },\n });\n\n this.#apiClient = apiClient;\n this.#isEnabled = isEnabled;\n this.#getVsCurrency = getVsCurrency;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Fetches DeFi positions for the selected account group. Each account key in\n * a ready response replaces that account's state (other accounts stay).\n * Accounts still indexing (`processingDefiPositions`) are skipped so prior\n * state is kept for them. No-ops when disabled or when the group has no\n * supported accounts. Caching / spam prevention is handled by the apiClient\n * TanStack Query cache (keyed by accounts + query options including\n * `vsCurrency`). Pass `{ forceRefresh: true }` to bypass the cache (e.g.\n * pull-to-refresh).\n *\n * @param options - Optional fetch modifiers.\n * @param options.forceRefresh - When true, bypass the apiClient cache and\n * fetch immediately.\n */\n async fetchDeFiPositions(options?: {\n forceRefresh?: boolean;\n }): Promise<void> {\n if (!this.#isEnabled()) {\n return;\n }\n\n const selectedAccounts = this.messenger.call(\n 'AccountTreeController:getAccountsFromSelectedAccountGroup',\n );\n\n const { networks, internalAccountIdByCaip } =\n buildDeFiBalancesQuery(selectedAccounts);\n\n if (internalAccountIdByCaip.size === 0 || networks.length === 0) {\n return;\n }\n\n const accountIds = [...internalAccountIdByCaip.keys()];\n const vsCurrency = this.#getVsCurrency().toLowerCase();\n\n try {\n const response =\n await this.#apiClient.accounts.fetchV6MultiAccountBalances(\n accountIds,\n {\n networks,\n includeDeFiBalances: true,\n forceFetchDeFiPositions: true,\n includePrices: true,\n vsCurrency,\n },\n {\n // staleTime: 0 makes TanStack treat the cache as stale for this call.\n ...(options?.forceRefresh ? { staleTime: 0 } : {}),\n },\n );\n\n // Skip accounts still indexing — their balances are not a valid snapshot.\n const readyAccounts = response.accounts.filter(\n (account) => !account.processingDefiPositions,\n );\n if (readyAccounts.length === 0) {\n return;\n }\n\n const positionsByAccount = groupDeFiPositionsV6(\n { ...response, accounts: readyAccounts },\n internalAccountIdByCaip,\n );\n\n // Last valid response wins per ready account; processing / other accounts\n // stay untouched.\n this.update((state) => {\n for (const [accountId, positions] of Object.entries(\n positionsByAccount,\n )) {\n state.allDeFiPositionsV2[accountId] = positions;\n }\n });\n } catch (error) {\n console.error('Failed to fetch DeFi positions', error);\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"DeFiPositionsControllerV2.d.cts","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,8DAA8D,EAAE,0CAA0C;AACxH,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EACV,wBAAwB,EACxB,2BAA2B,EAE5B,kCAAkC;AACnC,OAAO,KAAK,EAAE,iBAAiB,EAAE,+BAA+B;AAChE,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAGrD,OAAO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G;IACG,kBAAkB,CAAC,OAAO,CAAC,EAAE;QACjC,YAAY,CAAC,EAAE,OAAO,CAAC;KACxB,GAAG,OAAO,CAAC,IAAI,CAAC;CA8DlB"}
1
+ {"version":3,"file":"DeFiPositionsControllerV2.d.cts","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,8DAA8D,EAAE,0CAA0C;AACxH,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EACV,wBAAwB,EACxB,2BAA2B,EAE5B,kCAAkC;AACnC,OAAO,KAAK,EAAE,iBAAiB,EAAE,+BAA+B;AAChE,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAGrD,OAAO,KAAK,EAAE,sCAAsC,EAAE,4DAA2D;AACjH,OAAO,KAAK,EAAE,sBAAsB,EAAE,sCAAqC;AAG3E,QAAA,MAAM,cAAc,8BAA8B,CAAC;AAInD,MAAM,MAAM,8BAA8B,GAAG;IAC3C;;;;;;;;;;;;OAYG;IACH,kBAAkB,EAAE,sBAAsB,CAAC;CAC5C,CAAC;AAWF,eAAO,MAAM,wCAAwC,QAC/C,8BAIH,CAAC;AAEJ,MAAM,MAAM,uCAAuC,GAAG,wBAAwB,CAC5E,OAAO,cAAc,EACrB,8BAA8B,CAC/B,CAAC;AAEF,MAAM,MAAM,gCAAgC,GACxC,uCAAuC,GACvC,sCAAsC,CAAC;AAE3C,MAAM,MAAM,0CAA0C,GACpD,2BAA2B,CACzB,OAAO,cAAc,EACrB,8BAA8B,CAC/B,CAAC;AAEJ,MAAM,MAAM,+BAA+B,GACzC,0CAA0C,CAAC;AAE7C;;GAEG;AACH,MAAM,MAAM,cAAc,GACxB,8DAA8D,CAAC;AAEjE;;;;;;;GAOG;AACH,MAAM,MAAM,aAAa,GAAG,KAAK,CAAC;AAElC,MAAM,MAAM,kCAAkC,GAAG,SAAS,CACxD,OAAO,cAAc,EACrB,gCAAgC,GAAG,cAAc,EACjD,+BAA+B,GAAG,aAAa,CAChD,CAAC;AAEF;;;;;;;;GAQG;AACH,qBAAa,yBAA0B,SAAQ,cAAc,CAC3D,OAAO,cAAc,EACrB,8BAA8B,EAC9B,kCAAkC,CACnC;;IAOC;;;;;;;OAOG;gBACS,EACV,SAAS,EACT,SAAS,EACT,SAAS,EACT,aAAa,EACb,KAAK,GACN,EAAE;QACD,SAAS,EAAE,kCAAkC,CAAC;QAC9C,SAAS,EAAE,iBAAiB,CAAC;QAC7B,SAAS,EAAE,MAAM,OAAO,CAAC;QACzB,aAAa,EAAE,MAAM,MAAM,CAAC;QAC5B,KAAK,CAAC,EAAE,OAAO,CAAC,8BAA8B,CAAC,CAAC;KACjD;IAqBD;;;;;;;;;;;;;OAaG;IACG,kBAAkB,CAAC,OAAO,CAAC,EAAE;QACjC,YAAY,CAAC,EAAE,OAAO,CAAC;KACxB,GAAG,OAAO,CAAC,IAAI,CAAC;CA8DlB"}
@@ -1 +1 @@
1
- {"version":3,"file":"DeFiPositionsControllerV2.d.mts","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,8DAA8D,EAAE,0CAA0C;AACxH,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,KAAK,EACV,wBAAwB,EACxB,2BAA2B,EAE5B,kCAAkC;AACnC,OAAO,KAAK,EAAE,iBAAiB,EAAE,+BAA+B;AAChE,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AAGrD,OAAO,KAAK,EAAE,sCAAsC,EAAE,4DAAwD;AAC9G,OAAO,KAAK,EAAE,sBAAsB,EAAE,sCAAkC;AAGxE,QAAA,MAAM,cAAc,8BAA8B,CAAC;AAInD,MAAM,MAAM,8BAA8B,GAAG;IAC3C;;;;;;;;;;;;OAYG;IACH,kBAAkB,EAAE,sBAAsB,CAAC;CAC5C,CAAC;AAWF,eAAO,MAAM,wCAAwC,QAC/C,8BAIH,CAAC;AAEJ,MAAM,MAAM,uCAAuC,GAAG,wBAAwB,CAC5E,OAAO,cAAc,EACrB,8BAA8B,CAC/B,CAAC;AAEF,MAAM,MAAM,gCAAgC,GACxC,uCAAuC,GACvC,sCAAsC,CAAC;AAE3C,MAAM,MAAM,0CAA0C,GACpD,2BAA2B,CACzB,OAAO,cAAc,EACrB,8BAA8B,CAC/B,CAAC;AAEJ,MAAM,MAAM,+BAA+B,GACzC,0CAA0C,CAAC;AAE7C;;GAEG;AACH,MAAM,MAAM,cAAc,GACxB,8DAA8D,CAAC;AAEjE;;;;;;;GAOG;AACH,MAAM,MAAM,aAAa,GAAG,KAAK,CAAC;AAElC,MAAM,MAAM,kCAAkC,GAAG,SAAS,CACxD,OAAO,cAAc,EACrB,gCAAgC,GAAG,cAAc,EACjD,+BAA+B,GAAG,aAAa,CAChD,CAAC;AAEF;;;;;;;;GAQG;AACH,qBAAa,yBAA0B,SAAQ,cAAc,CAC3D,OAAO,cAAc,EACrB,8BAA8B,EAC9B,kCAAkC,CACnC;;IAOC;;;;;;;OAOG;gBACS,EACV,SAAS,EACT,SAAS,EACT,SAAS,EACT,aAAa,EACb,KAAK,GACN,EAAE;QACD,SAAS,EAAE,kCAAkC,CAAC;QAC9C,SAAS,EAAE,iBAAiB,CAAC;QAC7B,SAAS,EAAE,MAAM,OAAO,CAAC;QACzB,aAAa,EAAE,MAAM,MAAM,CAAC;QAC5B,KAAK,CAAC,EAAE,OAAO,CAAC,8BAA8B,CAAC,CAAC;KACjD;IAqBD;;;;;;;;;;;;;OAaG;IACG,kBAAkB,CAAC,OAAO,CAAC,EAAE;QACjC,YAAY,CAAC,EAAE,OAAO,CAAC;KACxB,GAAG,OAAO,CAAC,IAAI,CAAC;CA8DlB"}
1
+ {"version":3,"file":"DeFiPositionsControllerV2.d.mts","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,8DA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SAAS,EAAE,kCAAkC,CAAC;QAC9C,SAAS,EAAE,iBAAiB,CAAC;QAC7B,SAAS,EAAE,MAAM,OAAO,CAAC;QACzB,aAAa,EAAE,MAAM,MAAM,CAAC;QAC5B,KAAK,CAAC,EAAE,OAAO,CAAC,8BAA8B,CAAC,CAAC;KACjD;IAqBD;;;;;;;;;;;;;OAaG;IACG,kBAAkB,CAAC,OAAO,CAAC,EAAE;QACjC,YAAY,CAAC,EAAE,OAAO,CAAC;KACxB,GAAG,OAAO,CAAC,IAAI,CAAC;CA8DlB"}
@@ -1 +1 @@
1
- {"version":3,"file":"DeFiPositionsControllerV2.mjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFiPositionsControllerV2.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAS3D,OAAO,EAAE,sBAAsB,EAAE,wCAAoC;AAGrE,OAAO,EAAE,oBAAoB,EAAE,sCAAkC;AAEjE,MAAM,cAAc,GAAG,2BAA2B,CAAC;AAEnD,MAAM,yBAAyB,GAAG,CAAC,oBAAoB,CAAU,CAAC;AAmBlE,MAAM,kBAAkB,GAAkD;IACxE,kBAAkB,EAAE;QAClB,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,KAAK;QAC7B,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEF,MAAM,CAAC,MAAM,wCAAwC,GACnD,GAAmC,EAAE;IACnC,OAAO;QACL,kBAAkB,EAAE,EAAE;KACvB,CAAC;AACJ,CAAC,CAAC;AA0CJ;;;;;;;;GAQG;AACH,MAAM,OAAO,yBAA0B,SAAQ,cAI9C;IAOC;;;;;;;OAOG;IACH,YAAY,EACV,SAAS,EACT,SAAS,EACT,SAAS,EACT,aAAa,EACb,KAAK,GAON;QACC,KAAK,CAAC;YACJ,IAAI,EAAE,cAAc;YACpB,QAAQ,EAAE,kBAAkB;YAC5B,SAAS;YACT,KAAK,EAAE;g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CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;aACnD,CACF,CAAC;YAEJ,0EAA0E;YAC1E,MAAM,aAAa,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAC5C,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,uBAAuB,CAC9C,CAAC;YACF,IAAI,aAAa,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC/B,OAAO;YACT,CAAC;YAED,MAAM,kBAAkB,GAAG,oBAAoB,CAC7C,EAAE,GAAG,QAAQ,EAAE,QAAQ,EAAE,aAAa,EAAE,EACxC,uBAAuB,CACxB,CAAC;YAEF,0EAA0E;YAC1E,kBAAkB;YAClB,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;gBACpB,KAAK,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,IAAI,MAAM,CAAC,OAAO,CACjD,kBAAkB,CACnB,EAAE,CAAC;oBACF,KAAK,CAAC,kBAAkB,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;gBAClD,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,gCAAgC,EAAE,KAAK,CAAC,CAAC;QACzD,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { AccountTreeControllerGetAccountsFromSelectedAccountGroupAction } from '@metamask/account-tree-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangedEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type { ApiPlatformClient } from '@metamask/core-backend';\nimport type { Messenger } from '@metamask/messenger';\n\nimport { buildDeFiBalancesQuery } from './build-defi-balances-query';\nimport type { DeFiPositionsControllerV2MethodActions } from './DeFiPositionsControllerV2-method-action-types';\nimport type { DeFiPositionsByAccount } from './group-defi-positions-v6';\nimport { groupDeFiPositionsV6 } from './group-defi-positions-v6';\n\nconst controllerName = 'DeFiPositionsControllerV2';\n\nconst MESSENGER_EXPOSED_METHODS = ['fetchDeFiPositions'] as const;\n\nexport type DeFiPositionsControllerV2State = {\n /**\n * DeFi positions keyed by internal MetaMask account ID (`InternalAccount.id`,\n * the same key AssetsController uses). Each account maps to a flat list of\n * protocol groups shown in the DeFi tab, each carrying its own `chainId` for\n * filtering plus the details-page sections embedded inside it. This is\n * exactly the shape the client consumes, so no further transformation is\n * needed on read.\n *\n * Named `allDeFiPositionsV2` (rather than `allDeFiPositions`) so it can live\n * alongside the legacy `DeFiPositionsController` in clients that flatten every\n * controller's state into a single object (e.g. the extension background),\n * without colliding on the shared `allDeFiPositions` key.\n */\n allDeFiPositionsV2: DeFiPositionsByAccount;\n};\n\nconst controllerMetadata: StateMetadata<DeFiPositionsControllerV2State> = {\n allDeFiPositionsV2: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\nexport const getDefaultDeFiPositionsControllerV2State =\n (): DeFiPositionsControllerV2State => {\n return {\n allDeFiPositionsV2: {},\n };\n };\n\nexport type DeFiPositionsControllerV2GetStateAction = ControllerGetStateAction<\n typeof controllerName,\n DeFiPositionsControllerV2State\n>;\n\nexport type DeFiPositionsControllerV2Actions =\n | DeFiPositionsControllerV2GetStateAction\n | DeFiPositionsControllerV2MethodActions;\n\nexport type DeFiPositionsControllerV2StateChangedEvent =\n ControllerStateChangedEvent<\n typeof controllerName,\n DeFiPositionsControllerV2State\n >;\n\nexport type DeFiPositionsControllerV2Events =\n DeFiPositionsControllerV2StateChangedEvent;\n\n/**\n * The external actions available to the {@link DeFiPositionsControllerV2}.\n */\nexport type AllowedActions =\n AccountTreeControllerGetAccountsFromSelectedAccountGroupAction;\n\n/**\n * The external events available to the {@link DeFiPositionsControllerV2}.\n *\n * None yet — clients must call `fetchDeFiPositions` (and optionally\n * `{ forceRefresh: true }`) on their own triggers. Likely future subscriptions:\n * `AccountTreeController:selectedAccountGroupChange`,\n * `TransactionController:transactionConfirmed`, and `KeyringController:lock`.\n */\nexport type AllowedEvents = never;\n\nexport type DeFiPositionsControllerV2Messenger = Messenger<\n typeof controllerName,\n DeFiPositionsControllerV2Actions | AllowedActions,\n DeFiPositionsControllerV2Events | AllowedEvents\n>;\n\n/**\n * Controller that fetches DeFi positions for the selected account group from\n * the Accounts API (v6 multiaccount balances) and stores them in the shape the\n * client consumes directly.\n *\n * Deduplication and freshness are handled by the shared TanStack Query cache on\n * {@link ApiPlatformClient} (balances default `staleTime` is 1 minute). Pass\n * `{ forceRefresh: true }` to bypass that cache for pull-to-refresh.\n */\nexport class DeFiPositionsControllerV2 extends BaseController<\n typeof controllerName,\n DeFiPositionsControllerV2State,\n DeFiPositionsControllerV2Messenger\n> {\n readonly #apiClient: ApiPlatformClient;\n\n readonly #isEnabled: () => boolean;\n\n readonly #getVsCurrency: () => string;\n\n /**\n * @param options - Constructor options.\n * @param options.messenger - The controller messenger.\n * @param options.apiClient - Accounts API client used to fetch balances/positions. Auth is handled by the client.\n * @param options.isEnabled - Returns whether fetching is enabled (default: () => false).\n * @param options.getVsCurrency - Returns the fiat currency for prices (default: () => 'usd').\n * @param options.state - Initial controller state.\n */\n constructor({\n messenger,\n apiClient,\n isEnabled,\n getVsCurrency,\n state,\n }: {\n messenger: DeFiPositionsControllerV2Messenger;\n apiClient: ApiPlatformClient;\n isEnabled: () => boolean;\n getVsCurrency: () => string;\n state?: Partial<DeFiPositionsControllerV2State>;\n }) {\n super({\n name: controllerName,\n metadata: controllerMetadata,\n messenger,\n state: {\n ...getDefaultDeFiPositionsControllerV2State(),\n ...state,\n },\n });\n\n this.#apiClient = apiClient;\n this.#isEnabled = isEnabled;\n this.#getVsCurrency = getVsCurrency;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Fetches DeFi positions for the selected account group. Each account key in\n * a ready response replaces that account's state (other accounts stay).\n * Accounts still indexing (`processingDefiPositions`) are skipped so prior\n * state is kept for them. No-ops when disabled or when the group has no\n * supported accounts. Caching / spam prevention is handled by the apiClient\n * TanStack Query cache (keyed by accounts + query options including\n * `vsCurrency`). Pass `{ forceRefresh: true }` to bypass the cache (e.g.\n * pull-to-refresh).\n *\n * @param options - Optional fetch modifiers.\n * @param options.forceRefresh - When true, bypass the apiClient cache and\n * fetch immediately.\n */\n async fetchDeFiPositions(options?: {\n forceRefresh?: boolean;\n }): Promise<void> {\n if (!this.#isEnabled()) {\n return;\n }\n\n const selectedAccounts = this.messenger.call(\n 'AccountTreeController:getAccountsFromSelectedAccountGroup',\n );\n\n const { networks, internalAccountIdByCaip } =\n buildDeFiBalancesQuery(selectedAccounts);\n\n if (internalAccountIdByCaip.size === 0 || networks.length === 0) {\n return;\n }\n\n const accountIds = [...internalAccountIdByCaip.keys()];\n const vsCurrency = this.#getVsCurrency().toLowerCase();\n\n try {\n const response =\n await this.#apiClient.accounts.fetchV6MultiAccountBalances(\n accountIds,\n {\n networks,\n includeDeFiBalances: true,\n forceFetchDeFiPositions: true,\n includePrices: true,\n vsCurrency,\n },\n {\n // staleTime: 0 makes TanStack treat the cache as stale for this call.\n ...(options?.forceRefresh ? { staleTime: 0 } : {}),\n },\n );\n\n // Skip accounts still indexing — their balances are not a valid snapshot.\n const readyAccounts = response.accounts.filter(\n (account) => !account.processingDefiPositions,\n );\n if (readyAccounts.length === 0) {\n return;\n }\n\n const positionsByAccount = groupDeFiPositionsV6(\n { ...response, accounts: readyAccounts },\n internalAccountIdByCaip,\n );\n\n // Last valid response wins per ready account; processing / other accounts\n // stay untouched.\n this.update((state) => {\n for (const [accountId, positions] of Object.entries(\n positionsByAccount,\n )) {\n state.allDeFiPositionsV2[accountId] = positions;\n }\n });\n } catch (error) {\n console.error('Failed to fetch DeFi positions', error);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"DeFiPositionsControllerV2.mjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/DeFi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,CAAC;YAEF,0EAA0E;YAC1E,kBAAkB;YAClB,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;gBACpB,KAAK,MAAM,CAAC,SAAS,EAAE,SAAS,CAAC,IAAI,MAAM,CAAC,OAAO,CACjD,kBAAkB,CACnB,EAAE,CAAC;oBACF,KAAK,CAAC,kBAAkB,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC;gBAClD,CAAC;YACH,CAAC,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,gCAAgC,EAAE,KAAK,CAAC,CAAC;QACzD,CAAC;IACH,CAAC;CACF","sourcesContent":["import type { AccountTreeControllerGetAccountsFromSelectedAccountGroupAction } from '@metamask/account-tree-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangedEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport type { ApiPlatformClient } from '@metamask/core-backend';\nimport type { Messenger } from '@metamask/messenger';\n\nimport { buildDeFiBalancesQuery } from './build-defi-balances-query.js';\nimport type { DeFiPositionsControllerV2MethodActions } from './DeFiPositionsControllerV2-method-action-types.js';\nimport type { DeFiPositionsByAccount } from './group-defi-positions-v6.js';\nimport { groupDeFiPositionsV6 } from './group-defi-positions-v6.js';\n\nconst controllerName = 'DeFiPositionsControllerV2';\n\nconst MESSENGER_EXPOSED_METHODS = ['fetchDeFiPositions'] as const;\n\nexport type DeFiPositionsControllerV2State = {\n /**\n * DeFi positions keyed by internal MetaMask account ID (`InternalAccount.id`,\n * the same key AssetsController uses). Each account maps to a flat list of\n * protocol groups shown in the DeFi tab, each carrying its own `chainId` for\n * filtering plus the details-page sections embedded inside it. This is\n * exactly the shape the client consumes, so no further transformation is\n * needed on read.\n *\n * Named `allDeFiPositionsV2` (rather than `allDeFiPositions`) so it can live\n * alongside the legacy `DeFiPositionsController` in clients that flatten every\n * controller's state into a single object (e.g. the extension background),\n * without colliding on the shared `allDeFiPositions` key.\n */\n allDeFiPositionsV2: DeFiPositionsByAccount;\n};\n\nconst controllerMetadata: StateMetadata<DeFiPositionsControllerV2State> = {\n allDeFiPositionsV2: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: false,\n usedInUi: true,\n },\n};\n\nexport const getDefaultDeFiPositionsControllerV2State =\n (): DeFiPositionsControllerV2State => {\n return {\n allDeFiPositionsV2: {},\n };\n };\n\nexport type DeFiPositionsControllerV2GetStateAction = ControllerGetStateAction<\n typeof controllerName,\n DeFiPositionsControllerV2State\n>;\n\nexport type DeFiPositionsControllerV2Actions =\n | DeFiPositionsControllerV2GetStateAction\n | DeFiPositionsControllerV2MethodActions;\n\nexport type DeFiPositionsControllerV2StateChangedEvent =\n ControllerStateChangedEvent<\n typeof controllerName,\n DeFiPositionsControllerV2State\n >;\n\nexport type DeFiPositionsControllerV2Events =\n DeFiPositionsControllerV2StateChangedEvent;\n\n/**\n * The external actions available to the {@link DeFiPositionsControllerV2}.\n */\nexport type AllowedActions =\n AccountTreeControllerGetAccountsFromSelectedAccountGroupAction;\n\n/**\n * The external events available to the {@link DeFiPositionsControllerV2}.\n *\n * None yet — clients must call `fetchDeFiPositions` (and optionally\n * `{ forceRefresh: true }`) on their own triggers. Likely future subscriptions:\n * `AccountTreeController:selectedAccountGroupChange`,\n * `TransactionController:transactionConfirmed`, and `KeyringController:lock`.\n */\nexport type AllowedEvents = never;\n\nexport type DeFiPositionsControllerV2Messenger = Messenger<\n typeof controllerName,\n DeFiPositionsControllerV2Actions | AllowedActions,\n DeFiPositionsControllerV2Events | AllowedEvents\n>;\n\n/**\n * Controller that fetches DeFi positions for the selected account group from\n * the Accounts API (v6 multiaccount balances) and stores them in the shape the\n * client consumes directly.\n *\n * Deduplication and freshness are handled by the shared TanStack Query cache on\n * {@link ApiPlatformClient} (balances default `staleTime` is 1 minute). Pass\n * `{ forceRefresh: true }` to bypass that cache for pull-to-refresh.\n */\nexport class DeFiPositionsControllerV2 extends BaseController<\n typeof controllerName,\n DeFiPositionsControllerV2State,\n DeFiPositionsControllerV2Messenger\n> {\n readonly #apiClient: ApiPlatformClient;\n\n readonly #isEnabled: () => boolean;\n\n readonly #getVsCurrency: () => string;\n\n /**\n * @param options - Constructor options.\n * @param options.messenger - The controller messenger.\n * @param options.apiClient - Accounts API client used to fetch balances/positions. Auth is handled by the client.\n * @param options.isEnabled - Returns whether fetching is enabled (default: () => false).\n * @param options.getVsCurrency - Returns the fiat currency for prices (default: () => 'usd').\n * @param options.state - Initial controller state.\n */\n constructor({\n messenger,\n apiClient,\n isEnabled,\n getVsCurrency,\n state,\n }: {\n messenger: DeFiPositionsControllerV2Messenger;\n apiClient: ApiPlatformClient;\n isEnabled: () => boolean;\n getVsCurrency: () => string;\n state?: Partial<DeFiPositionsControllerV2State>;\n }) {\n super({\n name: controllerName,\n metadata: controllerMetadata,\n messenger,\n state: {\n ...getDefaultDeFiPositionsControllerV2State(),\n ...state,\n },\n });\n\n this.#apiClient = apiClient;\n this.#isEnabled = isEnabled;\n this.#getVsCurrency = getVsCurrency;\n\n this.messenger.registerMethodActionHandlers(\n this,\n MESSENGER_EXPOSED_METHODS,\n );\n }\n\n /**\n * Fetches DeFi positions for the selected account group. Each account key in\n * a ready response replaces that account's state (other accounts stay).\n * Accounts still indexing (`processingDefiPositions`) are skipped so prior\n * state is kept for them. No-ops when disabled or when the group has no\n * supported accounts. Caching / spam prevention is handled by the apiClient\n * TanStack Query cache (keyed by accounts + query options including\n * `vsCurrency`). Pass `{ forceRefresh: true }` to bypass the cache (e.g.\n * pull-to-refresh).\n *\n * @param options - Optional fetch modifiers.\n * @param options.forceRefresh - When true, bypass the apiClient cache and\n * fetch immediately.\n */\n async fetchDeFiPositions(options?: {\n forceRefresh?: boolean;\n }): Promise<void> {\n if (!this.#isEnabled()) {\n return;\n }\n\n const selectedAccounts = this.messenger.call(\n 'AccountTreeController:getAccountsFromSelectedAccountGroup',\n );\n\n const { networks, internalAccountIdByCaip } =\n buildDeFiBalancesQuery(selectedAccounts);\n\n if (internalAccountIdByCaip.size === 0 || networks.length === 0) {\n return;\n }\n\n const accountIds = [...internalAccountIdByCaip.keys()];\n const vsCurrency = this.#getVsCurrency().toLowerCase();\n\n try {\n const response =\n await this.#apiClient.accounts.fetchV6MultiAccountBalances(\n accountIds,\n {\n networks,\n includeDeFiBalances: true,\n forceFetchDeFiPositions: true,\n includePrices: true,\n vsCurrency,\n },\n {\n // staleTime: 0 makes TanStack treat the cache as stale for this call.\n ...(options?.forceRefresh ? { staleTime: 0 } : {}),\n },\n );\n\n // Skip accounts still indexing — their balances are not a valid snapshot.\n const readyAccounts = response.accounts.filter(\n (account) => !account.processingDefiPositions,\n );\n if (readyAccounts.length === 0) {\n return;\n }\n\n const positionsByAccount = groupDeFiPositionsV6(\n { ...response, accounts: readyAccounts },\n internalAccountIdByCaip,\n );\n\n // Last valid response wins per ready account; processing / other accounts\n // stay untouched.\n this.update((state) => {\n for (const [accountId, positions] of Object.entries(\n positionsByAccount,\n )) {\n state.allDeFiPositionsV2[accountId] = positions;\n }\n });\n } catch (error) {\n console.error('Failed to fetch DeFi positions', error);\n }\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"calculate-defi-metrics.cjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/calculate-defi-metrics.ts"],"names":[],"mappings":";;;AAOA;;;;;;GAMG;AACH,SAAgB,4BAA4B,CAC1C,wBAAsD;IAEtD,IAAI,mBAAmB,GAAG,CAAC,CAAC;IAC5B,IAAI,cAAc,GAAG,CAAC,CAAC;IACvB,MAAM,SAAS,GAKT,EAAE,CAAC;IAET,MAAM,CAAC,OAAO,CAAC,wBAAwB,CAAC,CAAC,OAAO,CAC9C,CAAC,CAAC,OAAO,EAAE,cAAc,CAAC,EAAE,EAAE;QAC5B,MAAM,wBAAwB,GAAG,cAAc,CAAC,qBAAqB,CAAC;QACtE,mBAAmB,IAAI,wBAAwB,CAAC;QAEhD,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC,OAAO,CAC9C,CAAC,CAAC,UAAU,EAAE,QAAQ,CAAC,EAAE,EAAE;YACzB,MAAM,2BAA2B,GAAG,QAAQ,CAAC,qBAAqB,CAAC;YAEnE,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC,MAAM,CAChE,CAAC,GAAG,EAAE,YAAY,EAAE,EAAE,CACpB,GAAG,GAAG,CAAC,YAAY,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,MAAM,IAAI,CAAC,CAAC,EAErD,CAAC,CACF,CAAC;YAEF,cAAc,IAAI,aAAa,CAAC;YAEhC,SAAS,CAAC,IAAI,CAAC;gBACb,UAAU;gBACV,cAAc,EAAE,2BAA2B;gBAC3C,OAAO,EAAE,OAAc;gBACvB,KAAK,EAAE,aAAa;aACrB,CAAC,CAAC;QACL,CAAC,CACF,CAAC;IACJ,CAAC,CACF,CAAC;IACF,OAAO;QACL,QAAQ,EAAE,MAAM;QAChB,KAAK,EAAE,YAAY;QACnB,UAAU,EAAE;YACV,mBAAmB;YACnB,cAAc;YACd,SAAS;SACV;KACF,CAAC;AACJ,CAAC;AAjDD,oEAiDC","sourcesContent":["import type { Hex } from '@metamask/utils';\n\nimport type {\n GroupedDeFiPositionsPerChain,\n TrackingEventPayload,\n} from './DeFiPositionsController';\n\n/**\n * Calculates the total market value and total positions for a given account\n * and returns a breakdown of the market value per protocol.\n *\n * @param accountPositionsPerChain - The account positions per chain.\n * @returns An object containing the total market value, total positions, and a breakdown of the market value per protocol.\n */\nexport function calculateDeFiPositionMetrics(\n accountPositionsPerChain: GroupedDeFiPositionsPerChain,\n): TrackingEventPayload {\n let totalMarketValueUSD = 0;\n let totalPositions = 0;\n const breakdown: {\n protocolId: string;\n marketValueUSD: number;\n chainId: Hex;\n count: number;\n }[] = [];\n\n Object.entries(accountPositionsPerChain).forEach(\n ([chainId, chainPositions]) => {\n const chainTotalMarketValueUSD = chainPositions.aggregatedMarketValue;\n totalMarketValueUSD += chainTotalMarketValueUSD;\n\n Object.entries(chainPositions.protocols).forEach(\n ([protocolId, protocol]) => {\n const protocolTotalMarketValueUSD = protocol.aggregatedMarketValue;\n\n const protocolCount = Object.values(protocol.positionTypes).reduce(\n (acc, positionType) =>\n acc + (positionType?.positions?.flat().length || 0),\n\n 0,\n );\n\n totalPositions += protocolCount;\n\n breakdown.push({\n protocolId,\n marketValueUSD: protocolTotalMarketValueUSD,\n chainId: chainId as Hex,\n count: protocolCount,\n });\n },\n );\n },\n );\n return {\n category: 'DeFi',\n event: 'DeFi Stats',\n properties: {\n totalMarketValueUSD,\n totalPositions,\n breakdown,\n },\n };\n}\n"]}
1
+ {"version":3,"file":"calculate-defi-metrics.cjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/calculate-defi-metrics.ts"],"names":[],"mappings":";;;AAOA;;;;;;GAMG;AACH,SAAgB,4BAA4B,CAC1C,wBAAsD;IAEtD,IAAI,mBAAmB,GAAG,CAAC,CAAC;IAC5B,IAAI,cAAc,GAAG,CAAC,CAAC;IACvB,MAAM,SAAS,GAKT,EAAE,CAAC;IAET,MAAM,CAAC,OAAO,CAAC,wBAAwB,CAAC,CAAC,OAAO,CAC9C,CAAC,CAAC,OAAO,EAAE,cAAc,CAAC,EAAE,EAAE;QAC5B,MAAM,wBAAwB,GAAG,cAAc,CAAC,qBAAqB,CAAC;QACtE,mBAAmB,IAAI,wBAAwB,CAAC;QAEhD,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC,OAAO,CAC9C,CAAC,CAAC,UAAU,EAAE,QAAQ,CAAC,EAAE,EAAE;YACzB,MAAM,2BAA2B,GAAG,QAAQ,CAAC,qBAAqB,CAAC;YAEnE,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC,MAAM,CAChE,CAAC,GAAG,EAAE,YAAY,EAAE,EAAE,CACpB,GAAG,GAAG,CAAC,YAAY,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,MAAM,IAAI,CAAC,CAAC,EAErD,CAAC,CACF,CAAC;YAEF,cAAc,IAAI,aAAa,CAAC;YAEhC,SAAS,CAAC,IAAI,CAAC;gBACb,UAAU;gBACV,cAAc,EAAE,2BAA2B;gBAC3C,OAAO,EAAE,OAAc;gBACvB,KAAK,EAAE,aAAa;aACrB,CAAC,CAAC;QACL,CAAC,CACF,CAAC;IACJ,CAAC,CACF,CAAC;IACF,OAAO;QACL,QAAQ,EAAE,MAAM;QAChB,KAAK,EAAE,YAAY;QACnB,UAAU,EAAE;YACV,mBAAmB;YACnB,cAAc;YACd,SAAS;SACV;KACF,CAAC;AACJ,CAAC;AAjDD,oEAiDC","sourcesContent":["import type { Hex } from '@metamask/utils';\n\nimport type {\n GroupedDeFiPositionsPerChain,\n TrackingEventPayload,\n} from './DeFiPositionsController.js';\n\n/**\n * Calculates the total market value and total positions for a given account\n * and returns a breakdown of the market value per protocol.\n *\n * @param accountPositionsPerChain - The account positions per chain.\n * @returns An object containing the total market value, total positions, and a breakdown of the market value per protocol.\n */\nexport function calculateDeFiPositionMetrics(\n accountPositionsPerChain: GroupedDeFiPositionsPerChain,\n): TrackingEventPayload {\n let totalMarketValueUSD = 0;\n let totalPositions = 0;\n const breakdown: {\n protocolId: string;\n marketValueUSD: number;\n chainId: Hex;\n count: number;\n }[] = [];\n\n Object.entries(accountPositionsPerChain).forEach(\n ([chainId, chainPositions]) => {\n const chainTotalMarketValueUSD = chainPositions.aggregatedMarketValue;\n totalMarketValueUSD += chainTotalMarketValueUSD;\n\n Object.entries(chainPositions.protocols).forEach(\n ([protocolId, protocol]) => {\n const protocolTotalMarketValueUSD = protocol.aggregatedMarketValue;\n\n const protocolCount = Object.values(protocol.positionTypes).reduce(\n (acc, positionType) =>\n acc + (positionType?.positions?.flat().length || 0),\n\n 0,\n );\n\n totalPositions += protocolCount;\n\n breakdown.push({\n protocolId,\n marketValueUSD: protocolTotalMarketValueUSD,\n chainId: chainId as Hex,\n count: protocolCount,\n });\n },\n );\n },\n );\n return {\n category: 'DeFi',\n event: 'DeFi Stats',\n properties: {\n totalMarketValueUSD,\n totalPositions,\n breakdown,\n },\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"calculate-defi-metrics.d.cts","sourceRoot":"","sources":["../../src/DeFiPositionsController/calculate-defi-metrics.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,4BAA4B,EAC5B,oBAAoB,EACrB,sCAAkC;AAEnC;;;;;;GAMG;AACH,wBAAgB,4BAA4B,CAC1C,wBAAwB,EAAE,4BAA4B,GACrD,oBAAoB,CA+CtB"}
1
+ {"version":3,"file":"calculate-defi-metrics.d.cts","sourceRoot":"","sources":["../../src/DeFiPositionsController/calculate-defi-metrics.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,4BAA4B,EAC5B,oBAAoB,EACrB,sCAAqC;AAEtC;;;;;;GAMG;AACH,wBAAgB,4BAA4B,CAC1C,wBAAwB,EAAE,4BAA4B,GACrD,oBAAoB,CA+CtB"}
@@ -1 +1 @@
1
- {"version":3,"file":"calculate-defi-metrics.d.mts","sourceRoot":"","sources":["../../src/DeFiPositionsController/calculate-defi-metrics.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,4BAA4B,EAC5B,oBAAoB,EACrB,sCAAkC;AAEnC;;;;;;GAMG;AACH,wBAAgB,4BAA4B,CAC1C,wBAAwB,EAAE,4BAA4B,GACrD,oBAAoB,CA+CtB"}
1
+ {"version":3,"file":"calculate-defi-metrics.d.mts","sourceRoot":"","sources":["../../src/DeFiPositionsController/calculate-defi-metrics.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,4BAA4B,EAC5B,oBAAoB,EACrB,sCAAqC;AAEtC;;;;;;GAMG;AACH,wBAAgB,4BAA4B,CAC1C,wBAAwB,EAAE,4BAA4B,GACrD,oBAAoB,CA+CtB"}
@@ -1 +1 @@
1
- {"version":3,"file":"calculate-defi-metrics.mjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/calculate-defi-metrics.ts"],"names":[],"mappings":"AAOA;;;;;;GAMG;AACH,MAAM,UAAU,4BAA4B,CAC1C,wBAAsD;IAEtD,IAAI,mBAAmB,GAAG,CAAC,CAAC;IAC5B,IAAI,cAAc,GAAG,CAAC,CAAC;IACvB,MAAM,SAAS,GAKT,EAAE,CAAC;IAET,MAAM,CAAC,OAAO,CAAC,wBAAwB,CAAC,CAAC,OAAO,CAC9C,CAAC,CAAC,OAAO,EAAE,cAAc,CAAC,EAAE,EAAE;QAC5B,MAAM,wBAAwB,GAAG,cAAc,CAAC,qBAAqB,CAAC;QACtE,mBAAmB,IAAI,wBAAwB,CAAC;QAEhD,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC,OAAO,CAC9C,CAAC,CAAC,UAAU,EAAE,QAAQ,CAAC,EAAE,EAAE;YACzB,MAAM,2BAA2B,GAAG,QAAQ,CAAC,qBAAqB,CAAC;YAEnE,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC,MAAM,CAChE,CAAC,GAAG,EAAE,YAAY,EAAE,EAAE,CACpB,GAAG,GAAG,CAAC,YAAY,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,MAAM,IAAI,CAAC,CAAC,EAErD,CAAC,CACF,CAAC;YAEF,cAAc,IAAI,aAAa,CAAC;YAEhC,SAAS,CAAC,IAAI,CAAC;gBACb,UAAU;gBACV,cAAc,EAAE,2BAA2B;gBAC3C,OAAO,EAAE,OAAc;gBACvB,KAAK,EAAE,aAAa;aACrB,CAAC,CAAC;QACL,CAAC,CACF,CAAC;IACJ,CAAC,CACF,CAAC;IACF,OAAO;QACL,QAAQ,EAAE,MAAM;QAChB,KAAK,EAAE,YAAY;QACnB,UAAU,EAAE;YACV,mBAAmB;YACnB,cAAc;YACd,SAAS;SACV;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { Hex } from '@metamask/utils';\n\nimport type {\n GroupedDeFiPositionsPerChain,\n TrackingEventPayload,\n} from './DeFiPositionsController';\n\n/**\n * Calculates the total market value and total positions for a given account\n * and returns a breakdown of the market value per protocol.\n *\n * @param accountPositionsPerChain - The account positions per chain.\n * @returns An object containing the total market value, total positions, and a breakdown of the market value per protocol.\n */\nexport function calculateDeFiPositionMetrics(\n accountPositionsPerChain: GroupedDeFiPositionsPerChain,\n): TrackingEventPayload {\n let totalMarketValueUSD = 0;\n let totalPositions = 0;\n const breakdown: {\n protocolId: string;\n marketValueUSD: number;\n chainId: Hex;\n count: number;\n }[] = [];\n\n Object.entries(accountPositionsPerChain).forEach(\n ([chainId, chainPositions]) => {\n const chainTotalMarketValueUSD = chainPositions.aggregatedMarketValue;\n totalMarketValueUSD += chainTotalMarketValueUSD;\n\n Object.entries(chainPositions.protocols).forEach(\n ([protocolId, protocol]) => {\n const protocolTotalMarketValueUSD = protocol.aggregatedMarketValue;\n\n const protocolCount = Object.values(protocol.positionTypes).reduce(\n (acc, positionType) =>\n acc + (positionType?.positions?.flat().length || 0),\n\n 0,\n );\n\n totalPositions += protocolCount;\n\n breakdown.push({\n protocolId,\n marketValueUSD: protocolTotalMarketValueUSD,\n chainId: chainId as Hex,\n count: protocolCount,\n });\n },\n );\n },\n );\n return {\n category: 'DeFi',\n event: 'DeFi Stats',\n properties: {\n totalMarketValueUSD,\n totalPositions,\n breakdown,\n },\n };\n}\n"]}
1
+ {"version":3,"file":"calculate-defi-metrics.mjs","sourceRoot":"","sources":["../../src/DeFiPositionsController/calculate-defi-metrics.ts"],"names":[],"mappings":"AAOA;;;;;;GAMG;AACH,MAAM,UAAU,4BAA4B,CAC1C,wBAAsD;IAEtD,IAAI,mBAAmB,GAAG,CAAC,CAAC;IAC5B,IAAI,cAAc,GAAG,CAAC,CAAC;IACvB,MAAM,SAAS,GAKT,EAAE,CAAC;IAET,MAAM,CAAC,OAAO,CAAC,wBAAwB,CAAC,CAAC,OAAO,CAC9C,CAAC,CAAC,OAAO,EAAE,cAAc,CAAC,EAAE,EAAE;QAC5B,MAAM,wBAAwB,GAAG,cAAc,CAAC,qBAAqB,CAAC;QACtE,mBAAmB,IAAI,wBAAwB,CAAC;QAEhD,MAAM,CAAC,OAAO,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC,OAAO,CAC9C,CAAC,CAAC,UAAU,EAAE,QAAQ,CAAC,EAAE,EAAE;YACzB,MAAM,2BAA2B,GAAG,QAAQ,CAAC,qBAAqB,CAAC;YAEnE,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC,MAAM,CAChE,CAAC,GAAG,EAAE,YAAY,EAAE,EAAE,CACpB,GAAG,GAAG,CAAC,YAAY,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,MAAM,IAAI,CAAC,CAAC,EAErD,CAAC,CACF,CAAC;YAEF,cAAc,IAAI,aAAa,CAAC;YAEhC,SAAS,CAAC,IAAI,CAAC;gBACb,UAAU;gBACV,cAAc,EAAE,2BAA2B;gBAC3C,OAAO,EAAE,OAAc;gBACvB,KAAK,EAAE,aAAa;aACrB,CAAC,CAAC;QACL,CAAC,CACF,CAAC;IACJ,CAAC,CACF,CAAC;IACF,OAAO;QACL,QAAQ,EAAE,MAAM;QAChB,KAAK,EAAE,YAAY;QACnB,UAAU,EAAE;YACV,mBAAmB;YACnB,cAAc;YACd,SAAS;SACV;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { Hex } from '@metamask/utils';\n\nimport type {\n GroupedDeFiPositionsPerChain,\n TrackingEventPayload,\n} from './DeFiPositionsController.js';\n\n/**\n * Calculates the total market value and total positions for a given account\n * and returns a breakdown of the market value per protocol.\n *\n * @param accountPositionsPerChain - The account positions per chain.\n * @returns An object containing the total market value, total positions, and a breakdown of the market value per protocol.\n */\nexport function calculateDeFiPositionMetrics(\n accountPositionsPerChain: GroupedDeFiPositionsPerChain,\n): TrackingEventPayload {\n let totalMarketValueUSD = 0;\n let totalPositions = 0;\n const breakdown: {\n protocolId: string;\n marketValueUSD: number;\n chainId: Hex;\n count: number;\n }[] = [];\n\n Object.entries(accountPositionsPerChain).forEach(\n ([chainId, chainPositions]) => {\n const chainTotalMarketValueUSD = chainPositions.aggregatedMarketValue;\n totalMarketValueUSD += chainTotalMarketValueUSD;\n\n Object.entries(chainPositions.protocols).forEach(\n ([protocolId, protocol]) => {\n const protocolTotalMarketValueUSD = protocol.aggregatedMarketValue;\n\n const protocolCount = Object.values(protocol.positionTypes).reduce(\n (acc, positionType) =>\n acc + (positionType?.positions?.flat().length || 0),\n\n 0,\n );\n\n totalPositions += protocolCount;\n\n breakdown.push({\n protocolId,\n marketValueUSD: protocolTotalMarketValueUSD,\n chainId: chainId as Hex,\n count: protocolCount,\n });\n },\n );\n },\n );\n return {\n category: 'DeFi',\n event: 'DeFi Stats',\n properties: {\n totalMarketValueUSD,\n totalPositions,\n breakdown,\n },\n };\n}\n"]}