@metamask/assets-controllers 35.0.0 → 37.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 (105) hide show
  1. package/CHANGELOG.md +84 -1
  2. package/dist/AssetsContractController.js +6 -6
  3. package/dist/AssetsContractController.mjs +5 -5
  4. package/dist/NftController.js +3 -3
  5. package/dist/NftController.mjs +2 -2
  6. package/dist/NftDetectionController.js +5 -2
  7. package/dist/NftDetectionController.mjs +4 -1
  8. package/dist/Standards/ERC20Standard.js +3 -3
  9. package/dist/Standards/ERC20Standard.mjs +2 -2
  10. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js +3 -3
  11. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.mjs +2 -2
  12. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js +3 -3
  13. package/dist/Standards/NftStandards/ERC721/ERC721Standard.mjs +2 -2
  14. package/dist/TokenBalancesController.js +2 -2
  15. package/dist/TokenBalancesController.mjs +1 -1
  16. package/dist/TokenDetectionController.js +3 -3
  17. package/dist/TokenDetectionController.mjs +2 -2
  18. package/dist/TokenListController.js +4 -4
  19. package/dist/TokenListController.mjs +3 -3
  20. package/dist/TokenRatesController.js +3 -3
  21. package/dist/TokenRatesController.mjs +2 -2
  22. package/dist/TokensController.js +6 -6
  23. package/dist/TokensController.mjs +5 -5
  24. package/dist/assetsUtil.js +4 -2
  25. package/dist/assetsUtil.mjs +3 -1
  26. package/dist/{chunk-3GGCHDRG.js → chunk-2TZK6YZA.js} +92 -45
  27. package/dist/chunk-2TZK6YZA.js.map +1 -0
  28. package/dist/{chunk-GHKGU6GK.js → chunk-3LPQTUGG.js} +5 -5
  29. package/dist/{chunk-JEIAMJGS.mjs → chunk-3QDXAE2D.mjs} +2 -2
  30. package/dist/{chunk-2TSAUGE7.mjs → chunk-46KUC5FH.mjs} +2 -2
  31. package/dist/{chunk-4JLB5OIJ.mjs → chunk-54JUUBXY.mjs} +5 -5
  32. package/dist/{chunk-JBF4XEGR.js → chunk-5QLC2MHV.js} +5 -5
  33. package/dist/{chunk-2NQRWANM.js → chunk-ADJ3IFJH.js} +11 -11
  34. package/dist/{chunk-47CRHAUE.mjs → chunk-AX522TDL.mjs} +2 -2
  35. package/dist/{chunk-354SINOH.js → chunk-BBCZM5P4.js} +67 -3
  36. package/dist/chunk-BBCZM5P4.js.map +1 -0
  37. package/dist/{chunk-VELPHITE.mjs → chunk-BZEAPSD5.mjs} +11 -5
  38. package/dist/chunk-BZEAPSD5.mjs.map +1 -0
  39. package/dist/{chunk-2IIQTSLV.mjs → chunk-C7LNCQXM.mjs} +67 -3
  40. package/dist/chunk-C7LNCQXM.mjs.map +1 -0
  41. package/dist/{chunk-OMNBGY7O.mjs → chunk-CN53OZAM.mjs} +135 -79
  42. package/dist/chunk-CN53OZAM.mjs.map +1 -0
  43. package/dist/{chunk-GJCTAKK5.mjs → chunk-CUFSPB7T.mjs} +2 -2
  44. package/dist/{chunk-RIMQ5DR3.js → chunk-GHG3DOUK.js} +138 -82
  45. package/dist/chunk-GHG3DOUK.js.map +1 -0
  46. package/dist/{chunk-LBJTMJFA.js → chunk-ISK2VSBB.js} +4 -4
  47. package/dist/{chunk-6PPM4ETZ.js → chunk-JCR4H6YL.js} +3 -3
  48. package/dist/{chunk-6VQJFTNC.mjs → chunk-JJX7TMH5.mjs} +8 -11
  49. package/dist/chunk-JJX7TMH5.mjs.map +1 -0
  50. package/dist/{chunk-X4RMS365.js → chunk-K7A3EOIM.js} +3 -3
  51. package/dist/{chunk-UYH6NWKB.mjs → chunk-KPBNX6GP.mjs} +2 -2
  52. package/dist/{chunk-NYVA7ZTQ.js → chunk-MZI3SDQN.js} +14 -8
  53. package/dist/chunk-MZI3SDQN.js.map +1 -0
  54. package/dist/{chunk-56O7BVZV.mjs → chunk-S5CFNNOM.mjs} +2 -2
  55. package/dist/{chunk-ZX5G3X74.mjs → chunk-SK2B36Q4.mjs} +92 -45
  56. package/dist/chunk-SK2B36Q4.mjs.map +1 -0
  57. package/dist/{chunk-Y45HQET7.mjs → chunk-TFLYM4PY.mjs} +3 -3
  58. package/dist/{chunk-RPQ737HL.js → chunk-X2HRAVDO.js} +4 -4
  59. package/dist/{chunk-NHFZIY2K.js → chunk-YGGUAMHV.js} +7 -10
  60. package/dist/chunk-YGGUAMHV.js.map +1 -0
  61. package/dist/{chunk-7OZL6IDY.js → chunk-ZAR4BIOC.js} +7 -7
  62. package/dist/index.js +14 -16
  63. package/dist/index.mjs +13 -15
  64. package/dist/token-service.js +3 -3
  65. package/dist/token-service.mjs +2 -2
  66. package/dist/tsconfig.build.tsbuildinfo +1 -1
  67. package/dist/types/AssetsContractController.d.ts +93 -56
  68. package/dist/types/AssetsContractController.d.ts.map +1 -1
  69. package/dist/types/NftController.d.ts +18 -18
  70. package/dist/types/NftController.d.ts.map +1 -1
  71. package/dist/types/NftDetectionController.d.ts +35 -1
  72. package/dist/types/NftDetectionController.d.ts.map +1 -1
  73. package/dist/types/TokenBalancesController.d.ts +6 -8
  74. package/dist/types/TokenBalancesController.d.ts.map +1 -1
  75. package/dist/types/assetsUtil.d.ts +10 -3
  76. package/dist/types/assetsUtil.d.ts.map +1 -1
  77. package/dist/types/index.d.ts +3 -2
  78. package/dist/types/index.d.ts.map +1 -1
  79. package/package.json +21 -20
  80. package/dist/chunk-2IIQTSLV.mjs.map +0 -1
  81. package/dist/chunk-354SINOH.js.map +0 -1
  82. package/dist/chunk-3GGCHDRG.js.map +0 -1
  83. package/dist/chunk-6VQJFTNC.mjs.map +0 -1
  84. package/dist/chunk-NHFZIY2K.js.map +0 -1
  85. package/dist/chunk-NYVA7ZTQ.js.map +0 -1
  86. package/dist/chunk-OMNBGY7O.mjs.map +0 -1
  87. package/dist/chunk-RIMQ5DR3.js.map +0 -1
  88. package/dist/chunk-VELPHITE.mjs.map +0 -1
  89. package/dist/chunk-ZX5G3X74.mjs.map +0 -1
  90. /package/dist/{chunk-GHKGU6GK.js.map → chunk-3LPQTUGG.js.map} +0 -0
  91. /package/dist/{chunk-JEIAMJGS.mjs.map → chunk-3QDXAE2D.mjs.map} +0 -0
  92. /package/dist/{chunk-2TSAUGE7.mjs.map → chunk-46KUC5FH.mjs.map} +0 -0
  93. /package/dist/{chunk-4JLB5OIJ.mjs.map → chunk-54JUUBXY.mjs.map} +0 -0
  94. /package/dist/{chunk-JBF4XEGR.js.map → chunk-5QLC2MHV.js.map} +0 -0
  95. /package/dist/{chunk-2NQRWANM.js.map → chunk-ADJ3IFJH.js.map} +0 -0
  96. /package/dist/{chunk-47CRHAUE.mjs.map → chunk-AX522TDL.mjs.map} +0 -0
  97. /package/dist/{chunk-GJCTAKK5.mjs.map → chunk-CUFSPB7T.mjs.map} +0 -0
  98. /package/dist/{chunk-LBJTMJFA.js.map → chunk-ISK2VSBB.js.map} +0 -0
  99. /package/dist/{chunk-6PPM4ETZ.js.map → chunk-JCR4H6YL.js.map} +0 -0
  100. /package/dist/{chunk-X4RMS365.js.map → chunk-K7A3EOIM.js.map} +0 -0
  101. /package/dist/{chunk-UYH6NWKB.mjs.map → chunk-KPBNX6GP.mjs.map} +0 -0
  102. /package/dist/{chunk-56O7BVZV.mjs.map → chunk-S5CFNNOM.mjs.map} +0 -0
  103. /package/dist/{chunk-Y45HQET7.mjs.map → chunk-TFLYM4PY.mjs.map} +0 -0
  104. /package/dist/{chunk-RPQ737HL.js.map → chunk-X2HRAVDO.js.map} +0 -0
  105. /package/dist/{chunk-7OZL6IDY.js.map → chunk-ZAR4BIOC.js.map} +0 -0
@@ -1,17 +1,17 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2
2
 
3
- var _chunk6PPM4ETZjs = require('./chunk-6PPM4ETZ.js');
3
+ var _chunkJCR4H6YLjs = require('./chunk-JCR4H6YL.js');
4
4
 
5
5
 
6
- var _chunkJBF4XEGRjs = require('./chunk-JBF4XEGR.js');
6
+ var _chunk5QLC2MHVjs = require('./chunk-5QLC2MHV.js');
7
7
 
8
8
 
9
9
 
10
- var _chunkX4RMS365js = require('./chunk-X4RMS365.js');
10
+ var _chunkK7A3EOIMjs = require('./chunk-K7A3EOIM.js');
11
11
 
12
12
 
13
13
 
14
- var _chunkNYVA7ZTQjs = require('./chunk-NYVA7ZTQ.js');
14
+ var _chunkMZI3SDQNjs = require('./chunk-MZI3SDQN.js');
15
15
 
16
16
 
17
17
 
@@ -243,12 +243,12 @@ var TokensController = class extends _basecontroller.BaseController {
243
243
  address,
244
244
  symbol,
245
245
  decimals,
246
- image: image || _chunkNYVA7ZTQjs.formatIconUrlWithProxy.call(void 0, {
246
+ image: image || _chunkMZI3SDQNjs.formatIconUrlWithProxy.call(void 0, {
247
247
  chainId: currentChainId,
248
248
  tokenAddress: address
249
249
  }),
250
250
  isERC721,
251
- aggregators: _chunkNYVA7ZTQjs.formatAggregatorNames.call(void 0, tokenMetadata?.aggregators || []),
251
+ aggregators: _chunkMZI3SDQNjs.formatAggregatorNames.call(void 0, tokenMetadata?.aggregators || []),
252
252
  name
253
253
  };
254
254
  const previousIndex = newTokens.findIndex(
@@ -522,7 +522,7 @@ var TokensController = class extends _basecontroller.BaseController {
522
522
  }
523
523
  const provider = _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getProvider, getProvider_fn).call(this, networkClientId);
524
524
  const isErc1155 = await _controllerutils.safelyExecute.call(void 0,
525
- () => new (0, _chunkJBF4XEGRjs.ERC1155Standard)(provider).contractSupportsBase1155Interface(
525
+ () => new (0, _chunk5QLC2MHVjs.ERC1155Standard)(provider).contractSupportsBase1155Interface(
526
526
  asset.address
527
527
  )
528
528
  );
@@ -533,7 +533,7 @@ var TokensController = class extends _basecontroller.BaseController {
533
533
  `Contract ${asset.address} must match type ${type}, but was detected as ${_controllerutils.ERC1155}`
534
534
  );
535
535
  }
536
- const erc20 = new (0, _chunk6PPM4ETZjs.ERC20Standard)(provider);
536
+ const erc20 = new (0, _chunkJCR4H6YLjs.ERC20Standard)(provider);
537
537
  const [contractName, contractSymbol, contractDecimals] = await Promise.all([
538
538
  _controllerutils.safelyExecute.call(void 0, () => erc20.getTokenName(asset.address)),
539
539
  _controllerutils.safelyExecute.call(void 0, () => erc20.getTokenSymbol(asset.address)),
@@ -648,14 +648,14 @@ onSelectedAccountChange_fn = function(selectedAccount) {
648
648
  _fetchTokenMetadata = new WeakSet();
649
649
  fetchTokenMetadata_fn = async function(tokenAddress) {
650
650
  try {
651
- const token = await _chunkX4RMS365js.fetchTokenMetadata.call(void 0,
651
+ const token = await _chunkK7A3EOIMjs.fetchTokenMetadata.call(void 0,
652
652
  _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _chainId),
653
653
  tokenAddress,
654
654
  _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _abortController).signal
655
655
  );
656
656
  return token;
657
657
  } catch (error) {
658
- if (error instanceof Error && error.message.includes(_chunkX4RMS365js.TOKEN_METADATA_NO_SUPPORT_ERROR)) {
658
+ if (error instanceof Error && error.message.includes(_chunkK7A3EOIMjs.TOKEN_METADATA_NO_SUPPORT_ERROR)) {
659
659
  return void 0;
660
660
  }
661
661
  throw error;
@@ -810,4 +810,4 @@ var TokensController_default = TokensController;
810
810
 
811
811
 
812
812
  exports.getDefaultTokensState = getDefaultTokensState; exports.TokensController = TokensController; exports.TokensController_default = TokensController_default;
813
- //# sourceMappingURL=chunk-2NQRWANM.js.map
813
+ //# sourceMappingURL=chunk-ADJ3IFJH.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  isTokenListSupportedForNetwork
3
- } from "./chunk-VELPHITE.mjs";
3
+ } from "./chunk-BZEAPSD5.mjs";
4
4
 
5
5
  // src/token-service.ts
6
6
  import {
@@ -82,4 +82,4 @@ export {
82
82
  fetchTokenListByChainId,
83
83
  fetchTokenMetadata
84
84
  };
85
- //# sourceMappingURL=chunk-47CRHAUE.mjs.map
85
+ //# sourceMappingURL=chunk-AX522TDL.mjs.map
@@ -1,5 +1,8 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
+ var _chunkMZI3SDQNjs = require('./chunk-MZI3SDQN.js');
4
+
5
+
3
6
 
4
7
 
5
8
 
@@ -14,10 +17,15 @@ var _basecontroller = require('@metamask/base-controller');
14
17
 
15
18
 
16
19
 
20
+
21
+
17
22
  var _controllerutils = require('@metamask/controller-utils');
18
23
  var _utils = require('@metamask/utils');
19
24
  var controllerName = "NftDetectionController";
20
- var supportedNftDetectionNetworks = [_controllerutils.ChainId.mainnet];
25
+ var supportedNftDetectionNetworks = [
26
+ _controllerutils.ChainId.mainnet,
27
+ _controllerutils.ChainId["linea-mainnet"]
28
+ ];
21
29
  var BlockaidResultType = /* @__PURE__ */ ((BlockaidResultType2) => {
22
30
  BlockaidResultType2["Benign"] = "Benign";
23
31
  BlockaidResultType2["Spam"] = "Spam";
@@ -25,6 +33,7 @@ var BlockaidResultType = /* @__PURE__ */ ((BlockaidResultType2) => {
25
33
  BlockaidResultType2["Malicious"] = "Malicious";
26
34
  return BlockaidResultType2;
27
35
  })(BlockaidResultType || {});
36
+ var MAX_GET_COLLECTION_BATCH_SIZE = 20;
28
37
  var _disabled, _addNft, _getNftState, _inProcessNftFetchingUpdates, _onPreferencesControllerStateChange, onPreferencesControllerStateChange_fn, _getOwnerNftApi, getOwnerNftApi_fn, _getOwnerNfts, getOwnerNfts_fn;
29
38
  var NftDetectionController = class extends _basecontroller.BaseController {
30
39
  /**
@@ -134,6 +143,60 @@ var NftDetectionController = class extends _basecontroller.BaseController {
134
143
  apiNfts = resultNftApi.tokens.filter(
135
144
  (elm) => elm.token.isSpam === false && (elm.blockaidResult?.result_type ? elm.blockaidResult?.result_type === "Benign" /* Benign */ : true)
136
145
  );
146
+ const collections = apiNfts.reduce((acc, currValue) => {
147
+ if (!acc.includes(currValue.token.contract) && currValue.token.contract === currValue?.token?.collection?.id) {
148
+ acc.push(currValue.token.contract);
149
+ }
150
+ return acc;
151
+ }, []);
152
+ if (collections.length !== 0) {
153
+ const collectionResponse = await _chunkMZI3SDQNjs.reduceInBatchesSerially.call(void 0, {
154
+ values: collections,
155
+ batchSize: MAX_GET_COLLECTION_BATCH_SIZE,
156
+ eachBatch: async (allResponses, batch) => {
157
+ const params = new URLSearchParams(
158
+ batch.map((s) => ["contract", s])
159
+ );
160
+ params.append("chainId", "1");
161
+ const collectionResponseForBatch = await _controllerutils.fetchWithErrorHandling.call(void 0,
162
+ {
163
+ url: `${_controllerutils.NFT_API_BASE_URL}/collections?${params.toString()}`,
164
+ options: {
165
+ headers: {
166
+ Version: _controllerutils.NFT_API_VERSION
167
+ }
168
+ },
169
+ timeout: _controllerutils.NFT_API_TIMEOUT
170
+ }
171
+ );
172
+ return {
173
+ ...allResponses,
174
+ ...collectionResponseForBatch
175
+ };
176
+ },
177
+ initialResult: {}
178
+ });
179
+ if (collectionResponse.collections?.length) {
180
+ apiNfts.forEach((singleNFT) => {
181
+ const found = collectionResponse.collections.find(
182
+ (elm) => elm.id?.toLowerCase() === singleNFT.token.contract.toLowerCase()
183
+ );
184
+ if (found) {
185
+ singleNFT.token = {
186
+ ...singleNFT.token,
187
+ collection: {
188
+ ...singleNFT.token.collection ?? {},
189
+ creator: found?.creator,
190
+ openseaVerificationStatus: found?.openseaVerificationStatus,
191
+ contractDeployedAt: found.contractDeployedAt,
192
+ ownerCount: found.ownerCount,
193
+ topBid: found.topBid
194
+ }
195
+ };
196
+ }
197
+ });
198
+ }
199
+ }
137
200
  const addNftPromises = apiNfts.map(async (nft) => {
138
201
  const {
139
202
  tokenId,
@@ -232,5 +295,6 @@ var NftDetectionController_default = NftDetectionController;
232
295
 
233
296
 
234
297
 
235
- exports.BlockaidResultType = BlockaidResultType; exports.NftDetectionController = NftDetectionController; exports.NftDetectionController_default = NftDetectionController_default;
236
- //# sourceMappingURL=chunk-354SINOH.js.map
298
+
299
+ exports.BlockaidResultType = BlockaidResultType; exports.MAX_GET_COLLECTION_BATCH_SIZE = MAX_GET_COLLECTION_BATCH_SIZE; exports.NftDetectionController = NftDetectionController; exports.NftDetectionController_default = NftDetectionController_default;
300
+ //# sourceMappingURL=chunk-BBCZM5P4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/NftDetectionController.ts"],"names":["BlockaidResultType"],"mappings":";;;;;;;;;;;AAGA,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAaP,SAAS,6BAAuC;AAUhD,IAAM,iBAAiB;AAsBvB,IAAM,gCAAuC;AAAA,EAC3C,QAAQ;AAAA,EACR,QAAQ,eAAe;AACzB;AA0JO,IAAK,qBAAL,kBAAKA,wBAAL;AACL,EAAAA,oBAAA,YAAS;AACT,EAAAA,oBAAA,UAAO;AACP,EAAAA,oBAAA,aAAU;AACV,EAAAA,oBAAA,eAAY;AAJF,SAAAA;AAAA,GAAA;AAsOL,IAAM,gCAAgC;AA7b7C;AAkcO,IAAM,yBAAN,cAAqC,eAI1C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAkBA,YAAY;AAAA,IACV;AAAA,IACA,WAAW;AAAA,IACX;AAAA,IACA;AAAA,EACF,GAKG;AACD,UAAM;AAAA,MACJ,MAAM;AAAA,MACN;AAAA,MACA,UAAU,CAAC;AAAA,MACX,OAAO,CAAC;AAAA,IACV,CAAC;AAwCH;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA;AAgBA,uBAAM;AA/FN;AAEA,uBAAS,SAAT;AAEA,uBAAS,cAAT;AAEA;AA4BE,uBAAK,WAAY;AACjB,uBAAK,8BAA+B,CAAC;AAErC,uBAAK,cAAe;AACpB,uBAAK,SAAU;AAEf,SAAK,gBAAgB;AAAA,MACnB;AAAA,MACA,sBAAK,4EAAoC,KAAK,IAAI;AAAA,IACpD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,E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;AAAA,cACA;AAAA,cACA,iBAAiB,SAAS;AAAA,YAC5B;AAAA,UACF;AAAA,QACF,CAAC;AACD,cAAM,QAAQ,IAAI,cAAc;AAAA,MAClC,SAAU,OAAO,aAAa;AAC9B,sBAAgB;AAAA,IAClB,SAAS,OAAO;AACd,mBAAa,KAAK;AAClB,YAAM;AAAA,IACR,UAAE;AACA,aAAO,mBAAK,8BAA6B,SAAS;AAAA,IACpD;AAAA,EACF;AACF;AAhUE;AAES;AAEA;AAET;AAmEA;AAAA,wCAAmC,SAAC,EAAE,gBAAgB,GAAqB;AACzE,MAAI,CAAC,oBAAoB,mBAAK,YAAW;AACvC,uBAAK,WAAY,CAAC;AAAA,EACpB;AACF;AAEA;AAAA,oBAAe,SAAC;AAAA,EACd;AAAA,EACA;AAAA,EACA;AACF,GAIG;AACD,SAAO,GACL,gBACF,UAAU,OAAO,oBAAoB,OAAO,6CAC1C,QAAQ,EACV;AACF;AAEM;AAAA,kBAAa,eACjB,SACA,SACA,QACA;AAEA,QAAM,mBAAmB,oBAAoB,OAAO,EAAE,SAAS;AAC/D,QAAM,MAAM,sBAAK,oCAAL,WAAqB;AAAA,IAC/B,SAAS;AAAA,IACT;AAAA,IACA,MAAM;AAAA,EACR;AACA,QAAM,iBAAoC,MAAM,YAAY,KAAK;AAAA,IAC/D,SAAS;AAAA,MACP,SAAS;AAAA,IACX;AAAA,EACF,CAAC;AACD,SAAO;AACT;AAiNF,IAAO,iCAAQ","sourcesContent":["import type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';\nimport type { AddApprovalRequest } from '@metamask/approval-controller';\nimport type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n toChecksumHexAddress,\n ChainId,\n NFT_API_BASE_URL,\n NFT_API_VERSION,\n convertHexToDecimal,\n handleFetch,\n fetchWithErrorHandling,\n NFT_API_TIMEOUT,\n} from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkClient,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerStateChangeEvent,\n NetworkControllerGetStateAction,\n} from '@metamask/network-controller';\nimport type {\n PreferencesControllerGetStateAction,\n PreferencesControllerStateChangeEvent,\n PreferencesState,\n} from '@metamask/preferences-controller';\nimport { createDeferredPromise, type Hex } from '@metamask/utils';\n\nimport { reduceInBatchesSerially } from './assetsUtil';\nimport { Source } from './constants';\nimport {\n type NftController,\n type NftControllerState,\n type NftMetadata,\n} from './NftController';\n\nconst controllerName = 'NftDetectionController';\n\nexport type NFTDetectionControllerState = Record<never, never>;\n\nexport type AllowedActions =\n | AddApprovalRequest\n | NetworkControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | PreferencesControllerGetStateAction\n | AccountsControllerGetSelectedAccountAction;\n\nexport type AllowedEvents =\n | PreferencesControllerStateChangeEvent\n | NetworkControllerStateChangeEvent;\n\nexport type NftDetectionControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n AllowedActions,\n AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\nconst supportedNftDetectionNetworks: Hex[] = [\n ChainId.mainnet,\n ChainId['linea-mainnet'],\n];\n\n/**\n * @type ApiNft\n *\n * NFT object coming from OpenSea api\n * @property token_id - The NFT identifier\n * @property num_sales - Number of sales\n * @property background_color - The background color to be displayed with the item\n * @property image_url - URI of an image associated with this NFT\n * @property image_preview_url - URI of a smaller image associated with this NFT\n * @property image_thumbnail_url - URI of a thumbnail image associated with this NFT\n * @property image_original_url - URI of the original image associated with this NFT\n * @property animation_url - URI of a animation associated with this NFT\n * @property animation_original_url - URI of the original animation associated with this NFT\n * @property name - The NFT name\n * @property description - The NFT description\n * @property external_link - External link containing additional information\n * @property assetContract - The NFT contract information object\n * @property creator - The NFT owner information object\n * @property lastSale - When this item was last sold\n */\nexport type ApiNft = {\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_id: 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 num_sales: number | null;\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 background_color: string | null;\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 image_url: string | null;\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 image_preview_url: string | null;\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 image_thumbnail_url: string | null;\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 image_original_url: string | null;\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 animation_url: string | null;\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 animation_original_url: string | null;\n name: string | null;\n description: string | null;\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 external_link: string | null;\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_contract: ApiNftContract;\n creator: ApiNftCreator;\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 last_sale: ApiNftLastSale | null;\n};\n\n/**\n * @type ApiNftContract\n *\n * NFT contract object coming from OpenSea api\n * @property address - Address of the NFT contract\n * @property asset_contract_type - The NFT type, it could be `semi-fungible` or `non-fungible`\n * @property created_date - Creation date\n * @property collection - Object containing the contract name and URI of an image associated\n * @property schema_name - The schema followed by the contract, it could be `ERC721` or `ERC1155`\n * @property symbol - The NFT contract symbol\n * @property total_supply - Total supply of NFTs\n * @property description - The NFT contract description\n * @property external_link - External link containing additional information\n */\nexport type ApiNftContract = {\n address: 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_contract_type: string | null;\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 created_date: string | null;\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 schema_name: string | null;\n symbol: string | null;\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 total_supply: string | null;\n description: string | null;\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 external_link: string | null;\n collection: {\n name: string | null;\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 image_url?: string | null;\n tokenCount?: string | null;\n };\n};\n\n/**\n * @type ApiNftLastSale\n *\n * NFT sale object coming from OpenSea api\n * @property event_timestamp - Object containing a `username`\n * @property total_price - URI of NFT image associated with this owner\n * @property transaction - Object containing transaction_hash and block_hash\n */\nexport type ApiNftLastSale = {\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 event_timestamp: 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 total_price: 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 transaction: { transaction_hash: string; block_hash: string };\n};\n\n/**\n * @type ApiNftCreator\n *\n * NFT creator object coming from OpenSea api\n * @property user - Object containing a `username`\n * @property profile_img_url - URI of NFT image associated with this owner\n * @property address - The owner address\n */\nexport type ApiNftCreator = {\n user: { username: 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 profile_img_url: string;\n address: string;\n};\n\nexport type ReservoirResponse = {\n tokens: TokensResponse[];\n continuation?: string;\n};\n\nexport type TokensResponse = {\n token: TokenResponse;\n ownership: Ownership;\n market?: Market;\n blockaidResult?: Blockaid;\n};\n\nexport enum BlockaidResultType {\n Benign = 'Benign',\n Spam = 'Spam',\n Warning = 'Warning',\n Malicious = 'Malicious',\n}\n\nexport type Blockaid = {\n contract: string;\n chainId: number;\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n result_type: BlockaidResultType;\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 malicious_score: 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 attack_types: object;\n};\n\nexport type Market = {\n floorAsk?: FloorAsk;\n topBid?: TopBid;\n};\n\nexport type TokenResponse = {\n chainId: number;\n contract: string;\n tokenId: string;\n kind?: string;\n name?: string;\n image?: string;\n imageSmall?: string;\n imageLarge?: string;\n metadata?: Metadata;\n description?: string;\n supply?: number;\n remainingSupply?: number;\n rarityScore?: number;\n rarity?: number;\n rarityRank?: number;\n media?: string;\n isFlagged?: boolean;\n isSpam?: boolean;\n isNsfw?: boolean;\n metadataDisabled?: boolean;\n lastFlagUpdate?: string;\n lastFlagChange?: string;\n collection?: Collection;\n lastSale?: LastSale;\n topBid?: TopBid;\n lastAppraisalValue?: number;\n attributes?: Attributes[];\n};\n\nexport type TopBid = {\n id?: string;\n price?: Price;\n source?: {\n id?: string;\n domain?: string;\n name?: string;\n icon?: string;\n url?: string;\n };\n};\n\nexport type LastSale = {\n saleId?: string;\n token?: {\n contract?: string;\n tokenId?: string;\n name?: string;\n image?: string;\n collection?: {\n id?: string;\n name?: string;\n };\n };\n orderSource?: string;\n orderSide?: 'ask' | 'bid';\n orderKind?: string;\n orderId?: string;\n from?: string;\n to?: string;\n amount?: string;\n fillSource?: string;\n block?: number;\n txHash?: string;\n logIndex?: number;\n batchIndex?: number;\n timestamp?: number;\n price?: Price;\n washTradingScore?: number;\n royaltyFeeBps?: number;\n marketplaceFeeBps?: number;\n paidFullRoyalty?: boolean;\n feeBreakdown?: FeeBreakdown[];\n isDeleted?: boolean;\n createdAt?: string;\n updatedAt?: string;\n};\n\nexport type FeeBreakdown = {\n kind?: string;\n bps?: number;\n recipient?: string;\n source?: string;\n rawAmount?: string;\n};\n\nexport type Attributes = {\n key?: string;\n kind?: string;\n value: string;\n tokenCount?: number;\n onSaleCount?: number;\n floorAskPrice?: Price | null;\n topBidValue?: number | null;\n createdAt?: string;\n};\n\nexport type GetCollectionsResponse = {\n collections: CollectionResponse[];\n};\n\nexport type CollectionResponse = {\n id?: string;\n openseaVerificationStatus?: string;\n contractDeployedAt?: string;\n creator?: string;\n ownerCount?: string;\n topBid?: TopBid & {\n sourceDomain?: string;\n };\n};\n\nexport type FloorAskCollection = {\n id?: string;\n price?: Price;\n maker?: string;\n kind?: string;\n validFrom?: number;\n validUntil?: number;\n source?: SourceCollection;\n rawData?: Metadata;\n isNativeOffChainCancellable?: boolean;\n};\n\nexport type SourceCollection = {\n id: string;\n domain: string;\n name: string;\n icon: string;\n url: string;\n};\n\nexport type TokenCollection = {\n id?: string;\n name?: string;\n slug?: string;\n symbol?: string;\n imageUrl?: string;\n image?: string;\n isSpam?: boolean;\n isNsfw?: boolean;\n creator?: string;\n tokenCount?: string;\n metadataDisabled?: boolean;\n openseaVerificationStatus?: string;\n floorAskPrice?: Price;\n royaltiesBps?: number;\n royalties?: Royalties[];\n floorAsk?: FloorAskCollection;\n};\n\nexport type Collection = TokenCollection & CollectionResponse;\n\nexport type Royalties = {\n bps?: number;\n recipient?: string;\n};\n\nexport type Ownership = {\n tokenCount?: string;\n onSaleCount?: string;\n floorAsk?: FloorAsk;\n acquiredAt?: string;\n};\n\nexport type FloorAsk = {\n id?: string;\n price?: Price;\n maker?: string;\n kind?: string;\n validFrom?: number;\n validUntil?: number;\n source?: Source;\n rawData?: Metadata;\n isNativeOffChainCancellable?: boolean;\n};\n\nexport type Price = {\n currency?: {\n contract?: string;\n name?: string;\n symbol?: string;\n decimals?: number;\n chainId?: number;\n };\n amount?: {\n raw?: string;\n decimal?: number;\n usd?: number;\n native?: number;\n };\n netAmount?: {\n raw?: string;\n decimal?: number;\n usd?: number;\n native?: number;\n };\n};\n\nexport type Metadata = {\n imageOriginal?: string;\n tokenURI?: string;\n};\n\nexport const MAX_GET_COLLECTION_BATCH_SIZE = 20;\n\n/**\n * Controller that passively detects nfts for a user address\n */\nexport class NftDetectionController extends BaseController<\n typeof controllerName,\n NFTDetectionControllerState,\n NftDetectionControllerMessenger\n> {\n #disabled: boolean;\n\n readonly #addNft: NftController['addNft'];\n\n readonly #getNftState: () => NftControllerState;\n\n #inProcessNftFetchingUpdates: Record<`${Hex}:${string}`, Promise<void>>;\n\n /**\n * The controller options\n *\n * @param options - The controller options.\n * @param options.messenger - A reference to the messaging system.\n * @param options.disabled - Represents previous value of useNftDetection. Used to detect changes of useNftDetection. Default value is true.\n * @param options.addNft - Add an NFT.\n * @param options.getNftState - Gets the current state of the Assets controller.\n */\n constructor({\n messenger,\n disabled = false,\n addNft,\n getNftState,\n }: {\n messenger: NftDetectionControllerMessenger;\n disabled: boolean;\n addNft: NftController['addNft'];\n getNftState: () => NftControllerState;\n }) {\n super({\n name: controllerName,\n messenger,\n metadata: {},\n state: {},\n });\n this.#disabled = disabled;\n this.#inProcessNftFetchingUpdates = {};\n\n this.#getNftState = getNftState;\n this.#addNft = addNft;\n\n this.messagingSystem.subscribe(\n 'PreferencesController:stateChange',\n this.#onPreferencesControllerStateChange.bind(this),\n );\n }\n\n /**\n * Checks whether network is mainnet or not.\n *\n * @returns Whether current network is mainnet.\n */\n isMainnet(): boolean {\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 chainId === ChainId.mainnet;\n }\n\n isMainnetByNetworkClientId(networkClient: NetworkClient): boolean {\n return networkClient.configuration.chainId === ChainId.mainnet;\n }\n\n /**\n * Handles the state change of the preference controller.\n * @param preferencesState - The new state of the preference controller.\n * @param preferencesState.useNftDetection - Boolean indicating user preference on NFT detection.\n */\n #onPreferencesControllerStateChange({ useNftDetection }: PreferencesState) {\n if (!useNftDetection !== this.#disabled) {\n this.#disabled = !useNftDetection;\n }\n }\n\n #getOwnerNftApi({\n chainId,\n address,\n next,\n }: {\n chainId: string;\n address: string;\n next?: string;\n }) {\n return `${\n NFT_API_BASE_URL as string\n }/users/${address}/tokens?chainIds=${chainId}&limit=50&includeTopBid=true&continuation=${\n next ?? ''\n }`;\n }\n\n async #getOwnerNfts(\n address: string,\n chainId: Hex,\n cursor: string | undefined,\n ) {\n // Convert hex chainId to number\n const convertedChainId = convertHexToDecimal(chainId).toString();\n const url = this.#getOwnerNftApi({\n chainId: convertedChainId,\n address,\n next: cursor,\n });\n const nftApiResponse: ReservoirResponse = await handleFetch(url, {\n headers: {\n Version: NFT_API_VERSION,\n },\n });\n return nftApiResponse;\n }\n\n /**\n * Triggers asset ERC721 token auto detection on mainnet. Any newly detected NFTs are\n * added.\n *\n * @param options - Options bag.\n * @param options.networkClientId - The network client ID to detect NFTs on.\n * @param options.userAddress - The address to detect NFTs for.\n */\n async detectNfts(options?: {\n networkClientId?: NetworkClientId;\n userAddress?: string;\n }) {\n const userAddress =\n options?.userAddress ??\n this.messagingSystem.call('AccountsController:getSelectedAccount')\n .address;\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\n /* istanbul ignore if */\n if (!supportedNftDetectionNetworks.includes(chainId) || this.#disabled) {\n return;\n }\n /* istanbul ignore else */\n if (!userAddress) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n const updateKey: `${Hex}:${string}` = `${chainId}:${userAddress}`;\n if (updateKey in this.#inProcessNftFetchingUpdates) {\n // This prevents redundant updates\n // This promise is resolved after the in-progress update has finished,\n // and state has been updated.\n await this.#inProcessNftFetchingUpdates[updateKey];\n return;\n }\n\n const {\n promise: inProgressUpdate,\n resolve: updateSucceeded,\n reject: updateFailed,\n } = createDeferredPromise({ suppressUnhandledRejection: true });\n this.#inProcessNftFetchingUpdates[updateKey] = inProgressUpdate;\n\n let next;\n let apiNfts: TokensResponse[] = [];\n let resultNftApi: ReservoirResponse;\n try {\n do {\n resultNftApi = await this.#getOwnerNfts(userAddress, chainId, next);\n apiNfts = resultNftApi.tokens.filter(\n (elm) =>\n elm.token.isSpam === false &&\n (elm.blockaidResult?.result_type\n ? elm.blockaidResult?.result_type === BlockaidResultType.Benign\n : true),\n );\n // Retrieve collections from apiNfts\n // contract and collection.id are equal for simple contract addresses; this is to exclude cases for shared contracts\n const collections = apiNfts.reduce<string[]>((acc, currValue) => {\n if (\n !acc.includes(currValue.token.contract) &&\n currValue.token.contract === currValue?.token?.collection?.id\n ) {\n acc.push(currValue.token.contract);\n }\n return acc;\n }, []);\n\n if (collections.length !== 0) {\n // Call API to retrive collections infos\n // The api accept a max of 20 contracts\n const collectionResponse: GetCollectionsResponse =\n await reduceInBatchesSerially({\n values: collections,\n batchSize: MAX_GET_COLLECTION_BATCH_SIZE,\n eachBatch: async (allResponses, batch) => {\n const params = new URLSearchParams(\n batch.map((s) => ['contract', s]),\n );\n params.append('chainId', '1'); // Adding chainId 1 because we are only detecting for mainnet\n const collectionResponseForBatch = await fetchWithErrorHandling(\n {\n url: `${\n NFT_API_BASE_URL as string\n }/collections?${params.toString()}`,\n options: {\n headers: {\n Version: NFT_API_VERSION,\n },\n },\n timeout: NFT_API_TIMEOUT,\n },\n );\n\n return {\n ...allResponses,\n ...collectionResponseForBatch,\n };\n },\n initialResult: {},\n });\n\n // Add collections response fields to newnfts\n if (collectionResponse.collections?.length) {\n apiNfts.forEach((singleNFT) => {\n const found = collectionResponse.collections.find(\n (elm) =>\n elm.id?.toLowerCase() ===\n singleNFT.token.contract.toLowerCase(),\n );\n if (found) {\n singleNFT.token = {\n ...singleNFT.token,\n collection: {\n ...(singleNFT.token.collection ?? {}),\n creator: found?.creator,\n openseaVerificationStatus: found?.openseaVerificationStatus,\n contractDeployedAt: found.contractDeployedAt,\n ownerCount: found.ownerCount,\n topBid: found.topBid,\n },\n };\n }\n });\n }\n }\n\n // Proceed to add NFTs\n const addNftPromises = apiNfts.map(async (nft) => {\n const {\n tokenId,\n contract,\n kind,\n image: imageUrl,\n imageSmall: imageThumbnailUrl,\n metadata: { imageOriginal: imageOriginalUrl } = {},\n name,\n description,\n attributes,\n topBid,\n lastSale,\n rarityRank,\n rarityScore,\n collection,\n } = nft.token;\n\n let ignored;\n /* istanbul ignore else */\n const { ignoredNfts } = this.#getNftState();\n if (ignoredNfts.length) {\n ignored = ignoredNfts.find((c) => {\n /* istanbul ignore next */\n return (\n c.address === toChecksumHexAddress(contract) &&\n c.tokenId === tokenId\n );\n });\n }\n\n /* istanbul ignore else */\n if (!ignored) {\n /* istanbul ignore next */\n const nftMetadata: NftMetadata = Object.assign(\n {},\n { name },\n description && { description },\n imageUrl && { image: imageUrl },\n imageThumbnailUrl && { imageThumbnail: imageThumbnailUrl },\n imageOriginalUrl && { imageOriginal: imageOriginalUrl },\n kind && { standard: kind.toUpperCase() },\n lastSale && { lastSale },\n attributes && { attributes },\n topBid && { topBid },\n rarityRank && { rarityRank },\n rarityScore && { rarityScore },\n collection && { collection },\n );\n await this.#addNft(contract, tokenId, {\n nftMetadata,\n userAddress,\n source: Source.Detected,\n networkClientId: options?.networkClientId,\n });\n }\n });\n await Promise.all(addNftPromises);\n } while ((next = resultNftApi.continuation));\n updateSucceeded();\n } catch (error) {\n updateFailed(error);\n throw error;\n } finally {\n delete this.#inProcessNftFetchingUpdates[updateKey];\n }\n }\n}\n\nexport default NftDetectionController;\n"]}
@@ -5,7 +5,6 @@ import {
5
5
  } from "@metamask/controller-utils";
6
6
  import { remove0x } from "@metamask/utils";
7
7
  import BN from "bn.js";
8
- import { CID } from "multiformats/cid";
9
8
  var TOKEN_PRICES_BATCH_SIZE = 30;
10
9
  function compareNftMetadata(newNftMetadata, nft) {
11
10
  const keys = [
@@ -27,6 +26,11 @@ function compareNftMetadata(newNftMetadata, nft) {
27
26
  }, 0);
28
27
  return differentValues > 0;
29
28
  }
29
+ function hasNewCollectionFields(newNftMetadata, nft) {
30
+ const keysNewNftMetadata = Object.keys(newNftMetadata.collection ?? {});
31
+ const keysExistingNft = new Set(Object.keys(nft.collection ?? {}));
32
+ return keysNewNftMetadata.some((key) => !keysExistingNft.has(key));
33
+ }
30
34
  var aggregatorNameByKey = {
31
35
  aave: "Aave",
32
36
  bancor: "Bancor",
@@ -102,20 +106,21 @@ function removeIpfsProtocolPrefix(ipfsUrl) {
102
106
  }
103
107
  throw new Error("this method should not be used with non ipfs urls");
104
108
  }
105
- function getIpfsCIDv1AndPath(ipfsUrl) {
109
+ async function getIpfsCIDv1AndPath(ipfsUrl) {
106
110
  const url = removeIpfsProtocolPrefix(ipfsUrl);
107
111
  const index = url.indexOf("/");
108
112
  const cid = index !== -1 ? url.substring(0, index) : url;
109
113
  const path = index !== -1 ? url.substring(index) : void 0;
114
+ const { CID } = await import("multiformats");
110
115
  return {
111
116
  cid: CID.parse(cid).toV1().toString(),
112
117
  path
113
118
  };
114
119
  }
115
- function getFormattedIpfsUrl(ipfsGateway, ipfsUrl, subdomainSupported) {
120
+ async function getFormattedIpfsUrl(ipfsGateway, ipfsUrl, subdomainSupported) {
116
121
  const { host, protocol, origin } = new URL(addUrlProtocolPrefix(ipfsGateway));
117
122
  if (subdomainSupported) {
118
- const { cid, path } = getIpfsCIDv1AndPath(ipfsUrl);
123
+ const { cid, path } = await getIpfsCIDv1AndPath(ipfsUrl);
119
124
  return `${protocol}//${cid}.ipfs.${host}${path ?? ""}`;
120
125
  }
121
126
  const cidAndPath = removeIpfsProtocolPrefix(ipfsUrl);
@@ -192,6 +197,7 @@ async function fetchTokenContractExchangeRates({
192
197
  export {
193
198
  TOKEN_PRICES_BATCH_SIZE,
194
199
  compareNftMetadata,
200
+ hasNewCollectionFields,
195
201
  formatAggregatorNames,
196
202
  formatIconUrlWithProxy,
197
203
  SupportedTokenDetectionNetworks,
@@ -206,4 +212,4 @@ export {
206
212
  reduceInBatchesSerially,
207
213
  fetchTokenContractExchangeRates
208
214
  };
209
- //# sourceMappingURL=chunk-VELPHITE.mjs.map
215
+ //# sourceMappingURL=chunk-BZEAPSD5.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';\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\n/**\n * Checks whether the existing nft object has all the keys of the new incoming nft metadata object\n * @param newNftMetadata - New nft metadata object\n * @param nft - Existing nft object to compare with\n * @returns Whether the existing nft object has all the new keys from the new Nft metadata object\n */\nexport function hasNewCollectionFields(\n newNftMetadata: NftMetadata,\n nft: Nft,\n): boolean {\n const keysNewNftMetadata = Object.keys(newNftMetadata.collection ?? {});\n const keysExistingNft = new Set(Object.keys(nft.collection ?? {}));\n\n return keysNewNftMetadata.some((key) => !keysExistingNft.has(key));\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 async function getIpfsCIDv1AndPath(ipfsUrl: string): Promise<{\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 const { CID } = await import('multiformats');\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 async function getFormattedIpfsUrl(\n ipfsGateway: string,\n ipfsUrl: string,\n subdomainSupported: boolean,\n): Promise<string> {\n const { host, protocol, origin } = new URL(addUrlProtocolPrefix(ipfsGateway));\n if (subdomainSupported) {\n const { cid, path } = await 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;AAUR,IAAM,0BAA0B;AAWhC,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AAQ,QAAQ,GAAG;AAC9C,oBAAgB,MAAM,UAAU,eAAe,OAAO,KAAK;AAAA,EAC7D;AAGA,QAAM,cAAc;AACpB,SAAO;AACT;AAYA,eAAsB,gCAAgC;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAKmC;AACjC,QAAM,qBACJ,mBAAmB,yBAAyB,OAAO;AACrD,QAAM,sBACJ,mBAAmB,0BAA0B,cAAc;AAE7D,MAAI,CAAC,sBAAsB,CAAC,qBAAqB;AAC/C,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,4BAA4B,MAAM,wBAGtC;AAAA,IACA,QAAQ,CAAC,GAAG,cAAc,EAAE,KAAK;AAAA,IACjC,WAAW;AAAA,IACX,WAAW,OAAO,8BAA8B,UAAU;AACxD,YAAM,oCACJ,MAAM,mBAAmB,iBAAiB;AAAA,QACxC,gBAAgB;AAAA,QAChB;AAAA,QACA,UAAU;AAAA,MACZ,CAAC;AAEH,aAAO;AAAA,QACL,GAAG;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,3 +1,6 @@
1
+ import {
2
+ reduceInBatchesSerially
3
+ } from "./chunk-BZEAPSD5.mjs";
1
4
  import {
2
5
  __privateAdd,
3
6
  __privateGet,
@@ -13,11 +16,16 @@ import {
13
16
  NFT_API_BASE_URL,
14
17
  NFT_API_VERSION,
15
18
  convertHexToDecimal,
16
- handleFetch
19
+ handleFetch,
20
+ fetchWithErrorHandling,
21
+ NFT_API_TIMEOUT
17
22
  } from "@metamask/controller-utils";
18
23
  import { createDeferredPromise } from "@metamask/utils";
19
24
  var controllerName = "NftDetectionController";
20
- var supportedNftDetectionNetworks = [ChainId.mainnet];
25
+ var supportedNftDetectionNetworks = [
26
+ ChainId.mainnet,
27
+ ChainId["linea-mainnet"]
28
+ ];
21
29
  var BlockaidResultType = /* @__PURE__ */ ((BlockaidResultType2) => {
22
30
  BlockaidResultType2["Benign"] = "Benign";
23
31
  BlockaidResultType2["Spam"] = "Spam";
@@ -25,6 +33,7 @@ var BlockaidResultType = /* @__PURE__ */ ((BlockaidResultType2) => {
25
33
  BlockaidResultType2["Malicious"] = "Malicious";
26
34
  return BlockaidResultType2;
27
35
  })(BlockaidResultType || {});
36
+ var MAX_GET_COLLECTION_BATCH_SIZE = 20;
28
37
  var _disabled, _addNft, _getNftState, _inProcessNftFetchingUpdates, _onPreferencesControllerStateChange, onPreferencesControllerStateChange_fn, _getOwnerNftApi, getOwnerNftApi_fn, _getOwnerNfts, getOwnerNfts_fn;
29
38
  var NftDetectionController = class extends BaseController {
30
39
  /**
@@ -134,6 +143,60 @@ var NftDetectionController = class extends BaseController {
134
143
  apiNfts = resultNftApi.tokens.filter(
135
144
  (elm) => elm.token.isSpam === false && (elm.blockaidResult?.result_type ? elm.blockaidResult?.result_type === "Benign" /* Benign */ : true)
136
145
  );
146
+ const collections = apiNfts.reduce((acc, currValue) => {
147
+ if (!acc.includes(currValue.token.contract) && currValue.token.contract === currValue?.token?.collection?.id) {
148
+ acc.push(currValue.token.contract);
149
+ }
150
+ return acc;
151
+ }, []);
152
+ if (collections.length !== 0) {
153
+ const collectionResponse = await reduceInBatchesSerially({
154
+ values: collections,
155
+ batchSize: MAX_GET_COLLECTION_BATCH_SIZE,
156
+ eachBatch: async (allResponses, batch) => {
157
+ const params = new URLSearchParams(
158
+ batch.map((s) => ["contract", s])
159
+ );
160
+ params.append("chainId", "1");
161
+ const collectionResponseForBatch = await fetchWithErrorHandling(
162
+ {
163
+ url: `${NFT_API_BASE_URL}/collections?${params.toString()}`,
164
+ options: {
165
+ headers: {
166
+ Version: NFT_API_VERSION
167
+ }
168
+ },
169
+ timeout: NFT_API_TIMEOUT
170
+ }
171
+ );
172
+ return {
173
+ ...allResponses,
174
+ ...collectionResponseForBatch
175
+ };
176
+ },
177
+ initialResult: {}
178
+ });
179
+ if (collectionResponse.collections?.length) {
180
+ apiNfts.forEach((singleNFT) => {
181
+ const found = collectionResponse.collections.find(
182
+ (elm) => elm.id?.toLowerCase() === singleNFT.token.contract.toLowerCase()
183
+ );
184
+ if (found) {
185
+ singleNFT.token = {
186
+ ...singleNFT.token,
187
+ collection: {
188
+ ...singleNFT.token.collection ?? {},
189
+ creator: found?.creator,
190
+ openseaVerificationStatus: found?.openseaVerificationStatus,
191
+ contractDeployedAt: found.contractDeployedAt,
192
+ ownerCount: found.ownerCount,
193
+ topBid: found.topBid
194
+ }
195
+ };
196
+ }
197
+ });
198
+ }
199
+ }
137
200
  const addNftPromises = apiNfts.map(async (nft) => {
138
201
  const {
139
202
  tokenId,
@@ -230,7 +293,8 @@ var NftDetectionController_default = NftDetectionController;
230
293
 
231
294
  export {
232
295
  BlockaidResultType,
296
+ MAX_GET_COLLECTION_BATCH_SIZE,
233
297
  NftDetectionController,
234
298
  NftDetectionController_default
235
299
  };
236
- //# sourceMappingURL=chunk-2IIQTSLV.mjs.map
300
+ //# sourceMappingURL=chunk-C7LNCQXM.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/NftDetectionController.ts"],"sourcesContent":["import type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';\nimport type { AddApprovalRequest } from '@metamask/approval-controller';\nimport type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n toChecksumHexAddress,\n ChainId,\n NFT_API_BASE_URL,\n NFT_API_VERSION,\n convertHexToDecimal,\n handleFetch,\n fetchWithErrorHandling,\n NFT_API_TIMEOUT,\n} from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkClient,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerStateChangeEvent,\n NetworkControllerGetStateAction,\n} from '@metamask/network-controller';\nimport type {\n PreferencesControllerGetStateAction,\n PreferencesControllerStateChangeEvent,\n PreferencesState,\n} from '@metamask/preferences-controller';\nimport { createDeferredPromise, type Hex } from '@metamask/utils';\n\nimport { reduceInBatchesSerially } from './assetsUtil';\nimport { Source } from './constants';\nimport {\n type NftController,\n type NftControllerState,\n type NftMetadata,\n} from './NftController';\n\nconst controllerName = 'NftDetectionController';\n\nexport type NFTDetectionControllerState = Record<never, never>;\n\nexport type AllowedActions =\n | AddApprovalRequest\n | NetworkControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | PreferencesControllerGetStateAction\n | AccountsControllerGetSelectedAccountAction;\n\nexport type AllowedEvents =\n | PreferencesControllerStateChangeEvent\n | NetworkControllerStateChangeEvent;\n\nexport type NftDetectionControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n AllowedActions,\n AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\nconst supportedNftDetectionNetworks: Hex[] = [\n ChainId.mainnet,\n ChainId['linea-mainnet'],\n];\n\n/**\n * @type ApiNft\n *\n * NFT object coming from OpenSea api\n * @property token_id - The NFT identifier\n * @property num_sales - Number of sales\n * @property background_color - The background color to be displayed with the item\n * @property image_url - URI of an image associated with this NFT\n * @property image_preview_url - URI of a smaller image associated with this NFT\n * @property image_thumbnail_url - URI of a thumbnail image associated with this NFT\n * @property image_original_url - URI of the original image associated with this NFT\n * @property animation_url - URI of a animation associated with this NFT\n * @property animation_original_url - URI of the original animation associated with this NFT\n * @property name - The NFT name\n * @property description - The NFT description\n * @property external_link - External link containing additional information\n * @property assetContract - The NFT contract information object\n * @property creator - The NFT owner information object\n * @property lastSale - When this item was last sold\n */\nexport type ApiNft = {\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_id: 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 num_sales: number | null;\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 background_color: string | null;\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 image_url: string | null;\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 image_preview_url: string | null;\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 image_thumbnail_url: string | null;\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 image_original_url: string | null;\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 animation_url: string | null;\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 animation_original_url: string | null;\n name: string | null;\n description: string | null;\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 external_link: string | null;\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_contract: ApiNftContract;\n creator: ApiNftCreator;\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 last_sale: ApiNftLastSale | null;\n};\n\n/**\n * @type ApiNftContract\n *\n * NFT contract object coming from OpenSea api\n * @property address - Address of the NFT contract\n * @property asset_contract_type - The NFT type, it could be `semi-fungible` or `non-fungible`\n * @property created_date - Creation date\n * @property collection - Object containing the contract name and URI of an image associated\n * @property schema_name - The schema followed by the contract, it could be `ERC721` or `ERC1155`\n * @property symbol - The NFT contract symbol\n * @property total_supply - Total supply of NFTs\n * @property description - The NFT contract description\n * @property external_link - External link containing additional information\n */\nexport type ApiNftContract = {\n address: 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_contract_type: string | null;\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 created_date: string | null;\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 schema_name: string | null;\n symbol: string | null;\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 total_supply: string | null;\n description: string | null;\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 external_link: string | null;\n collection: {\n name: string | null;\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 image_url?: string | null;\n tokenCount?: string | null;\n };\n};\n\n/**\n * @type ApiNftLastSale\n *\n * NFT sale object coming from OpenSea api\n * @property event_timestamp - Object containing a `username`\n * @property total_price - URI of NFT image associated with this owner\n * @property transaction - Object containing transaction_hash and block_hash\n */\nexport type ApiNftLastSale = {\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 event_timestamp: 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 total_price: 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 transaction: { transaction_hash: string; block_hash: string };\n};\n\n/**\n * @type ApiNftCreator\n *\n * NFT creator object coming from OpenSea api\n * @property user - Object containing a `username`\n * @property profile_img_url - URI of NFT image associated with this owner\n * @property address - The owner address\n */\nexport type ApiNftCreator = {\n user: { username: 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 profile_img_url: string;\n address: string;\n};\n\nexport type ReservoirResponse = {\n tokens: TokensResponse[];\n continuation?: string;\n};\n\nexport type TokensResponse = {\n token: TokenResponse;\n ownership: Ownership;\n market?: Market;\n blockaidResult?: Blockaid;\n};\n\nexport enum BlockaidResultType {\n Benign = 'Benign',\n Spam = 'Spam',\n Warning = 'Warning',\n Malicious = 'Malicious',\n}\n\nexport type Blockaid = {\n contract: string;\n chainId: number;\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n result_type: BlockaidResultType;\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 malicious_score: 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 attack_types: object;\n};\n\nexport type Market = {\n floorAsk?: FloorAsk;\n topBid?: TopBid;\n};\n\nexport type TokenResponse = {\n chainId: number;\n contract: string;\n tokenId: string;\n kind?: string;\n name?: string;\n image?: string;\n imageSmall?: string;\n imageLarge?: string;\n metadata?: Metadata;\n description?: string;\n supply?: number;\n remainingSupply?: number;\n rarityScore?: number;\n rarity?: number;\n rarityRank?: number;\n media?: string;\n isFlagged?: boolean;\n isSpam?: boolean;\n isNsfw?: boolean;\n metadataDisabled?: boolean;\n lastFlagUpdate?: string;\n lastFlagChange?: string;\n collection?: Collection;\n lastSale?: LastSale;\n topBid?: TopBid;\n lastAppraisalValue?: number;\n attributes?: Attributes[];\n};\n\nexport type TopBid = {\n id?: string;\n price?: Price;\n source?: {\n id?: string;\n domain?: string;\n name?: string;\n icon?: string;\n url?: string;\n };\n};\n\nexport type LastSale = {\n saleId?: string;\n token?: {\n contract?: string;\n tokenId?: string;\n name?: string;\n image?: string;\n collection?: {\n id?: string;\n name?: string;\n };\n };\n orderSource?: string;\n orderSide?: 'ask' | 'bid';\n orderKind?: string;\n orderId?: string;\n from?: string;\n to?: string;\n amount?: string;\n fillSource?: string;\n block?: number;\n txHash?: string;\n logIndex?: number;\n batchIndex?: number;\n timestamp?: number;\n price?: Price;\n washTradingScore?: number;\n royaltyFeeBps?: number;\n marketplaceFeeBps?: number;\n paidFullRoyalty?: boolean;\n feeBreakdown?: FeeBreakdown[];\n isDeleted?: boolean;\n createdAt?: string;\n updatedAt?: string;\n};\n\nexport type FeeBreakdown = {\n kind?: string;\n bps?: number;\n recipient?: string;\n source?: string;\n rawAmount?: string;\n};\n\nexport type Attributes = {\n key?: string;\n kind?: string;\n value: string;\n tokenCount?: number;\n onSaleCount?: number;\n floorAskPrice?: Price | null;\n topBidValue?: number | null;\n createdAt?: string;\n};\n\nexport type GetCollectionsResponse = {\n collections: CollectionResponse[];\n};\n\nexport type CollectionResponse = {\n id?: string;\n openseaVerificationStatus?: string;\n contractDeployedAt?: string;\n creator?: string;\n ownerCount?: string;\n topBid?: TopBid & {\n sourceDomain?: string;\n };\n};\n\nexport type FloorAskCollection = {\n id?: string;\n price?: Price;\n maker?: string;\n kind?: string;\n validFrom?: number;\n validUntil?: number;\n source?: SourceCollection;\n rawData?: Metadata;\n isNativeOffChainCancellable?: boolean;\n};\n\nexport type SourceCollection = {\n id: string;\n domain: string;\n name: string;\n icon: string;\n url: string;\n};\n\nexport type TokenCollection = {\n id?: string;\n name?: string;\n slug?: string;\n symbol?: string;\n imageUrl?: string;\n image?: string;\n isSpam?: boolean;\n isNsfw?: boolean;\n creator?: string;\n tokenCount?: string;\n metadataDisabled?: boolean;\n openseaVerificationStatus?: string;\n floorAskPrice?: Price;\n royaltiesBps?: number;\n royalties?: Royalties[];\n floorAsk?: FloorAskCollection;\n};\n\nexport type Collection = TokenCollection & CollectionResponse;\n\nexport type Royalties = {\n bps?: number;\n recipient?: string;\n};\n\nexport type Ownership = {\n tokenCount?: string;\n onSaleCount?: string;\n floorAsk?: FloorAsk;\n acquiredAt?: string;\n};\n\nexport type FloorAsk = {\n id?: string;\n price?: Price;\n maker?: string;\n kind?: string;\n validFrom?: number;\n validUntil?: number;\n source?: Source;\n rawData?: Metadata;\n isNativeOffChainCancellable?: boolean;\n};\n\nexport type Price = {\n currency?: {\n contract?: string;\n name?: string;\n symbol?: string;\n decimals?: number;\n chainId?: number;\n };\n amount?: {\n raw?: string;\n decimal?: number;\n usd?: number;\n native?: number;\n };\n netAmount?: {\n raw?: string;\n decimal?: number;\n usd?: number;\n native?: number;\n };\n};\n\nexport type Metadata = {\n imageOriginal?: string;\n tokenURI?: string;\n};\n\nexport const MAX_GET_COLLECTION_BATCH_SIZE = 20;\n\n/**\n * Controller that passively detects nfts for a user address\n */\nexport class NftDetectionController extends BaseController<\n typeof controllerName,\n NFTDetectionControllerState,\n NftDetectionControllerMessenger\n> {\n #disabled: boolean;\n\n readonly #addNft: NftController['addNft'];\n\n readonly #getNftState: () => NftControllerState;\n\n #inProcessNftFetchingUpdates: Record<`${Hex}:${string}`, Promise<void>>;\n\n /**\n * The controller options\n *\n * @param options - The controller options.\n * @param options.messenger - A reference to the messaging system.\n * @param options.disabled - Represents previous value of useNftDetection. Used to detect changes of useNftDetection. Default value is true.\n * @param options.addNft - Add an NFT.\n * @param options.getNftState - Gets the current state of the Assets controller.\n */\n constructor({\n messenger,\n disabled = false,\n addNft,\n getNftState,\n }: {\n messenger: NftDetectionControllerMessenger;\n disabled: boolean;\n addNft: NftController['addNft'];\n getNftState: () => NftControllerState;\n }) {\n super({\n name: controllerName,\n messenger,\n metadata: {},\n state: {},\n });\n this.#disabled = disabled;\n this.#inProcessNftFetchingUpdates = {};\n\n this.#getNftState = getNftState;\n this.#addNft = addNft;\n\n this.messagingSystem.subscribe(\n 'PreferencesController:stateChange',\n this.#onPreferencesControllerStateChange.bind(this),\n );\n }\n\n /**\n * Checks whether network is mainnet or not.\n *\n * @returns Whether current network is mainnet.\n */\n isMainnet(): boolean {\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 chainId === ChainId.mainnet;\n }\n\n isMainnetByNetworkClientId(networkClient: NetworkClient): boolean {\n return networkClient.configuration.chainId === ChainId.mainnet;\n }\n\n /**\n * Handles the state change of the preference controller.\n * @param preferencesState - The new state of the preference controller.\n * @param preferencesState.useNftDetection - Boolean indicating user preference on NFT detection.\n */\n #onPreferencesControllerStateChange({ useNftDetection }: PreferencesState) {\n if (!useNftDetection !== this.#disabled) {\n this.#disabled = !useNftDetection;\n }\n }\n\n #getOwnerNftApi({\n chainId,\n address,\n next,\n }: {\n chainId: string;\n address: string;\n next?: string;\n }) {\n return `${\n NFT_API_BASE_URL as string\n }/users/${address}/tokens?chainIds=${chainId}&limit=50&includeTopBid=true&continuation=${\n next ?? ''\n }`;\n }\n\n async #getOwnerNfts(\n address: string,\n chainId: Hex,\n cursor: string | undefined,\n ) {\n // Convert hex chainId to number\n const convertedChainId = convertHexToDecimal(chainId).toString();\n const url = this.#getOwnerNftApi({\n chainId: convertedChainId,\n address,\n next: cursor,\n });\n const nftApiResponse: ReservoirResponse = await handleFetch(url, {\n headers: {\n Version: NFT_API_VERSION,\n },\n });\n return nftApiResponse;\n }\n\n /**\n * Triggers asset ERC721 token auto detection on mainnet. Any newly detected NFTs are\n * added.\n *\n * @param options - Options bag.\n * @param options.networkClientId - The network client ID to detect NFTs on.\n * @param options.userAddress - The address to detect NFTs for.\n */\n async detectNfts(options?: {\n networkClientId?: NetworkClientId;\n userAddress?: string;\n }) {\n const userAddress =\n options?.userAddress ??\n this.messagingSystem.call('AccountsController:getSelectedAccount')\n .address;\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\n /* istanbul ignore if */\n if (!supportedNftDetectionNetworks.includes(chainId) || this.#disabled) {\n return;\n }\n /* istanbul ignore else */\n if (!userAddress) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n const updateKey: `${Hex}:${string}` = `${chainId}:${userAddress}`;\n if (updateKey in this.#inProcessNftFetchingUpdates) {\n // This prevents redundant updates\n // This promise is resolved after the in-progress update has finished,\n // and state has been updated.\n await this.#inProcessNftFetchingUpdates[updateKey];\n return;\n }\n\n const {\n promise: inProgressUpdate,\n resolve: updateSucceeded,\n reject: updateFailed,\n } = createDeferredPromise({ suppressUnhandledRejection: true });\n this.#inProcessNftFetchingUpdates[updateKey] = inProgressUpdate;\n\n let next;\n let apiNfts: TokensResponse[] = [];\n let resultNftApi: ReservoirResponse;\n try {\n do {\n resultNftApi = await this.#getOwnerNfts(userAddress, chainId, next);\n apiNfts = resultNftApi.tokens.filter(\n (elm) =>\n elm.token.isSpam === false &&\n (elm.blockaidResult?.result_type\n ? elm.blockaidResult?.result_type === BlockaidResultType.Benign\n : true),\n );\n // Retrieve collections from apiNfts\n // contract and collection.id are equal for simple contract addresses; this is to exclude cases for shared contracts\n const collections = apiNfts.reduce<string[]>((acc, currValue) => {\n if (\n !acc.includes(currValue.token.contract) &&\n currValue.token.contract === currValue?.token?.collection?.id\n ) {\n acc.push(currValue.token.contract);\n }\n return acc;\n }, []);\n\n if (collections.length !== 0) {\n // Call API to retrive collections infos\n // The api accept a max of 20 contracts\n const collectionResponse: GetCollectionsResponse =\n await reduceInBatchesSerially({\n values: collections,\n batchSize: MAX_GET_COLLECTION_BATCH_SIZE,\n eachBatch: async (allResponses, batch) => {\n const params = new URLSearchParams(\n batch.map((s) => ['contract', s]),\n );\n params.append('chainId', '1'); // Adding chainId 1 because we are only detecting for mainnet\n const collectionResponseForBatch = await fetchWithErrorHandling(\n {\n url: `${\n NFT_API_BASE_URL as string\n }/collections?${params.toString()}`,\n options: {\n headers: {\n Version: NFT_API_VERSION,\n },\n },\n timeout: NFT_API_TIMEOUT,\n },\n );\n\n return {\n ...allResponses,\n ...collectionResponseForBatch,\n };\n },\n initialResult: {},\n });\n\n // Add collections response fields to newnfts\n if (collectionResponse.collections?.length) {\n apiNfts.forEach((singleNFT) => {\n const found = collectionResponse.collections.find(\n (elm) =>\n elm.id?.toLowerCase() ===\n singleNFT.token.contract.toLowerCase(),\n );\n if (found) {\n singleNFT.token = {\n ...singleNFT.token,\n collection: {\n ...(singleNFT.token.collection ?? {}),\n creator: found?.creator,\n openseaVerificationStatus: found?.openseaVerificationStatus,\n contractDeployedAt: found.contractDeployedAt,\n ownerCount: found.ownerCount,\n topBid: found.topBid,\n },\n };\n }\n });\n }\n }\n\n // Proceed to add NFTs\n const addNftPromises = apiNfts.map(async (nft) => {\n const {\n tokenId,\n contract,\n kind,\n image: imageUrl,\n imageSmall: imageThumbnailUrl,\n metadata: { imageOriginal: imageOriginalUrl } = {},\n name,\n description,\n attributes,\n topBid,\n lastSale,\n rarityRank,\n rarityScore,\n collection,\n } = nft.token;\n\n let ignored;\n /* istanbul ignore else */\n const { ignoredNfts } = this.#getNftState();\n if (ignoredNfts.length) {\n ignored = ignoredNfts.find((c) => {\n /* istanbul ignore next */\n return (\n c.address === toChecksumHexAddress(contract) &&\n c.tokenId === tokenId\n );\n });\n }\n\n /* istanbul ignore else */\n if (!ignored) {\n /* istanbul ignore next */\n const nftMetadata: NftMetadata = Object.assign(\n {},\n { name },\n description && { description },\n imageUrl && { image: imageUrl },\n imageThumbnailUrl && { imageThumbnail: imageThumbnailUrl },\n imageOriginalUrl && { imageOriginal: imageOriginalUrl },\n kind && { standard: kind.toUpperCase() },\n lastSale && { lastSale },\n attributes && { attributes },\n topBid && { topBid },\n rarityRank && { rarityRank },\n rarityScore && { rarityScore },\n collection && { collection },\n );\n await this.#addNft(contract, tokenId, {\n nftMetadata,\n userAddress,\n source: Source.Detected,\n networkClientId: options?.networkClientId,\n });\n }\n });\n await Promise.all(addNftPromises);\n } while ((next = resultNftApi.continuation));\n updateSucceeded();\n } catch (error) {\n updateFailed(error);\n throw error;\n } finally {\n delete this.#inProcessNftFetchingUpdates[updateKey];\n }\n }\n}\n\n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