@metamask/assets-controllers 31.0.0 → 33.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/CHANGELOG.md +68 -1
  2. package/dist/AccountTrackerController.js +2 -2
  3. package/dist/AccountTrackerController.mjs +1 -1
  4. package/dist/AssetsContractController.js +6 -6
  5. package/dist/AssetsContractController.mjs +5 -5
  6. package/dist/CurrencyRateController.js +3 -3
  7. package/dist/CurrencyRateController.mjs +2 -2
  8. package/dist/NftController.js +3 -3
  9. package/dist/NftController.mjs +2 -2
  10. package/dist/NftDetectionController.js +2 -2
  11. package/dist/NftDetectionController.mjs +1 -1
  12. package/dist/RatesController/RatesController.js +3 -3
  13. package/dist/RatesController/RatesController.mjs +2 -2
  14. package/dist/RatesController/index.js +3 -3
  15. package/dist/RatesController/index.mjs +2 -2
  16. package/dist/Standards/ERC20Standard.js +3 -3
  17. package/dist/Standards/ERC20Standard.mjs +2 -2
  18. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js +3 -3
  19. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.mjs +2 -2
  20. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js +3 -3
  21. package/dist/Standards/NftStandards/ERC721/ERC721Standard.mjs +2 -2
  22. package/dist/TokenBalancesController.js +2 -2
  23. package/dist/TokenBalancesController.mjs +1 -1
  24. package/dist/TokenDetectionController.js +3 -3
  25. package/dist/TokenDetectionController.mjs +2 -2
  26. package/dist/TokenListController.js +4 -4
  27. package/dist/TokenListController.mjs +3 -3
  28. package/dist/TokenRatesController.js +9 -5
  29. package/dist/TokenRatesController.mjs +10 -6
  30. package/dist/TokensController.js +6 -6
  31. package/dist/TokensController.mjs +5 -5
  32. package/dist/assetsUtil.js +2 -2
  33. package/dist/assetsUtil.mjs +1 -1
  34. package/dist/chunk-2IIQTSLV.mjs +236 -0
  35. package/dist/chunk-2IIQTSLV.mjs.map +1 -0
  36. package/dist/chunk-354SINOH.js +236 -0
  37. package/dist/chunk-354SINOH.js.map +1 -0
  38. package/dist/{chunk-MR6EF4B7.mjs → chunk-3K3LE2CZ.mjs} +14 -2
  39. package/dist/chunk-3K3LE2CZ.mjs.map +1 -0
  40. package/dist/{chunk-5W5OO2Q5.mjs → chunk-47CRHAUE.mjs} +2 -2
  41. package/dist/chunk-47CRHAUE.mjs.map +1 -0
  42. package/dist/{chunk-65PB33TE.mjs → chunk-526TATMH.mjs} +25 -17
  43. package/dist/chunk-526TATMH.mjs.map +1 -0
  44. package/dist/{chunk-D3K5MPMW.mjs → chunk-56O7BVZV.mjs} +2 -2
  45. package/dist/{chunk-B5YY22QQ.js → chunk-6PPM4ETZ.js} +3 -3
  46. package/dist/{chunk-CGLUTXI7.js → chunk-7JWDWDXT.js} +190 -107
  47. package/dist/chunk-7JWDWDXT.js.map +1 -0
  48. package/dist/{chunk-JUI3XNEF.js → chunk-7OZL6IDY.js} +16 -9
  49. package/dist/chunk-7OZL6IDY.js.map +1 -0
  50. package/dist/{chunk-GU53EI7A.js → chunk-AZ6SRJVI.js} +24 -16
  51. package/dist/chunk-AZ6SRJVI.js.map +1 -0
  52. package/dist/{chunk-YIFA2HXH.js → chunk-F6L3DFOZ.js} +5 -3
  53. package/dist/chunk-F6L3DFOZ.js.map +1 -0
  54. package/dist/{chunk-UEDNQBJN.js → chunk-FGAZXVKS.js} +200 -104
  55. package/dist/chunk-FGAZXVKS.js.map +1 -0
  56. package/dist/{chunk-B6W4CQOR.mjs → chunk-HJ5GXVDT.mjs} +2 -2
  57. package/dist/chunk-HJ5GXVDT.mjs.map +1 -0
  58. package/dist/{chunk-BOTVAG4A.js → chunk-JBF4XEGR.js} +5 -5
  59. package/dist/{chunk-ASA5RLBY.mjs → chunk-JEIAMJGS.mjs} +2 -2
  60. package/dist/{chunk-CNKVITJO.mjs → chunk-JTXPJ6TK.mjs} +4 -2
  61. package/dist/chunk-JTXPJ6TK.mjs.map +1 -0
  62. package/dist/{chunk-U3DJJN4X.js → chunk-LBJTMJFA.js} +4 -4
  63. package/dist/{chunk-IBK6AXPP.js → chunk-NWVMFCSC.js} +1 -1
  64. package/dist/{chunk-IBK6AXPP.js.map → chunk-NWVMFCSC.js.map} +1 -1
  65. package/dist/{chunk-NEXY7SE2.js → chunk-NYVA7ZTQ.js} +2 -2
  66. package/dist/chunk-NYVA7ZTQ.js.map +1 -0
  67. package/dist/{chunk-WCCLSUOI.mjs → chunk-OEEFNXR7.mjs} +1 -1
  68. package/dist/{chunk-WCCLSUOI.mjs.map → chunk-OEEFNXR7.mjs.map} +1 -1
  69. package/dist/{chunk-E4ECCGJV.mjs → chunk-P3O5CVAH.mjs} +195 -99
  70. package/dist/chunk-P3O5CVAH.mjs.map +1 -0
  71. package/dist/{chunk-4AC3X2U5.js → chunk-RJBYLTY5.js} +29 -14
  72. package/dist/chunk-RJBYLTY5.js.map +1 -0
  73. package/dist/{chunk-B5YVX5IO.mjs → chunk-SBWPU4VT.mjs} +4 -2
  74. package/dist/chunk-SBWPU4VT.mjs.map +1 -0
  75. package/dist/{chunk-ELSMS5S7.js → chunk-T5ZX5BV7.js} +3 -3
  76. package/dist/{chunk-ELSMS5S7.js.map → chunk-T5ZX5BV7.js.map} +1 -1
  77. package/dist/{chunk-HLCGZGPA.mjs → chunk-TWR6P5WG.mjs} +11 -7
  78. package/dist/chunk-TWR6P5WG.mjs.map +1 -0
  79. package/dist/{chunk-73F3SN5O.mjs → chunk-UVE4XY5Y.mjs} +23 -8
  80. package/dist/chunk-UVE4XY5Y.mjs.map +1 -0
  81. package/dist/{chunk-LZ5ZGQEX.mjs → chunk-UYH6NWKB.mjs} +2 -2
  82. package/dist/{chunk-Z6TBQQE5.js → chunk-V6DNVROD.js} +4 -4
  83. package/dist/chunk-V6DNVROD.js.map +1 -0
  84. package/dist/{chunk-Q5JRBGWO.mjs → chunk-VELPHITE.mjs} +2 -2
  85. package/dist/chunk-VELPHITE.mjs.map +1 -0
  86. package/dist/{chunk-HDI4L2DD.js → chunk-VZF43NDM.js} +17 -5
  87. package/dist/chunk-VZF43NDM.js.map +1 -0
  88. package/dist/{chunk-62T7RKU3.mjs → chunk-W57QXOHJ.mjs} +188 -105
  89. package/dist/chunk-W57QXOHJ.mjs.map +1 -0
  90. package/dist/{chunk-PYMUBJQX.js → chunk-X4RMS365.js} +3 -3
  91. package/dist/chunk-X4RMS365.js.map +1 -0
  92. package/dist/{chunk-Y35SM7TO.mjs → chunk-XQO3EG4J.mjs} +4 -4
  93. package/dist/chunk-XQO3EG4J.mjs.map +1 -0
  94. package/dist/{chunk-QHWKLZUC.js → chunk-XSNGD5US.js} +14 -10
  95. package/dist/chunk-XSNGD5US.js.map +1 -0
  96. package/dist/{chunk-A2DDWXMS.mjs → chunk-Y45HQET7.mjs} +12 -5
  97. package/dist/chunk-Y45HQET7.mjs.map +1 -0
  98. package/dist/{chunk-WB6KJX4N.js → chunk-ZG5MS2TO.js} +4 -2
  99. package/dist/chunk-ZG5MS2TO.js.map +1 -0
  100. package/dist/crypto-compare-service/crypto-compare.js +2 -2
  101. package/dist/crypto-compare-service/crypto-compare.mjs +1 -1
  102. package/dist/crypto-compare-service/index.js +2 -2
  103. package/dist/crypto-compare-service/index.mjs +1 -1
  104. package/dist/index.js +21 -19
  105. package/dist/index.mjs +21 -19
  106. package/dist/token-prices-service/codefi-v2.js +2 -2
  107. package/dist/token-prices-service/codefi-v2.mjs +1 -1
  108. package/dist/token-prices-service/index.js +2 -2
  109. package/dist/token-prices-service/index.mjs +1 -1
  110. package/dist/token-service.js +3 -3
  111. package/dist/token-service.mjs +2 -2
  112. package/dist/tsconfig.build.tsbuildinfo +1 -1
  113. package/dist/types/AccountTrackerController.d.ts +13 -12
  114. package/dist/types/AccountTrackerController.d.ts.map +1 -1
  115. package/dist/types/AssetsContractController.d.ts.map +1 -1
  116. package/dist/types/CurrencyRateController.d.ts.map +1 -1
  117. package/dist/types/NftController.d.ts +4 -5
  118. package/dist/types/NftController.d.ts.map +1 -1
  119. package/dist/types/NftDetectionController.d.ts +7 -18
  120. package/dist/types/NftDetectionController.d.ts.map +1 -1
  121. package/dist/types/RatesController/RatesController.d.ts.map +1 -1
  122. package/dist/types/TokenBalancesController.d.ts.map +1 -1
  123. package/dist/types/TokenDetectionController.d.ts.map +1 -1
  124. package/dist/types/TokenListController.d.ts.map +1 -1
  125. package/dist/types/TokenRatesController.d.ts +72 -65
  126. package/dist/types/TokenRatesController.d.ts.map +1 -1
  127. package/dist/types/TokensController.d.ts.map +1 -1
  128. package/dist/types/assetsUtil.d.ts.map +1 -1
  129. package/dist/types/crypto-compare-service/crypto-compare.d.ts.map +1 -1
  130. package/dist/types/index.d.ts +2 -2
  131. package/dist/types/index.d.ts.map +1 -1
  132. package/dist/types/token-prices-service/abstract-token-prices-service.d.ts +0 -1
  133. package/dist/types/token-prices-service/abstract-token-prices-service.d.ts.map +1 -1
  134. package/dist/types/token-prices-service/codefi-v2.d.ts +1 -1
  135. package/dist/types/token-prices-service/codefi-v2.d.ts.map +1 -1
  136. package/dist/types/token-service.d.ts.map +1 -1
  137. package/package.json +16 -16
  138. package/dist/chunk-4AC3X2U5.js.map +0 -1
  139. package/dist/chunk-543CC74T.mjs +0 -253
  140. package/dist/chunk-543CC74T.mjs.map +0 -1
  141. package/dist/chunk-5W5OO2Q5.mjs.map +0 -1
  142. package/dist/chunk-62T7RKU3.mjs.map +0 -1
  143. package/dist/chunk-65PB33TE.mjs.map +0 -1
  144. package/dist/chunk-73F3SN5O.mjs.map +0 -1
  145. package/dist/chunk-A2DDWXMS.mjs.map +0 -1
  146. package/dist/chunk-B5YVX5IO.mjs.map +0 -1
  147. package/dist/chunk-B6W4CQOR.mjs.map +0 -1
  148. package/dist/chunk-CGLUTXI7.js.map +0 -1
  149. package/dist/chunk-CNKVITJO.mjs.map +0 -1
  150. package/dist/chunk-E4ECCGJV.mjs.map +0 -1
  151. package/dist/chunk-GU53EI7A.js.map +0 -1
  152. package/dist/chunk-HDI4L2DD.js.map +0 -1
  153. package/dist/chunk-HLCGZGPA.mjs.map +0 -1
  154. package/dist/chunk-JUI3XNEF.js.map +0 -1
  155. package/dist/chunk-MR6EF4B7.mjs.map +0 -1
  156. package/dist/chunk-NEXY7SE2.js.map +0 -1
  157. package/dist/chunk-PYMUBJQX.js.map +0 -1
  158. package/dist/chunk-Q5JRBGWO.mjs.map +0 -1
  159. package/dist/chunk-QFDTOEYR.js +0 -253
  160. package/dist/chunk-QFDTOEYR.js.map +0 -1
  161. package/dist/chunk-QHWKLZUC.js.map +0 -1
  162. package/dist/chunk-UEDNQBJN.js.map +0 -1
  163. package/dist/chunk-WB6KJX4N.js.map +0 -1
  164. package/dist/chunk-Y35SM7TO.mjs.map +0 -1
  165. package/dist/chunk-YIFA2HXH.js.map +0 -1
  166. package/dist/chunk-Z6TBQQE5.js.map +0 -1
  167. /package/dist/{chunk-D3K5MPMW.mjs.map → chunk-56O7BVZV.mjs.map} +0 -0
  168. /package/dist/{chunk-B5YY22QQ.js.map → chunk-6PPM4ETZ.js.map} +0 -0
  169. /package/dist/{chunk-BOTVAG4A.js.map → chunk-JBF4XEGR.js.map} +0 -0
  170. /package/dist/{chunk-ASA5RLBY.mjs.map → chunk-JEIAMJGS.mjs.map} +0 -0
  171. /package/dist/{chunk-U3DJJN4X.js.map → chunk-LBJTMJFA.js.map} +0 -0
  172. /package/dist/{chunk-LZ5ZGQEX.mjs.map → chunk-UYH6NWKB.mjs.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/token-prices-service/codefi-v2.ts"],"names":[],"mappings":";;;;;;;AAAA,SAAS,mBAAmB;AAE5B,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAYA,IAAM,uBAAuB;AAAA;AAAA,EAElC;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA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1E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,0BAA0B,UAAkD;AAC1E,UAAM,sBAAyC;AAC/C,WACE,OAAO,aAAa,YACpB,oBAAoB,SAAS,SAAS,YAAY,CAAC;AAAA,EAEvD;AACF;AA5JE","sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\nimport { hexToNumber } from '@metamask/utils';\nimport {\n circuitBreaker,\n ConsecutiveBreaker,\n ExponentialBackoff,\n handleAll,\n type IPolicy,\n retry,\n wrap,\n CircuitState,\n} from 'cockatiel';\n\nimport type {\n AbstractTokenPricesService,\n TokenPrice,\n TokenPricesByTokenAddress,\n} from './abstract-token-prices-service';\n\n/**\n * The list of currencies that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint, in lowercase form.\n */\nexport const SUPPORTED_CURRENCIES = [\n // Bitcoin\n 'btc',\n // Ether\n 'eth',\n // Litecoin\n 'ltc',\n // Bitcoin Cash\n 'bch',\n // Binance Coin\n 'bnb',\n // EOS\n 'eos',\n // XRP\n 'xrp',\n // Lumens\n 'xlm',\n // Chainlink\n 'link',\n // Polkadot\n 'dot',\n // Yearn.finance\n 'yfi',\n // US Dollar\n 'usd',\n // United Arab Emirates Dirham\n 'aed',\n // Argentine Peso\n 'ars',\n // Australian Dollar\n 'aud',\n // Bangladeshi Taka\n 'bdt',\n // Bahraini Dinar\n 'bhd',\n // Bermudian Dollar\n 'bmd',\n // Brazil Real\n 'brl',\n // Canadian Dollar\n 'cad',\n // Swiss Franc\n 'chf',\n // Chilean Peso\n 'clp',\n // Chinese Yuan\n 'cny',\n // Czech Koruna\n 'czk',\n // Danish Krone\n 'dkk',\n // Euro\n 'eur',\n // British Pound Sterling\n 'gbp',\n // Hong Kong Dollar\n 'hkd',\n // Hungarian Forint\n 'huf',\n // Indonesian Rupiah\n 'idr',\n // Israeli New Shekel\n 'ils',\n // Indian Rupee\n 'inr',\n // Japanese Yen\n 'jpy',\n // South Korean Won\n 'krw',\n // Kuwaiti Dinar\n 'kwd',\n // Sri Lankan Rupee\n 'lkr',\n // Burmese Kyat\n 'mmk',\n // Mexican Peso\n 'mxn',\n // Malaysian Ringgit\n 'myr',\n // Nigerian Naira\n 'ngn',\n // Norwegian Krone\n 'nok',\n // New Zealand Dollar\n 'nzd',\n // Philippine Peso\n 'php',\n // Pakistani Rupee\n 'pkr',\n // Polish Zloty\n 'pln',\n // Russian Ruble\n 'rub',\n // Saudi Riyal\n 'sar',\n // Swedish Krona\n 'sek',\n // Singapore Dollar\n 'sgd',\n // Thai Baht\n 'thb',\n // Turkish Lira\n 'try',\n // New Taiwan Dollar\n 'twd',\n // Ukrainian hryvnia\n 'uah',\n // Venezuelan bolívar fuerte\n 'vef',\n // Vietnamese đồng\n 'vnd',\n // South African Rand\n 'zar',\n // IMF Special Drawing Rights\n 'xdr',\n // Silver - Troy Ounce\n 'xag',\n // Gold - Troy Ounce\n 'xau',\n // Bits\n 'bits',\n // Satoshi\n 'sats',\n] as const;\n\n/**\n * Represents the zero address, commonly used as a placeholder in blockchain transactions.\n * In the context of fetching market data, the zero address is utilized to retrieve information\n * specifically for native currencies. This allows for a standardized approach to query market\n * data for blockchain-native assets without a specific contract address.\n */\nexport const ZERO_ADDRESS: Hex =\n '0x0000000000000000000000000000000000000000' as const;\n\n/**\n * A currency that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.\n */\ntype SupportedCurrency =\n | (typeof SUPPORTED_CURRENCIES)[number]\n | Uppercase<(typeof SUPPORTED_CURRENCIES)[number]>;\n\n/**\n * The list of chain IDs that can be supplied in the URL for the `/spot-prices`\n * endpoint, but in hexadecimal form (for consistency with how we represent\n * chain IDs in other places).\n * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.\n */\nexport const SUPPORTED_CHAIN_IDS = [\n // Ethereum Mainnet\n '0x1',\n // OP Mainnet\n '0xa',\n // Cronos Mainnet\n '0x19',\n // BNB Smart Chain Mainnet\n '0x38',\n // Syscoin Mainnet\n '0x39',\n // OKXChain Mainnet\n '0x42',\n // Hoo Smart Chain\n '0x46',\n // Meter Mainnet\n '0x52',\n // TomoChain\n '0x58',\n // Gnosis\n '0x64',\n // Velas EVM Mainnet\n '0x6a',\n // Fuse Mainnet\n '0x7a',\n // Huobi ECO Chain Mainnet\n '0x80',\n // Polygon Mainnet\n '0x89',\n // Fantom Opera\n '0xfa',\n // Boba Network\n '0x120',\n // KCC Mainnet\n '0x141',\n // zkSync Era Mainnet\n '0x144',\n // Theta Mainnet\n '0x169',\n // Metis Andromeda Mainnet\n '0x440',\n // Moonbeam\n '0x504',\n // Moonriver\n '0x505',\n // Mantle\n '0x1388',\n // Base\n '0x2105',\n // Shiden\n '0x150',\n // Smart Bitcoin Cash\n '0x2710',\n // Arbitrum One\n '0xa4b1',\n // Celo Mainnet\n '0xa4ec',\n // Oasis Emerald\n '0xa516',\n // Avalanche C-Chain\n '0xa86a',\n // Polis Mainnet\n '0x518af',\n // Aurora Mainnet\n '0x4e454152',\n // Harmony Mainnet Shard 0\n '0x63564c40',\n // Linea Mainnet\n '0xe708',\n] as const;\n\n/**\n * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,\n * but in hexadecimal form (for consistency with how we represent chain IDs in\n * other places).\n */\ntype SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];\n\n/**\n * All requests to V2 of the Price API start with this.\n */\nconst BASE_URL = 'https://price.api.cx.metamask.io/v2';\n\nconst DEFAULT_TOKEN_PRICE_RETRIES = 3;\n// Each update attempt will result (1 + retries) calls if the server is down\nconst DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES =\n (1 + DEFAULT_TOKEN_PRICE_RETRIES) * 3;\n\nconst DEFAULT_DEGRADED_THRESHOLD = 5_000;\n\n/**\n * The shape of the data that the /spot-prices endpoint returns.\n */\ntype MarketData = {\n /**\n * The all-time highest price of the token.\n */\n allTimeHigh: number;\n /**\n * The all-time lowest price of the token.\n */\n allTimeLow: number;\n /**\n * The number of tokens currently in circulation.\n */\n circulatingSupply: number;\n /**\n * The market cap calculated using the diluted supply.\n */\n dilutedMarketCap: number;\n /**\n * The highest price of the token in the last 24 hours.\n */\n high1d: number;\n /**\n * The lowest price of the token in the last 24 hours.\n */\n low1d: number;\n /**\n * The current market capitalization of the token.\n */\n marketCap: number;\n /**\n * The percentage change in market capitalization over the last 24 hours.\n */\n marketCapPercentChange1d: number;\n /**\n * The current price of the token.\n */\n price: number;\n /**\n * The absolute change in price over the last 24 hours.\n */\n priceChange1d: number;\n /**\n * The percentage change in price over the last 24 hours.\n */\n pricePercentChange1d: number;\n /**\n * The percentage change in price over the last hour.\n */\n pricePercentChange1h: number;\n /**\n * The percentage change in price over the last year.\n */\n pricePercentChange1y: number;\n /**\n * The percentage change in price over the last 7 days.\n */\n pricePercentChange7d: number;\n /**\n * The percentage change in price over the last 14 days.\n */\n pricePercentChange14d: number;\n /**\n * The percentage change in price over the last 30 days.\n */\n pricePercentChange30d: number;\n /**\n * The percentage change in price over the last 200 days.\n */\n pricePercentChange200d: number;\n /**\n * The total trading volume of the token in the last 24 hours.\n */\n totalVolume: number;\n};\n\ntype MarketDataByTokenAddress = { [address: Hex]: MarketData };\n/**\n * This version of the token prices service uses V2 of the Codefi Price API to\n * fetch token prices.\n */\nexport class CodefiTokenPricesServiceV2\n implements\n AbstractTokenPricesService<SupportedChainId, Hex, SupportedCurrency>\n{\n #tokenPricePolicy: IPolicy;\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @param options - Constructor options\n * @param options.degradedThreshold - The threshold between \"normal\" and \"degrated\" service,\n * in milliseconds.\n * @param options.retries - Number of retry attempts for each token price update.\n * @param options.maximumConsecutiveFailures - The maximum number of consecutive failures\n * allowed before breaking the circuit and pausing further updates.\n * @param options.onBreak - An event handler for when the circuit breaks, useful for capturing\n * metrics about network failures.\n * @param options.onDegraded - An event handler for when the circuit remains closed, but requests\n * are failing or resolving too slowly (i.e. resolving more slowly than the `degradedThreshold).\n * @param options.circuitBreakDuration - The amount of time to wait when the circuit breaks\n * from too many consecutive failures.\n */\n constructor({\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n retries = DEFAULT_TOKEN_PRICE_RETRIES,\n maximumConsecutiveFailures = DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES,\n onBreak,\n onDegraded,\n circuitBreakDuration = 30 * 60 * 1000,\n }: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n } = {}) {\n // Construct a policy that will retry each update, and halt further updates\n // for a certain period after too many consecutive failures.\n const retryPolicy = retry(handleAll, {\n maxAttempts: retries,\n backoff: new ExponentialBackoff(),\n });\n const circuitBreakerPolicy = circuitBreaker(handleAll, {\n halfOpenAfter: circuitBreakDuration,\n breaker: new ConsecutiveBreaker(maximumConsecutiveFailures),\n });\n if (onBreak) {\n circuitBreakerPolicy.onBreak(onBreak);\n }\n if (onDegraded) {\n retryPolicy.onGiveUp(() => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n onDegraded();\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (\n circuitBreakerPolicy.state === CircuitState.Closed &&\n duration > degradedThreshold\n ) {\n onDegraded();\n }\n });\n }\n this.#tokenPricePolicy = wrap(retryPolicy, circuitBreakerPolicy);\n }\n\n /**\n * Retrieves prices in the given currency for the tokens identified by the\n * given addresses which are expected to live on the given chain.\n *\n * @param args - The arguments to function.\n * @param args.chainId - An EIP-155 chain ID.\n * @param args.tokenAddresses - Addresses for tokens that live on the chain.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n async fetchTokenPrices({\n chainId,\n tokenAddresses,\n currency,\n }: {\n chainId: SupportedChainId;\n tokenAddresses: Hex[];\n currency: SupportedCurrency;\n }): Promise<Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>> {\n const chainIdAsNumber = hexToNumber(chainId);\n\n const url = new URL(`${BASE_URL}/chains/${chainIdAsNumber}/spot-prices`);\n url.searchParams.append(\n 'tokenAddresses',\n [ZERO_ADDRESS, ...tokenAddresses].join(','),\n );\n url.searchParams.append('vsCurrency', currency);\n url.searchParams.append('includeMarketData', 'true');\n\n const addressCryptoDataMap: MarketDataByTokenAddress =\n await this.#tokenPricePolicy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n );\n\n return [ZERO_ADDRESS, ...tokenAddresses].reduce(\n (\n obj: Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>,\n tokenAddress,\n ) => {\n // The Price API lowercases both currency and token addresses, so we have\n // to keep track of them and make sure we return the original versions.\n const lowercasedTokenAddress =\n tokenAddress.toLowerCase() as Lowercase<Hex>;\n\n const marketData = addressCryptoDataMap[lowercasedTokenAddress];\n\n if (!marketData) {\n return obj;\n }\n\n const token: TokenPrice<Hex, SupportedCurrency> = {\n tokenAddress,\n currency,\n ...marketData,\n };\n\n return {\n ...obj,\n [tokenAddress]: token,\n };\n },\n {},\n ) as Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>;\n }\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is SupportedChainId {\n const supportedChainIds: readonly string[] = SUPPORTED_CHAIN_IDS;\n return typeof chainId === 'string' && supportedChainIds.includes(chainId);\n }\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check. If a string, can be either\n * lowercase or uppercase.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is SupportedCurrency {\n const supportedCurrencies: readonly string[] = SUPPORTED_CURRENCIES;\n return (\n typeof currency === 'string' &&\n supportedCurrencies.includes(currency.toLowerCase())\n );\n }\n}\n"]}
@@ -182,7 +182,7 @@ async function fetchTokenContractExchangeRates({
182
182
  (obj, [tokenAddress, tokenPrice]) => {
183
183
  return {
184
184
  ...obj,
185
- [toChecksumHexAddress(tokenAddress)]: tokenPrice?.value
185
+ [toChecksumHexAddress(tokenAddress)]: tokenPrice?.price
186
186
  };
187
187
  },
188
188
  {}
@@ -206,4 +206,4 @@ export {
206
206
  reduceInBatchesSerially,
207
207
  fetchTokenContractExchangeRates
208
208
  };
209
- //# sourceMappingURL=chunk-Q5JRBGWO.mjs.map
209
+ //# sourceMappingURL=chunk-VELPHITE.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/assetsUtil.ts"],"sourcesContent":["import type { BigNumber } from '@ethersproject/bignumber';\nimport {\n convertHexToDecimal,\n toChecksumHexAddress,\n} from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\nimport { remove0x } from '@metamask/utils';\nimport BN from 'bn.js';\nimport { CID } from 'multiformats/cid';\n\nimport type { Nft, NftMetadata } from './NftController';\nimport type { AbstractTokenPricesService } from './token-prices-service';\nimport { type ContractExchangeRates } from './TokenRatesController';\n\n/**\n * The maximum number of token addresses that should be sent to the Price API in\n * a single request.\n */\nexport const TOKEN_PRICES_BATCH_SIZE = 30;\n\n/**\n * Compares nft metadata entries to any nft entry.\n * We need this method when comparing a new fetched nft metadata, in case a entry changed to a defined value,\n * there's a need to update the nft in state.\n *\n * @param newNftMetadata - Nft metadata object.\n * @param nft - Nft object to compare with.\n * @returns Whether there are differences.\n */\nexport function compareNftMetadata(newNftMetadata: NftMetadata, nft: Nft) {\n const keys: (keyof NftMetadata)[] = [\n 'image',\n 'backgroundColor',\n 'imagePreview',\n 'imageThumbnail',\n 'imageOriginal',\n 'animation',\n 'animationOriginal',\n 'externalLink',\n 'tokenURI',\n ];\n const differentValues = keys.reduce((value, key) => {\n if (newNftMetadata[key] && newNftMetadata[key] !== nft[key]) {\n return value + 1;\n }\n return value;\n }, 0);\n return differentValues > 0;\n}\n\nconst aggregatorNameByKey: Record<string, string> = {\n aave: 'Aave',\n bancor: 'Bancor',\n cmc: 'CMC',\n cryptocom: 'Crypto.com',\n coinGecko: 'CoinGecko',\n oneInch: '1inch',\n paraswap: 'Paraswap',\n pmm: 'PMM',\n zapper: 'Zapper',\n zerion: 'Zerion',\n zeroEx: '0x',\n synthetix: 'Synthetix',\n yearn: 'Yearn',\n apeswap: 'ApeSwap',\n binanceDex: 'BinanceDex',\n pancakeTop100: 'PancakeTop100',\n pancakeExtended: 'PancakeExtended',\n balancer: 'Balancer',\n quickswap: 'QuickSwap',\n matcha: 'Matcha',\n pangolinDex: 'PangolinDex',\n pangolinDexStableCoin: 'PangolinDexStableCoin',\n pangolinDexAvaxBridge: 'PangolinDexAvaxBridge',\n traderJoe: 'TraderJoe',\n airswapLight: 'AirswapLight',\n kleros: 'Kleros',\n};\n\n/**\n * Formats aggregator names to presentable format.\n *\n * @param aggregators - List of token list names in camelcase.\n * @returns Formatted aggregator names.\n */\nexport const formatAggregatorNames = (aggregators: string[]) => {\n return aggregators.map(\n (key) =>\n aggregatorNameByKey[key] ||\n `${key[0].toUpperCase()}${key.substring(1, key.length)}`,\n );\n};\n\n/**\n * Format token list assets to use image proxy from Codefi.\n *\n * @param params - Object that contains chainID and tokenAddress.\n * @param params.chainId - ChainID of network in 0x-prefixed hexadecimal format.\n * @param params.tokenAddress - Address of token in mixed or lowercase.\n * @returns Formatted image url\n */\nexport const formatIconUrlWithProxy = ({\n chainId,\n tokenAddress,\n}: {\n chainId: Hex;\n tokenAddress: string;\n}) => {\n const chainIdDecimal = convertHexToDecimal(chainId).toString();\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n return `https://static.cx.metamask.io/api/v1/tokenIcons/${chainIdDecimal}/${tokenAddress.toLowerCase()}.png`;\n};\n\n/**\n * Networks where token detection is supported - Values are in hex format\n */\nexport enum SupportedTokenDetectionNetworks {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n mainnet = '0x1', // decimal: 1\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n bsc = '0x38', // decimal: 56\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n polygon = '0x89', // decimal: 137\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n avax = '0xa86a', // decimal: 43114\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n aurora = '0x4e454152', // decimal: 1313161554\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n linea_goerli = '0xe704', // decimal: 59140\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n linea_mainnet = '0xe708', // decimal: 59144\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n arbitrum = '0xa4b1', // decimal: 42161\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n optimism = '0xa', // decimal: 10\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n base = '0x2105', // decimal: 8453\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n zksync = '0x144', // decimal: 324\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n cronos = '0x19', // decimal: 25\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n celo = '0xa4ec', // decimal: 42220\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n gnosis = '0x64', // decimal: 100\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n fantom = '0xfa', // decimal: 250\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n polygon_zkevm = '0x44d', // decimal: 1101\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n moonbeam = '0x504', // decimal: 1284\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n moonriver = '0x505', // decimal: 1285\n}\n\n/**\n * Check if token detection is enabled for certain networks.\n *\n * @param chainId - ChainID of network\n * @returns Whether the current network supports token detection\n */\nexport function isTokenDetectionSupportedForNetwork(chainId: Hex): boolean {\n return Object.values<Hex>(SupportedTokenDetectionNetworks).includes(chainId);\n}\n\n/**\n * Check if token list polling is enabled for a given network.\n * Currently this method is used to support e2e testing for consumers of this package.\n *\n * @param chainId - ChainID of network\n * @returns Whether the current network supports tokenlists\n */\nexport function isTokenListSupportedForNetwork(chainId: Hex): boolean {\n return isTokenDetectionSupportedForNetwork(chainId);\n}\n\n/**\n * Removes IPFS protocol prefix from input string.\n *\n * @param ipfsUrl - An IPFS url (e.g. ipfs://{content id})\n * @returns IPFS content identifier and (possibly) path in a string\n * @throws Will throw if the url passed is not IPFS.\n */\nexport function removeIpfsProtocolPrefix(ipfsUrl: string) {\n if (ipfsUrl.startsWith('ipfs://ipfs/')) {\n return ipfsUrl.replace('ipfs://ipfs/', '');\n } else if (ipfsUrl.startsWith('ipfs://')) {\n return ipfsUrl.replace('ipfs://', '');\n }\n // this method should not be used with non-ipfs urls (i.e. startsWith('ipfs://') === true)\n throw new Error('this method should not be used with non ipfs urls');\n}\n\n/**\n * Extracts content identifier and path from an input string.\n *\n * @param ipfsUrl - An IPFS URL minus the IPFS protocol prefix\n * @returns IFPS content identifier (cid) and sub path as string.\n * @throws Will throw if the url passed is not ipfs.\n */\nexport function getIpfsCIDv1AndPath(ipfsUrl: string): {\n cid: string;\n path?: string;\n} {\n const url = removeIpfsProtocolPrefix(ipfsUrl);\n\n // check if there is a path\n // (CID is everything preceding first forward slash, path is everything after)\n const index = url.indexOf('/');\n const cid = index !== -1 ? url.substring(0, index) : url;\n const path = index !== -1 ? url.substring(index) : undefined;\n\n // We want to ensure that the CID is v1 (https://docs.ipfs.io/concepts/content-addressing/#identifier-formats)\n // because most cid v0s appear to be incompatible with IPFS subdomains\n return {\n cid: CID.parse(cid).toV1().toString(),\n path,\n };\n}\n\n/**\n * Formats URL correctly for use retrieving assets hosted on IPFS.\n *\n * @param ipfsGateway - The users preferred IPFS gateway (full URL or just host).\n * @param ipfsUrl - The IFPS URL pointed at the asset.\n * @param subdomainSupported - Boolean indicating whether the URL should be formatted with subdomains or not.\n * @returns A formatted URL, with the user's preferred IPFS gateway and format (subdomain or not), pointing to an asset hosted on IPFS.\n */\nexport function getFormattedIpfsUrl(\n ipfsGateway: string,\n ipfsUrl: string,\n subdomainSupported: boolean,\n): string {\n const { host, protocol, origin } = new URL(addUrlProtocolPrefix(ipfsGateway));\n if (subdomainSupported) {\n const { cid, path } = getIpfsCIDv1AndPath(ipfsUrl);\n return `${protocol}//${cid}.ipfs.${host}${path ?? ''}`;\n }\n const cidAndPath = removeIpfsProtocolPrefix(ipfsUrl);\n return `${origin}/ipfs/${cidAndPath}`;\n}\n\n/**\n * Adds URL protocol prefix to input URL string if missing.\n *\n * @param urlString - An IPFS URL.\n * @returns A URL with a https:// prepended.\n */\nexport function addUrlProtocolPrefix(urlString: string): string {\n if (!urlString.match(/(^http:\\/\\/)|(^https:\\/\\/)/u)) {\n return `https://${urlString}`;\n }\n return urlString;\n}\n\n/**\n * Converts an Ethers BigNumber to a BN.\n *\n * @param bigNumber - An Ethers BigNumber instance.\n * @returns A BN object.\n */\nexport function ethersBigNumberToBN(bigNumber: BigNumber): BN {\n return new BN(remove0x(bigNumber.toHexString()), 'hex');\n}\n\n/**\n * Partitions a list of values into groups that are at most `batchSize` in\n * length.\n *\n * @param values - The list of values.\n * @param args - The remaining arguments.\n * @param args.batchSize - The desired maximum number of values per batch.\n * @returns The list of batches.\n */\nexport function divideIntoBatches<Value>(\n values: Value[],\n { batchSize }: { batchSize: number },\n): Value[][] {\n const batches = [];\n for (let i = 0; i < values.length; i += batchSize) {\n batches.push(values.slice(i, i + batchSize));\n }\n return batches;\n}\n\n/**\n * Constructs an object from processing batches of the given values\n * sequentially.\n *\n * @param args - The arguments to this function.\n * @param args.values - A list of values to iterate over.\n * @param args.batchSize - The maximum number of values in each batch.\n * @param args.eachBatch - A function to call for each batch. This function is\n * similar to the function that `Array.prototype.reduce` takes, in that it\n * receives the object that is being built, each batch in the list of batches\n * and the index, and should return an updated version of the object.\n * @param args.initialResult - The initial value of the final data structure,\n * i.e., the value that will be fed into the first call of `eachBatch`.\n * @returns The built object.\n */\nexport async function reduceInBatchesSerially<\n Value,\n Result extends Record<PropertyKey, unknown>,\n>({\n values,\n batchSize,\n eachBatch,\n initialResult,\n}: {\n values: Value[];\n batchSize: number;\n eachBatch: (\n workingResult: Partial<Result>,\n batch: Value[],\n index: number,\n ) => Partial<Result> | Promise<Partial<Result>>;\n initialResult: Partial<Result>;\n}): Promise<Result> {\n const batches = divideIntoBatches(values, { batchSize });\n let workingResult = initialResult;\n for (const [index, batch] of batches.entries()) {\n workingResult = await eachBatch(workingResult, batch, index);\n }\n // There's no way around this — we have to assume that in the end, the result\n // matches the intended type.\n const finalResult = workingResult as Result;\n return finalResult;\n}\n\n/**\n * Retrieves token prices for a set of contract addresses in a specific currency and chainId.\n *\n * @param args - The arguments to function.\n * @param args.tokenPricesService - An object in charge of retrieving token prices.\n * @param args.nativeCurrency - The native currency to request price in.\n * @param args.tokenAddresses - The list of contract addresses.\n * @param args.chainId - The chainId of the tokens.\n * @returns The prices for the requested tokens.\n */\nexport async function fetchTokenContractExchangeRates({\n tokenPricesService,\n nativeCurrency,\n tokenAddresses,\n chainId,\n}: {\n tokenPricesService: AbstractTokenPricesService;\n nativeCurrency: string;\n tokenAddresses: Hex[];\n chainId: Hex;\n}): Promise<ContractExchangeRates> {\n const isChainIdSupported =\n tokenPricesService.validateChainIdSupported(chainId);\n const isCurrencySupported =\n tokenPricesService.validateCurrencySupported(nativeCurrency);\n\n if (!isChainIdSupported || !isCurrencySupported) {\n return {};\n }\n\n const tokenPricesByTokenAddress = await reduceInBatchesSerially<\n Hex,\n Awaited<ReturnType<AbstractTokenPricesService['fetchTokenPrices']>>\n >({\n values: [...tokenAddresses].sort(),\n batchSize: TOKEN_PRICES_BATCH_SIZE,\n eachBatch: async (allTokenPricesByTokenAddress, batch) => {\n const tokenPricesByTokenAddressForBatch =\n await tokenPricesService.fetchTokenPrices({\n tokenAddresses: batch,\n chainId,\n currency: nativeCurrency,\n });\n\n return {\n ...allTokenPricesByTokenAddress,\n ...tokenPricesByTokenAddressForBatch,\n };\n },\n initialResult: {},\n });\n\n return Object.entries(tokenPricesByTokenAddress).reduce(\n (obj, [tokenAddress, tokenPrice]) => {\n return {\n ...obj,\n [toChecksumHexAddress(tokenAddress)]: tokenPrice?.price,\n };\n },\n {},\n );\n}\n"],"mappings":";AACA;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,gBAAgB;AACzB,OAAO,QAAQ;AACf,SAAS,WAAW;AAUb,IAAM,0BAA0B;AAWhC,SAAS,mBAAmB,gBAA6B,KAAU;AACxE,QAAM,OAA8B;AAAA,IAClC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,QAAM,kBAAkB,KAAK,OAAO,CAAC,OAAO,QAAQ;AAClD,QAAI,eAAe,GAAG,KAAK,eAAe,GAAG,MAAM,IAAI,GAAG,GAAG;AAC3D,aAAO,QAAQ;AAAA,IACjB;AACA,WAAO;AA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AAG;AAAA,QACH,GAAG;AAAA,MACL;AAAA,IACF;AAAA,IACA,eAAe,CAAC;AAAA,EAClB,CAAC;AAED,SAAO,OAAO,QAAQ,yBAAyB,EAAE;AAAA,IAC/C,CAAC,KAAK,CAAC,cAAc,UAAU,MAAM;AACnC,aAAO;AAAA,QACL,GAAG;AAAA,QACH,CAAC,qBAAqB,YAAY,CAAC,GAAG,YAAY;AAAA,MACpD;AAAA,IACF;AAAA,IACA,CAAC;AAAA,EACH;AACF;","names":["SupportedTokenDetectionNetworks"]}
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2
2
 
3
- var _chunkNEXY7SE2js = require('./chunk-NEXY7SE2.js');
3
+ var _chunkNYVA7ZTQjs = require('./chunk-NYVA7ZTQ.js');
4
4
 
5
5
 
6
6
 
@@ -99,7 +99,7 @@ var TokenDetectionController = class extends _pollingcontroller.StaticIntervalPo
99
99
  _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _networkClientId, networkClientId);
100
100
  const { useTokenDetection: defaultUseTokenDetection } = this.messagingSystem.call("PreferencesController:getState");
101
101
  _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _isDetectionEnabledFromPreferences, defaultUseTokenDetection);
102
- _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _isDetectionEnabledForNetwork, _chunkNEXY7SE2js.isTokenDetectionSupportedForNetwork.call(void 0, chainId));
102
+ _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _isDetectionEnabledForNetwork, _chunkNYVA7ZTQjs.isTokenDetectionSupportedForNetwork.call(void 0, chainId));
103
103
  _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _getBalancesInSingleCall, getBalancesInSingleCall);
104
104
  _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _trackMetaMetricsEvent, trackMetaMetricsEvent);
105
105
  const { isUnlocked } = this.messagingSystem.call(
@@ -169,7 +169,7 @@ var TokenDetectionController = class extends _pollingcontroller.StaticIntervalPo
169
169
  const { chainId, networkClientId: selectedNetworkClientId } = _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getCorrectChainIdAndNetworkClientId, getCorrectChainIdAndNetworkClientId_fn).call(this, networkClientId);
170
170
  const chainIdAgainstWhichToDetect = chainId;
171
171
  const networkClientIdAgainstWhichToDetect = selectedNetworkClientId;
172
- if (!_chunkNEXY7SE2js.isTokenDetectionSupportedForNetwork.call(void 0, chainIdAgainstWhichToDetect)) {
172
+ if (!_chunkNYVA7ZTQjs.isTokenDetectionSupportedForNetwork.call(void 0, chainIdAgainstWhichToDetect)) {
173
173
  return;
174
174
  }
175
175
  if (!_chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _isDetectionEnabledFromPreferences) && chainIdAgainstWhichToDetect !== _controllerutils.ChainId.mainnet) {
@@ -215,6 +215,8 @@ registerEventListeners_fn = function() {
215
215
  });
216
216
  this.messagingSystem.subscribe(
217
217
  "TokenListController:stateChange",
218
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
219
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
218
220
  async ({ tokenList }) => {
219
221
  const hasTokens = Object.keys(tokenList).length;
220
222
  if (hasTokens) {
@@ -224,6 +226,8 @@ registerEventListeners_fn = function() {
224
226
  );
225
227
  this.messagingSystem.subscribe(
226
228
  "PreferencesController:stateChange",
229
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
230
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
227
231
  async ({ selectedAddress: newSelectedAddress, useTokenDetection }) => {
228
232
  const isSelectedAddressChanged = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _selectedAddress) !== newSelectedAddress;
229
233
  const isDetectionChangedFromPreferences = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _isDetectionEnabledFromPreferences) !== useTokenDetection;
@@ -238,6 +242,8 @@ registerEventListeners_fn = function() {
238
242
  );
239
243
  this.messagingSystem.subscribe(
240
244
  "AccountsController:selectedAccountChange",
245
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
246
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
241
247
  async ({ address: newSelectedAddress }) => {
242
248
  const isSelectedAddressChanged = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _selectedAddress) !== newSelectedAddress;
243
249
  if (isSelectedAddressChanged) {
@@ -250,10 +256,12 @@ registerEventListeners_fn = function() {
250
256
  );
251
257
  this.messagingSystem.subscribe(
252
258
  "NetworkController:networkDidChange",
259
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
260
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
253
261
  async ({ selectedNetworkClientId }) => {
254
262
  const isNetworkClientIdChanged = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _networkClientId) !== selectedNetworkClientId;
255
263
  const { chainId: newChainId } = _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getCorrectChainIdAndNetworkClientId, getCorrectChainIdAndNetworkClientId_fn).call(this, selectedNetworkClientId);
256
- _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _isDetectionEnabledForNetwork, _chunkNEXY7SE2js.isTokenDetectionSupportedForNetwork.call(void 0, newChainId));
264
+ _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _isDetectionEnabledForNetwork, _chunkNYVA7ZTQjs.isTokenDetectionSupportedForNetwork.call(void 0, newChainId));
257
265
  if (isNetworkClientIdChanged && _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _isDetectionEnabledForNetwork)) {
258
266
  _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _networkClientId, selectedNetworkClientId);
259
267
  await _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _restartTokenDetection, restartTokenDetection_fn).call(this, {
@@ -384,7 +392,11 @@ addDetectedTokens_fn = async function({
384
392
  category: "Wallet",
385
393
  properties: {
386
394
  tokens: eventTokensDetails,
395
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
396
+ // eslint-disable-next-line @typescript-eslint/naming-convention
387
397
  token_standard: "ERC20",
398
+ // TODO: Either fix this lint violation or explain why it's necessary to ignore.
399
+ // eslint-disable-next-line @typescript-eslint/naming-convention
388
400
  asset_type: "TOKEN"
389
401
  }
390
402
  });
@@ -408,4 +420,4 @@ var TokenDetectionController_default = TokenDetectionController;
408
420
 
409
421
 
410
422
  exports.isEqualCaseInsensitive = isEqualCaseInsensitive; exports.STATIC_MAINNET_TOKEN_LIST = STATIC_MAINNET_TOKEN_LIST; exports.controllerName = controllerName; exports.TokenDetectionController = TokenDetectionController; exports.TokenDetectionController_default = TokenDetectionController_default;
411
- //# sourceMappingURL=chunk-HDI4L2DD.js.map
423
+ //# sourceMappingURL=chunk-VZF43NDM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/TokenDetectionController.ts"],"names":[],"mappings":";;;;;;;;;;;AASA,OAAO,iBAAiB;AACxB,SAAS,SAAS,qBAAqB;AAavC,SAAS,uCAAuC;AAoBhD,IAAM,mBAAmB;AAYlB,SAAS,uBACd,QACA,QACS;AACT,MAAI,OAAO,WAAW,YAAY,OAAO,WAAW,UAAU;AAC5D,WAAO;AAAA,EACT;AACA,SAAO,OAAO,YAAY,MAAM,OAAO,YAAY;AACrD;AAeO,IAAM,4BAA4B,OAAO;AAAA,EAC9C;AACF,EAAE,OAA0B,CAAC,KAAK,CAAC,MAAM,QAAQ,MAAM;AACrD,QAAM,EAAE,MAAM,OAAO,QAAQ,GAAG,cAAc,IAAI;AAClD,SAAO;AAAA,IACL,GAAG;AAAA,IACH,CAAC,KAAK,YAAY,CAAC,GAAG;AAAA,MACpB,GAAG;AAAA,MACH,SAAS,KAAK,YAAY;AAAA,MAC1B,SAAS,mBAAmB,IAAI;AAAA,MAChC,aAAa,CAAC;AAAA,IAChB;AAAA,EACF;AACF,GAAG,CAAC,CAAC;AAEE,IAAM,iBAAiB;AA7F9B;AAoJO,IAAM,2BAAN,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K,GAAG,MAAM,MAAM,mBAAmB,EAAE;AAC5D,wBAAkB,KAAK;AAAA,QACrB,SAAS;AAAA,QACT;AAAA,QACA;AAAA,QACA;AAAA,QACA,OAAO;AAAA,QACP,UAAU;AAAA,QACV;AAAA,MACF,CAAC;AAAA,IACH;AAEA,QAAI,kBAAkB,QAAQ;AAC5B,yBAAK,wBAAL,WAA4B;AAAA,QAC1B,OAAO;AAAA,QACP,UAAU;AAAA,QACV,YAAY;AAAA,UACV,QAAQ;AAAA;AAAA;AAAA,UAGR,gBAAgB;AAAA;AAAA;AAAA,UAGhB,YAAY;AAAA,QACd;AAAA,MACF;AAEA,YAAM,KAAK,gBAAgB;AAAA,QACzB;AAAA,QACA;AAAA,QACA;AAAA,UACE;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAGF,IAAO,mCAAQ","sourcesContent":["import type {\n AccountsControllerGetSelectedAccountAction,\n AccountsControllerSelectedAccountChangeEvent,\n} from '@metamask/accounts-controller';\nimport type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport contractMap from '@metamask/contract-metadata';\nimport { ChainId, safelyExecute } from '@metamask/controller-utils';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type {\n NetworkClientId,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetNetworkConfigurationByNetworkClientId,\n NetworkControllerGetStateAction,\n NetworkControllerNetworkDidChangeEvent,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type {\n PreferencesControllerGetStateAction,\n PreferencesControllerStateChangeEvent,\n} from '@metamask/preferences-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport type { AssetsContractController } from './AssetsContractController';\nimport { isTokenDetectionSupportedForNetwork } from './assetsUtil';\nimport type {\n GetTokenListState,\n TokenListMap,\n TokenListStateChange,\n} from './TokenListController';\nimport type { Token } from './TokenRatesController';\nimport type {\n TokensControllerAddDetectedTokensAction,\n TokensControllerGetStateAction,\n} from './TokensController';\n\nconst DEFAULT_INTERVAL = 180000;\n\n/**\n * Compare 2 given strings and return boolean\n * eg: \"foo\" and \"FOO\" => true\n * eg: \"foo\" and \"bar\" => false\n * eg: \"foo\" and 123 => false\n *\n * @param value1 - first string to compare\n * @param value2 - first string to compare\n * @returns true if 2 strings are identical when they are lowercase\n */\nexport function isEqualCaseInsensitive(\n value1: string,\n value2: string,\n): boolean {\n if (typeof value1 !== 'string' || typeof value2 !== 'string') {\n return false;\n }\n return value1.toLowerCase() === value2.toLowerCase();\n}\n\ntype LegacyToken = {\n name: string;\n logo: `${string}.svg`;\n symbol: string;\n decimals: number;\n erc20?: boolean;\n erc721?: boolean;\n};\n\ntype TokenDetectionMap = {\n [P in keyof TokenListMap]: Omit<TokenListMap[P], 'occurrences'>;\n};\n\nexport const STATIC_MAINNET_TOKEN_LIST = Object.entries<LegacyToken>(\n contractMap,\n).reduce<TokenDetectionMap>((acc, [base, contract]) => {\n const { logo, erc20, erc721, ...tokenMetadata } = contract;\n return {\n ...acc,\n [base.toLowerCase()]: {\n ...tokenMetadata,\n address: base.toLowerCase(),\n iconUrl: `images/contract/${logo}`,\n aggregators: [],\n },\n };\n}, {});\n\nexport const controllerName = 'TokenDetectionController';\n\nexport type TokenDetectionState = Record<never, never>;\n\nexport type TokenDetectionControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n TokenDetectionState\n>;\n\nexport type TokenDetectionControllerActions =\n TokenDetectionControllerGetStateAction;\n\nexport type AllowedActions =\n | AccountsControllerGetSelectedAccountAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetNetworkConfigurationByNetworkClientId\n | NetworkControllerGetStateAction\n | GetTokenListState\n | KeyringControllerGetStateAction\n | PreferencesControllerGetStateAction\n | TokensControllerGetStateAction\n | TokensControllerAddDetectedTokensAction;\n\nexport type TokenDetectionControllerStateChangeEvent =\n ControllerStateChangeEvent<typeof controllerName, TokenDetectionState>;\n\nexport type TokenDetectionControllerEvents =\n TokenDetectionControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | AccountsControllerSelectedAccountChangeEvent\n | NetworkControllerNetworkDidChangeEvent\n | TokenListStateChange\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n | PreferencesControllerStateChangeEvent;\n\nexport type TokenDetectionControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n TokenDetectionControllerActions | AllowedActions,\n TokenDetectionControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Controller that passively polls on a set interval for Tokens auto detection\n * @property intervalId - Polling interval used to fetch new token rates\n * @property selectedAddress - Vault selected address\n * @property networkClientId - The network client ID of the current selected network\n * @property disabled - Boolean to track if network requests are blocked\n * @property isUnlocked - Boolean to track if the keyring state is unlocked\n * @property isDetectionEnabledFromPreferences - Boolean to track if detection is enabled from PreferencesController\n * @property isDetectionEnabledForNetwork - Boolean to track if detected is enabled for current network\n */\nexport class TokenDetectionController extends StaticIntervalPollingController<\n typeof controllerName,\n TokenDetectionState,\n TokenDetectionControllerMessenger\n> {\n #intervalId?: ReturnType<typeof setTimeout>;\n\n #selectedAddress: string;\n\n #networkClientId: NetworkClientId;\n\n #tokenList: TokenDetectionMap = {};\n\n #disabled: boolean;\n\n #isUnlocked: boolean;\n\n #isDetectionEnabledFromPreferences: boolean;\n\n #isDetectionEnabledForNetwork: boolean;\n\n readonly #getBalancesInSingleCall: AssetsContractController['getBalancesInSingleCall'];\n\n readonly #trackMetaMetricsEvent: (options: {\n event: string;\n category: string;\n properties: {\n tokens: string[];\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n token_standard: string;\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n asset_type: string;\n };\n }) => void;\n\n /**\n * Creates a TokenDetectionController instance.\n *\n * @param options - The controller options.\n * @param options.messenger - The controller messaging system.\n * @param options.disabled - If set to true, all network requests are blocked.\n * @param options.interval - Polling interval used to fetch new token rates\n * @param options.selectedAddress - Vault selected address\n * @param options.getBalancesInSingleCall - Gets the balances of a list of tokens for the given address.\n * @param options.trackMetaMetricsEvent - Sets options for MetaMetrics event tracking.\n */\n constructor({\n selectedAddress,\n interval = DEFAULT_INTERVAL,\n disabled = true,\n getBalancesInSingleCall,\n trackMetaMetricsEvent,\n messenger,\n }: {\n selectedAddress?: string;\n interval?: number;\n disabled?: boolean;\n getBalancesInSingleCall: AssetsContractController['getBalancesInSingleCall'];\n trackMetaMetricsEvent: (options: {\n event: string;\n category: string;\n properties: {\n tokens: string[];\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n token_standard: string;\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n asset_type: string;\n };\n }) => void;\n messenger: TokenDetectionControllerMessenger;\n }) {\n super({\n name: controllerName,\n messenger,\n state: {},\n metadata: {},\n });\n\n this.#disabled = disabled;\n this.setIntervalLength(interval);\n\n this.#selectedAddress =\n selectedAddress ??\n this.messagingSystem.call('AccountsController:getSelectedAccount')\n .address;\n\n const { chainId, networkClientId } =\n this.#getCorrectChainIdAndNetworkClientId();\n this.#networkClientId = networkClientId;\n\n const { useTokenDetection: defaultUseTokenDetection } =\n this.messagingSystem.call('PreferencesController:getState');\n this.#isDetectionEnabledFromPreferences = defaultUseTokenDetection;\n this.#isDetectionEnabledForNetwork =\n isTokenDetectionSupportedForNetwork(chainId);\n\n this.#getBalancesInSingleCall = getBalancesInSingleCall;\n\n this.#trackMetaMetricsEvent = trackMetaMetricsEvent;\n\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.#registerEventListeners();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system subscriptions to controller events.\n */\n #registerEventListeners() {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.messagingSystem.subscribe('KeyringController:unlock', async () => {\n this.#isUnlocked = true;\n await this.#restartTokenDetection();\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n this.#stopPolling();\n });\n\n this.messagingSystem.subscribe(\n 'TokenListController:stateChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async ({ tokenList }) => {\n const hasTokens = Object.keys(tokenList).length;\n\n if (hasTokens) {\n await this.#restartTokenDetection();\n }\n },\n );\n\n this.messagingSystem.subscribe(\n 'PreferencesController:stateChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async ({ selectedAddress: newSelectedAddress, useTokenDetection }) => {\n const isSelectedAddressChanged =\n this.#selectedAddress !== newSelectedAddress;\n const isDetectionChangedFromPreferences =\n this.#isDetectionEnabledFromPreferences !== useTokenDetection;\n\n this.#selectedAddress = newSelectedAddress;\n this.#isDetectionEnabledFromPreferences = useTokenDetection;\n\n if (isSelectedAddressChanged || isDetectionChangedFromPreferences) {\n await this.#restartTokenDetection({\n selectedAddress: this.#selectedAddress,\n });\n }\n },\n );\n\n this.messagingSystem.subscribe(\n 'AccountsController:selectedAccountChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async ({ address: newSelectedAddress }) => {\n const isSelectedAddressChanged =\n this.#selectedAddress !== newSelectedAddress;\n if (isSelectedAddressChanged) {\n this.#selectedAddress = newSelectedAddress;\n await this.#restartTokenDetection({\n selectedAddress: this.#selectedAddress,\n });\n }\n },\n );\n\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async ({ selectedNetworkClientId }) => {\n const isNetworkClientIdChanged =\n this.#networkClientId !== selectedNetworkClientId;\n\n const { chainId: newChainId } =\n this.#getCorrectChainIdAndNetworkClientId(selectedNetworkClientId);\n this.#isDetectionEnabledForNetwork =\n isTokenDetectionSupportedForNetwork(newChainId);\n\n if (isNetworkClientIdChanged && this.#isDetectionEnabledForNetwork) {\n this.#networkClientId = selectedNetworkClientId;\n await this.#restartTokenDetection({\n networkClientId: this.#networkClientId,\n });\n }\n },\n );\n }\n\n /**\n * Allows controller to make active and passive polling requests\n */\n enable(): void {\n this.#disabled = false;\n }\n\n /**\n * Blocks controller from making network calls\n */\n disable(): void {\n this.#disabled = true;\n }\n\n /**\n * Internal isActive state\n * @type {boolean}\n */\n get isActive(): boolean {\n return !this.#disabled && this.#isUnlocked;\n }\n\n /**\n * Start polling for detected tokens.\n */\n async start(): Promise<void> {\n this.enable();\n await this.#startPolling();\n }\n\n /**\n * Stop polling for detected tokens.\n */\n stop(): void {\n this.disable();\n this.#stopPolling();\n }\n\n #stopPolling(): void {\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n }\n }\n\n /**\n * Starts a new polling interval.\n */\n async #startPolling(): Promise<void> {\n if (!this.isActive) {\n return;\n }\n this.#stopPolling();\n await this.detectTokens();\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.#intervalId = setInterval(async () => {\n await this.detectTokens();\n }, this.getIntervalLength());\n }\n\n #getCorrectChainIdAndNetworkClientId(networkClientId?: NetworkClientId): {\n chainId: Hex;\n networkClientId: NetworkClientId;\n } {\n if (networkClientId) {\n const networkConfiguration = this.messagingSystem.call(\n 'NetworkController:getNetworkConfigurationByNetworkClientId',\n networkClientId,\n );\n if (networkConfiguration) {\n return {\n chainId: networkConfiguration.chainId,\n networkClientId,\n };\n }\n }\n const { selectedNetworkClientId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n const {\n configuration: { chainId },\n } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n return {\n chainId,\n networkClientId: selectedNetworkClientId,\n };\n }\n\n async _executePoll(\n networkClientId: NetworkClientId,\n options: { address: string },\n ): Promise<void> {\n if (!this.isActive) {\n return;\n }\n await this.detectTokens({\n networkClientId,\n selectedAddress: options.address,\n });\n }\n\n /**\n * Restart token detection polling period and call detectNewTokens\n * in case of address change or user session initialization.\n *\n * @param options - Options for restart token detection.\n * @param options.selectedAddress - the selectedAddress against which to detect for token balances\n * @param options.networkClientId - The ID of the network client to use.\n */\n async #restartTokenDetection({\n selectedAddress,\n networkClientId,\n }: {\n selectedAddress?: string;\n networkClientId?: NetworkClientId;\n } = {}): Promise<void> {\n await this.detectTokens({\n networkClientId,\n selectedAddress,\n });\n this.setIntervalLength(DEFAULT_INTERVAL);\n }\n\n /**\n * For each token in the token list provided by the TokenListController, checks the token's balance for the selected account address on the active network.\n * On mainnet, if token detection is disabled in preferences, ERC20 token auto detection will be triggered for each contract address in the legacy token list from the @metamask/contract-metadata repo.\n *\n * @param options - Options for token detection.\n * @param options.networkClientId - The ID of the network client to use.\n * @param options.selectedAddress - the selectedAddress against which to detect for token balances.\n */\n async detectTokens({\n networkClientId,\n selectedAddress,\n }: {\n networkClientId?: NetworkClientId;\n selectedAddress?: string;\n } = {}): Promise<void> {\n if (!this.isActive) {\n return;\n }\n\n const addressAgainstWhichToDetect =\n selectedAddress ?? this.#selectedAddress;\n const { chainId, networkClientId: selectedNetworkClientId } =\n this.#getCorrectChainIdAndNetworkClientId(networkClientId);\n const chainIdAgainstWhichToDetect = chainId;\n const networkClientIdAgainstWhichToDetect = selectedNetworkClientId;\n\n if (!isTokenDetectionSupportedForNetwork(chainIdAgainstWhichToDetect)) {\n return;\n }\n if (\n !this.#isDetectionEnabledFromPreferences &&\n chainIdAgainstWhichToDetect !== ChainId.mainnet\n ) {\n return;\n }\n const isTokenDetectionInactiveInMainnet =\n !this.#isDetectionEnabledFromPreferences &&\n chainIdAgainstWhichToDetect === ChainId.mainnet;\n const { tokensChainsCache } = this.messagingSystem.call(\n 'TokenListController:getState',\n );\n this.#tokenList = isTokenDetectionInactiveInMainnet\n ? STATIC_MAINNET_TOKEN_LIST\n : tokensChainsCache[chainIdAgainstWhichToDetect]?.data ?? {};\n\n for (const tokensSlice of this.#getSlicesOfTokensToDetect({\n chainId: chainIdAgainstWhichToDetect,\n selectedAddress: addressAgainstWhichToDetect,\n })) {\n await this.#addDetectedTokens({\n tokensSlice,\n selectedAddress: addressAgainstWhichToDetect,\n networkClientId: networkClientIdAgainstWhichToDetect,\n chainId: chainIdAgainstWhichToDetect,\n });\n }\n }\n\n #getSlicesOfTokensToDetect({\n chainId,\n selectedAddress,\n }: {\n chainId: Hex;\n selectedAddress: string;\n }): string[][] {\n const { allTokens, allDetectedTokens, allIgnoredTokens } =\n this.messagingSystem.call('TokensController:getState');\n const [tokensAddresses, detectedTokensAddresses, ignoredTokensAddresses] = [\n allTokens,\n allDetectedTokens,\n allIgnoredTokens,\n ].map((tokens) =>\n (tokens[chainId]?.[selectedAddress] ?? []).map((value) =>\n typeof value === 'string' ? value : value.address,\n ),\n );\n\n const tokensToDetect: string[] = [];\n for (const tokenAddress of Object.keys(this.#tokenList)) {\n if (\n [\n tokensAddresses,\n detectedTokensAddresses,\n ignoredTokensAddresses,\n ].every(\n (addresses) =>\n !addresses.find((address) =>\n isEqualCaseInsensitive(address, tokenAddress),\n ),\n )\n ) {\n tokensToDetect.push(tokenAddress);\n }\n }\n\n const slicesOfTokensToDetect = [];\n for (let i = 0, size = 1000; i < tokensToDetect.length; i += size) {\n slicesOfTokensToDetect.push(tokensToDetect.slice(i, i + size));\n }\n\n return slicesOfTokensToDetect;\n }\n\n async #addDetectedTokens({\n tokensSlice,\n selectedAddress,\n networkClientId,\n chainId,\n }: {\n tokensSlice: string[];\n selectedAddress: string;\n networkClientId: NetworkClientId;\n chainId: Hex;\n }): Promise<void> {\n await safelyExecute(async () => {\n const balances = await this.#getBalancesInSingleCall(\n selectedAddress,\n tokensSlice,\n networkClientId,\n );\n\n const tokensWithBalance: Token[] = [];\n const eventTokensDetails: string[] = [];\n for (const nonZeroTokenAddress of Object.keys(balances)) {\n const { decimals, symbol, aggregators, iconUrl, name } =\n this.#tokenList[nonZeroTokenAddress];\n eventTokensDetails.push(`${symbol} - ${nonZeroTokenAddress}`);\n tokensWithBalance.push({\n address: nonZeroTokenAddress,\n decimals,\n symbol,\n aggregators,\n image: iconUrl,\n isERC721: false,\n name,\n });\n }\n\n if (tokensWithBalance.length) {\n this.#trackMetaMetricsEvent({\n event: 'Token Detected',\n category: 'Wallet',\n properties: {\n tokens: eventTokensDetails,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n token_standard: 'ERC20',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n asset_type: 'TOKEN',\n },\n });\n\n await this.messagingSystem.call(\n 'TokensController:addDetectedTokens',\n tokensWithBalance,\n {\n selectedAddress,\n chainId,\n },\n );\n }\n });\n }\n}\n\nexport default TokenDetectionController;\n"]}