@metamask-previews/assets-controllers 34.0.0-preview-ece76bc → 34.0.0-preview-6c18bc6

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.
@@ -2,7 +2,7 @@
2
2
 
3
3
 
4
4
 
5
- var _chunkRI6CELGJjs = require('./chunk-RI6CELGJ.js');
5
+ var _chunkEJBF33KQjs = require('./chunk-EJBF33KQ.js');
6
6
  require('./chunk-RGHTNZQ6.js');
7
7
  require('./chunk-NYVA7ZTQ.js');
8
8
  require('./chunk-Z4BLTVTB.js');
@@ -10,5 +10,5 @@ require('./chunk-Z4BLTVTB.js');
10
10
 
11
11
 
12
12
 
13
- exports.NftController = _chunkRI6CELGJjs.NftController; exports.default = _chunkRI6CELGJjs.NftController_default; exports.getDefaultNftControllerState = _chunkRI6CELGJjs.getDefaultNftControllerState;
13
+ exports.NftController = _chunkEJBF33KQjs.NftController; exports.default = _chunkEJBF33KQjs.NftController_default; exports.getDefaultNftControllerState = _chunkEJBF33KQjs.getDefaultNftControllerState;
14
14
  //# sourceMappingURL=NftController.js.map
@@ -2,7 +2,7 @@ import {
2
2
  NftController,
3
3
  NftController_default,
4
4
  getDefaultNftControllerState
5
- } from "./chunk-C2ZDNCFD.mjs";
5
+ } from "./chunk-HPYR2PGE.mjs";
6
6
  import "./chunk-CP3HC7AQ.mjs";
7
7
  import "./chunk-VELPHITE.mjs";
8
8
  import "./chunk-XUI43LEZ.mjs";
@@ -44,7 +44,7 @@ var getDefaultNftControllerState = () => ({
44
44
  allNfts: {},
45
45
  ignoredNfts: []
46
46
  });
47
- var _mutex, _selectedAccountId, _chainId, _ipfsGateway, _openSeaEnabled, _useIpfsSubdomains, _isIpfsGatewayEnabled, _getERC721AssetName, _getERC721AssetSymbol, _getERC721TokenURI, _getERC721OwnerOf, _getERC1155BalanceOf, _getERC1155TokenURI, _onNftAdded, _onNetworkControllerNetworkDidChange, onNetworkControllerNetworkDidChange_fn, _onPreferencesControllerStateChange, onPreferencesControllerStateChange_fn, _onSelectedAccountChange, onSelectedAccountChange_fn, _updateNestedNftState, updateNestedNftState_fn, _getNftInformationFromApi, getNftInformationFromApi_fn, _getNftInformationFromTokenURI, getNftInformationFromTokenURI_fn, _getNftURIAndStandard, getNftURIAndStandard_fn, _getNftInformation, getNftInformation_fn, _parseNftInfoResults, parseNftInfoResults_fn, _getNftContractInformationFromContract, getNftContractInformationFromContract_fn, _getNftContractInformation, getNftContractInformation_fn, _addIndividualNft, addIndividualNft_fn, _addNftContract, addNftContract_fn, _removeAndIgnoreIndividualNft, removeAndIgnoreIndividualNft_fn, _removeIndividualNft, removeIndividualNft_fn, _removeNftContract, removeNftContract_fn, _validateWatchNft, validateWatchNft_fn, _getCorrectChainId, getCorrectChainId_fn, _getAddressOrSelectedAddress, getAddressOrSelectedAddress_fn, _updateNftUpdateForAccount, updateNftUpdateForAccount_fn;
47
+ var _mutex, _selectedAccountId, _chainId, _ipfsGateway, _openSeaEnabled, _useIpfsSubdomains, _isIpfsGatewayEnabled, _getERC721AssetName, _getERC721AssetSymbol, _getERC721TokenURI, _getERC721OwnerOf, _getERC1155BalanceOf, _getERC1155TokenURI, _onNftAdded, _onNetworkControllerNetworkDidChange, onNetworkControllerNetworkDidChange_fn, _onPreferencesControllerStateChange, onPreferencesControllerStateChange_fn, _onSelectedAccountChange, onSelectedAccountChange_fn, _updateNestedNftState, updateNestedNftState_fn, _getNftCollectionInformationFromApi, getNftCollectionInformationFromApi_fn, _getNftCollectionApi, getNftCollectionApi_fn, _getNftInformationFromApi, getNftInformationFromApi_fn, _getNftInformationFromTokenURI, getNftInformationFromTokenURI_fn, _getNftURIAndStandard, getNftURIAndStandard_fn, _getNftInformation, getNftInformation_fn, _getNftContractInformationFromContract, getNftContractInformationFromContract_fn, _getNftContractInformation, getNftContractInformation_fn, _addIndividualNft, addIndividualNft_fn, _addNftContract, addNftContract_fn, _removeAndIgnoreIndividualNft, removeAndIgnoreIndividualNft_fn, _removeIndividualNft, removeIndividualNft_fn, _removeNftContract, removeNftContract_fn, _validateWatchNft, validateWatchNft_fn, _getCorrectChainId, getCorrectChainId_fn, _getAddressOrSelectedAddress, getAddressOrSelectedAddress_fn, _updateNftUpdateForAccount, updateNftUpdateForAccount_fn;
48
48
  var NftController = class extends _basecontroller.BaseController {
49
49
  /**
50
50
  * Creates an NftController instance.
@@ -120,6 +120,8 @@ var NftController = class extends _basecontroller.BaseController {
120
120
  * @param passedConfig.chainId - the chainId passed through the NFT detection flow to ensure assets are stored to the correct account
121
121
  */
122
122
  _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _updateNestedNftState);
123
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _getNftCollectionInformationFromApi);
124
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _getNftCollectionApi);
123
125
  /**
124
126
  * Request individual NFT information from NFT API.
125
127
  *
@@ -155,9 +157,6 @@ var NftController = class extends _basecontroller.BaseController {
155
157
  * @returns Promise resolving to the current NFT name and image.
156
158
  */
157
159
  _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _getNftInformation);
158
- // This function is a good candidate for a utility function since it doesn't do anything with context
159
- // But since types are defined here, I will leave it here to prevent circular dependencies
160
- _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _parseNftInfoResults);
161
160
  /**
162
161
  * Request NFT contract information from the contract itself.
163
162
  *
@@ -285,6 +284,17 @@ var NftController = class extends _basecontroller.BaseController {
285
284
  getNftApi() {
286
285
  return `${_controllerutils.NFT_API_BASE_URL}/tokens`;
287
286
  }
287
+ /**
288
+ * Fetches NFT Collection Metadata from the NFT API.
289
+ *
290
+ * @param contractAddress - The contract address of the NFT.
291
+ * @param chainId - The chain ID of the network where the NFT is located.
292
+ *
293
+ * @returns The NFT metadata.
294
+ */
295
+ async fetchNftCollectionMetadata(contractAddress, chainId) {
296
+ return await _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getNftCollectionInformationFromApi, getNftCollectionInformationFromApi_fn).call(this, contractAddress, chainId);
297
+ }
288
298
  /**
289
299
  * Adds a new suggestedAsset to state. Parameters will be validated according to
290
300
  * asset type being watched. A `<suggestedNftMeta.id>:pending` hub event will be emitted once added.
@@ -795,23 +805,6 @@ var NftController = class extends _basecontroller.BaseController {
795
805
  true
796
806
  );
797
807
  }
798
- /**
799
- * Fetches NFT metadata from the NFT API.
800
- *
801
- * @param contractAddress - The contract address of the NFT.
802
- * @param tokenId - The token ID of the NFT.
803
- * @param chainId - The chain ID of the network where the NFT is located.
804
- *
805
- * @returns The NFT metadata.
806
- */
807
- async fetchNftMetadata(contractAddress, tokenId, chainId) {
808
- const nftApiMetadata = await _controllerutils.safelyExecute.call(void 0,
809
- () => _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getNftInformationFromApi, getNftInformationFromApi_fn).call(this, contractAddress, tokenId, {
810
- chainId
811
- })
812
- );
813
- return _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _parseNftInfoResults, parseNftInfoResults_fn).call(this, void 0, nftApiMetadata);
814
- }
815
808
  };
816
809
  _mutex = new WeakMap();
817
810
  _selectedAccountId = new WeakMap();
@@ -884,27 +877,39 @@ updateNestedNftState_fn = function(newCollection, baseStateKey, { userAddress, c
884
877
  };
885
878
  });
886
879
  };
887
- _getNftInformationFromApi = new WeakSet();
888
- getNftInformationFromApi_fn = async function(contractAddress, tokenId, {
889
- chainId = "0x1",
890
- includeAttributes = false,
891
- includeLastSale = false,
892
- includeTopBid = false
893
- }) {
880
+ _getNftCollectionInformationFromApi = new WeakSet();
881
+ getNftCollectionInformationFromApi_fn = async function(contractAddress, chainId) {
894
882
  const urlParams = new URLSearchParams({
895
- chainIds: chainId,
896
- tokens: `${contractAddress}:${tokenId}`
897
- });
898
- const optionalBooleanUrlParams = {
899
- includeAttributes,
900
- includeLastSale,
901
- includeTopBid
902
- };
903
- Object.entries(optionalBooleanUrlParams).forEach(([key, value]) => {
904
- if (value) {
905
- urlParams.append(key, "true");
883
+ chainId,
884
+ contract: `${contractAddress}`
885
+ }).toString();
886
+ const nftCollectionInformation = await _controllerutils.handleFetch.call(void 0, `${_chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getNftCollectionApi, getNftCollectionApi_fn).call(this)}?${urlParams}`, {
887
+ headers: {
888
+ Version: "1"
906
889
  }
907
890
  });
891
+ if (nftCollectionInformation?.collections.length === 0) {
892
+ return {
893
+ collection: null
894
+ };
895
+ }
896
+ return {
897
+ collection: nftCollectionInformation.collections[0]
898
+ };
899
+ };
900
+ _getNftCollectionApi = new WeakSet();
901
+ getNftCollectionApi_fn = function() {
902
+ return `${_controllerutils.NFT_API_BASE_URL}/collections`;
903
+ };
904
+ _getNftInformationFromApi = new WeakSet();
905
+ getNftInformationFromApi_fn = async function(contractAddress, tokenId) {
906
+ const urlParams = new URLSearchParams({
907
+ chainIds: "1",
908
+ tokens: `${contractAddress}:${tokenId}`,
909
+ includeTopBid: "true",
910
+ includeAttributes: "true",
911
+ includeLastSale: "true"
912
+ }).toString();
908
913
  const nftInformation = await _controllerutils.fetchWithErrorHandling.call(void 0, {
909
914
  url: `${this.getNftApi()}?${urlParams}`,
910
915
  options: {
@@ -1051,17 +1056,9 @@ getNftInformation_fn = async function(contractAddress, tokenId, networkClientId)
1051
1056
  () => _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getNftInformationFromTokenURI, getNftInformationFromTokenURI_fn).call(this, contractAddress, tokenId, networkClientId)
1052
1057
  ),
1053
1058
  _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _openSeaEnabled) && chainId === "0x1" ? _controllerutils.safelyExecute.call(void 0,
1054
- () => _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getNftInformationFromApi, getNftInformationFromApi_fn).call(this, contractAddress, tokenId, {
1055
- includeAttributes: true,
1056
- includeLastSale: true,
1057
- includeTopBid: true
1058
- })
1059
+ () => _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getNftInformationFromApi, getNftInformationFromApi_fn).call(this, contractAddress, tokenId)
1059
1060
  ) : void 0
1060
1061
  ]);
1061
- return _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _parseNftInfoResults, parseNftInfoResults_fn).call(this, blockchainMetadata, nftApiMetadata);
1062
- };
1063
- _parseNftInfoResults = new WeakSet();
1064
- parseNftInfoResults_fn = function(blockchainMetadata, nftApiMetadata) {
1065
1062
  return {
1066
1063
  ...nftApiMetadata,
1067
1064
  name: blockchainMetadata?.name ?? nftApiMetadata?.name ?? null,
@@ -1395,4 +1392,4 @@ var NftController_default = NftController;
1395
1392
 
1396
1393
 
1397
1394
  exports.getDefaultNftControllerState = getDefaultNftControllerState; exports.NftController = NftController; exports.NftController_default = NftController_default;
1398
- //# sourceMappingURL=chunk-RI6CELGJ.js.map
1395
+ //# sourceMappingURL=chunk-EJBF33KQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/NftController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAW1B;AAAA,EACE;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAYP,SAAS,iBAAiB;AAE1B,SAAS,gBAAgB;AACzB,SAAS,aAAa;AACtB,OAAO,QAAQ;AACf,SAAS,MAAM,cAAc;AAqJ7B,IAAM,wBAAwB;AAAA,EAC5B,iBAAiB,EAAE,SAAS,MAAM,WAAW,MAAM;AAAA,EACnD,SAAS,EAAE,SAAS,MAAM,WAAW,MAAM;AAAA,EAC3C,aAAa,EAAE,SAAS,MAAM,WAAW,MAAM;AACjD;AAEA,IAAM,qBAAqB;AAC3B,IAAM,+BAA+B;AAUrC,IAAM,iBAAiB;AAwChB,IAAM,+BAA+B,OAA2B;AAAA,EACrE,iBAAiB,CAAC;AAAA,EAClB,SAAS,CAAC;AAAA,EACV,aAAa,CAAC;AAChB;AA7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ACnB,UAAM;AAAA,MACJ,eAAe,EAAE,QAAQ;AAAA,IAC3B,IAAI,KAAK,gBAAgB;AAAA,MACvB;AAAA,MACA;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACA,SAAO,mBAAK;AACd;AA2rBA;AAAA,iCAA4B,SAAC,SAAqC;AAChE,MAAI,SAAS;AACX,WAAO;AAAA,EACT;AAGA,QAAM,kBAAkB,KAAK,gBAAgB;AAAA,IAC3C;AAAA,IACA,mBAAK;AAAA,EACP;AACA,SAAO,iBAAiB,WAAW;AACrC;AAEM;AAAA,+BAA0B,eAAC,SAA0B;AACzD,QAAM,OACJ,KAAK,MAAM,QAAQ,QAAQ,OAAO,IAAI,mBAAK,SAAQ,KAAK,CAAC;AAG3D,QAAM,eAAe,KAAK;AAAA,IACxB,CAAC,cACC,CAAC,UAAU,QAAQ,CAAC,UAAU,eAAe,CAAC,UAAU;AAAA,EAC5D;AACA,MAAI,aAAa,WAAW,GAAG;AAC7B,UAAM,KAAK,kBAAkB;AAAA,MAC3B,MAAM;AAAA,MACN,aAAa,QAAQ;AAAA,IACvB,CAAC;AAAA,EACH;AACF;AAGF,IAAO,wBAAQ","sourcesContent":["import { isAddress } from '@ethersproject/address';\nimport type {\n AccountsControllerSelectedEvmAccountChangeEvent,\n AccountsControllerGetAccountAction,\n AccountsControllerGetSelectedAccountAction,\n} from '@metamask/accounts-controller';\nimport type { AddApprovalRequest } from '@metamask/approval-controller';\nimport type {\n RestrictedControllerMessenger,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport {\n BaseController,\n type ControllerGetStateAction,\n} from '@metamask/base-controller';\nimport {\n safelyExecute,\n handleFetch,\n toChecksumHexAddress,\n BNToHex,\n fetchWithErrorHandling,\n IPFS_DEFAULT_GATEWAY_URL,\n ERC721,\n ERC1155,\n ApprovalType,\n NFT_API_BASE_URL,\n} from '@metamask/controller-utils';\nimport { type InternalAccount } from '@metamask/keyring-api';\nimport type {\n NetworkClientId,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerNetworkDidChangeEvent,\n NetworkState,\n} from '@metamask/network-controller';\nimport type {\n PreferencesControllerStateChangeEvent,\n PreferencesState,\n} from '@metamask/preferences-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { remove0x } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\nimport BN from 'bn.js';\nimport { v4 as random } from 'uuid';\n\nimport type { AssetsContractController } from './AssetsContractController';\nimport { compareNftMetadata, getFormattedIpfsUrl } from './assetsUtil';\nimport { Source } from './constants';\nimport type {\n ApiNftContract,\n ReservoirResponse,\n Collection,\n Attributes,\n LastSale,\n} from './NftDetectionController';\n\ntype NFTStandardType = 'ERC721' | 'ERC1155';\n\ntype SuggestedNftMeta = {\n asset: { address: string; tokenId: string } & NftMetadata;\n id: string;\n time: number;\n type: NFTStandardType;\n interactingAddress: string;\n origin: string;\n};\n\n/**\n * @type Nft\n *\n * NFT representation\n * @property address - Hex address of a ERC721 contract\n * @property description - The NFT description\n * @property image - URI of custom NFT image associated with this tokenId\n * @property name - Name associated with this tokenId and contract address\n * @property tokenId - The NFT identifier\n * @property numberOfSales - Number of sales\n * @property backgroundColor - The background color to be displayed with the item\n * @property imagePreview - URI of a smaller image associated with this NFT\n * @property imageThumbnail - URI of a thumbnail image associated with this NFT\n * @property imageOriginal - URI of the original image associated with this NFT\n * @property animation - URI of a animation associated with this NFT\n * @property animationOriginal - URI of the original animation associated with this NFT\n * @property externalLink - External link containing additional information\n * @property creator - The NFT owner information object\n * @property isCurrentlyOwned - Boolean indicating whether the address/chainId combination where it's currently stored currently owns this NFT\n * @property transactionId - Transaction Id associated with the NFT\n */\nexport type Nft =\n | {\n tokenId: string;\n address: string;\n isCurrentlyOwned?: boolean;\n } & NftMetadata;\n\ntype NftUpdate = {\n nft: Nft;\n newMetadata: NftMetadata;\n};\n\n/**\n * @type NftContract\n *\n * NFT contract information representation\n * @property name - Contract name\n * @property logo - Contract logo\n * @property address - Contract address\n * @property symbol - Contract symbol\n * @property description - Contract description\n * @property totalSupply - Total supply of NFTs\n * @property assetContractType - The NFT type, it could be `semi-fungible` or `non-fungible`\n * @property createdDate - Creation date\n * @property schemaName - The schema followed by the contract, it could be `ERC721` or `ERC1155`\n * @property externalLink - External link containing additional information\n */\nexport type NftContract = {\n name?: string;\n logo?: string;\n address: string;\n symbol?: string;\n description?: string;\n totalSupply?: string;\n assetContractType?: string;\n createdDate?: string;\n schemaName?: string;\n externalLink?: string;\n};\n\n/**\n * @type NftMetadata\n *\n * NFT custom information\n * @property name - NFT custom name\n * @property description - The NFT description\n * @property numberOfSales - Number of sales\n * @property backgroundColor - The background color to be displayed with the item\n * @property image - Image custom image URI\n * @property imagePreview - URI of a smaller image associated with this NFT\n * @property imageThumbnail - URI of a thumbnail image associated with this NFT\n * @property imageOriginal - URI of the original image associated with this NFT\n * @property animation - URI of a animation associated with this NFT\n * @property animationOriginal - URI of the original animation associated with this NFT\n * @property externalLink - External link containing additional information\n * @property creator - The NFT owner information object\n * @property standard - NFT standard name for the NFT, e.g., ERC-721 or ERC-1155\n */\nexport type NftMetadata = {\n name: string | null;\n description: string | null;\n image: string | null;\n standard: string | null;\n favorite?: boolean;\n numberOfSales?: number;\n backgroundColor?: string;\n imagePreview?: string;\n imageThumbnail?: string;\n imageOriginal?: string;\n animation?: string;\n animationOriginal?: string;\n externalLink?: string;\n creator?: string;\n transactionId?: string;\n tokenURI?: string | null;\n collection?: Collection;\n address?: string;\n attributes?: Attributes;\n lastSale?: LastSale;\n rarityRank?: string;\n};\n\n/**\n * @type NftControllerState\n *\n * NFT controller state\n * @property allNftContracts - Object containing NFT contract information\n * @property allNfts - Object containing NFTs per account and network\n * @property ignoredNfts - List of NFTs that should be ignored\n */\nexport type NftControllerState = {\n allNftContracts: {\n [key: string]: {\n [chainId: Hex]: NftContract[];\n };\n };\n allNfts: {\n [key: string]: {\n [chainId: Hex]: Nft[];\n };\n };\n ignoredNfts: Nft[];\n};\n\nconst nftControllerMetadata = {\n allNftContracts: { persist: true, anonymous: false },\n allNfts: { persist: true, anonymous: false },\n ignoredNfts: { persist: true, anonymous: false },\n};\n\nconst ALL_NFTS_STATE_KEY = 'allNfts';\nconst ALL_NFTS_CONTRACTS_STATE_KEY = 'allNftContracts';\n\ntype NftAsset = {\n address: string;\n tokenId: string;\n};\n\n/**\n * The name of the {@link NftController}.\n */\nconst controllerName = 'NftController';\n\nexport type NftControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n NftControllerState\n>;\nexport type NftControllerActions = NftControllerGetStateAction;\n\n/**\n * The external actions available to the {@link NftController}.\n */\nexport type AllowedActions =\n | AddApprovalRequest\n | AccountsControllerGetAccountAction\n | AccountsControllerGetSelectedAccountAction\n | NetworkControllerGetNetworkClientByIdAction;\n\nexport type AllowedEvents =\n | PreferencesControllerStateChangeEvent\n | NetworkControllerNetworkDidChangeEvent\n | AccountsControllerSelectedEvmAccountChangeEvent;\n\nexport type NftControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n NftControllerState\n>;\n\nexport type NftControllerEvents = NftControllerStateChangeEvent;\n\n/**\n * The messenger of the {@link NftController}.\n */\nexport type NftControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n NftControllerActions | AllowedActions,\n NftControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\nexport const getDefaultNftControllerState = (): NftControllerState => ({\n allNftContracts: {},\n allNfts: {},\n ignoredNfts: [],\n});\n\n/**\n * Controller that stores assets and exposes convenience methods\n */\nexport class NftController extends BaseController<\n typeof controllerName,\n NftControllerState,\n NftControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n /**\n * Optional API key to use with opensea\n */\n openSeaApiKey?: string;\n\n #selectedAccountId: string;\n\n #chainId: Hex;\n\n #ipfsGateway: string;\n\n #openSeaEnabled: boolean;\n\n #useIpfsSubdomains: boolean;\n\n #isIpfsGatewayEnabled: boolean;\n\n readonly #getERC721AssetName: AssetsContractController['getERC721AssetName'];\n\n readonly #getERC721AssetSymbol: AssetsContractController['getERC721AssetSymbol'];\n\n readonly #getERC721TokenURI: AssetsContractController['getERC721TokenURI'];\n\n readonly #getERC721OwnerOf: AssetsContractController['getERC721OwnerOf'];\n\n readonly #getERC1155BalanceOf: AssetsContractController['getERC1155BalanceOf'];\n\n readonly #getERC1155TokenURI: AssetsContractController['getERC1155TokenURI'];\n\n readonly #onNftAdded?: (data: {\n address: string;\n symbol: string | undefined;\n tokenId: string;\n standard: string | null;\n source: Source;\n }) => void;\n\n /**\n * Creates an NftController instance.\n *\n * @param options - The controller options.\n * @param options.chainId - The chain ID of the current network.\n * @param options.ipfsGateway - The configured IPFS gateway.\n * @param options.openSeaEnabled - Controls whether the OpenSea API is used.\n * @param options.useIpfsSubdomains - Controls whether IPFS subdomains are used.\n * @param options.isIpfsGatewayEnabled - Controls whether IPFS is enabled or not.\n * @param options.getERC721AssetName - Gets the name of the asset at the given address.\n * @param options.getERC721AssetSymbol - Gets the symbol of the asset at the given address.\n * @param options.getERC721TokenURI - Gets the URI of the ERC721 token at the given address, with the given ID.\n * @param options.getERC721OwnerOf - Get the owner of a ERC-721 NFT.\n * @param options.getERC1155BalanceOf - Gets balance of a ERC-1155 NFT.\n * @param options.getERC1155TokenURI - Gets the URI of the ERC1155 token at the given address, with the given ID.\n * @param options.onNftAdded - Callback that is called when an NFT is added. Currently used pass data\n * for tracking the NFT added event.\n * @param options.messenger - The controller messenger.\n * @param options.state - Initial state to set on this controller.\n */\n constructor({\n chainId: initialChainId,\n ipfsGateway = IPFS_DEFAULT_GATEWAY_URL,\n openSeaEnabled = false,\n useIpfsSubdomains = true,\n isIpfsGatewayEnabled = true,\n getERC721AssetName,\n getERC721AssetSymbol,\n getERC721TokenURI,\n getERC721OwnerOf,\n getERC1155BalanceOf,\n getERC1155TokenURI,\n onNftAdded,\n messenger,\n state = {},\n }: {\n chainId: Hex;\n ipfsGateway?: string;\n openSeaEnabled?: boolean;\n useIpfsSubdomains?: boolean;\n isIpfsGatewayEnabled?: boolean;\n getERC721AssetName: AssetsContractController['getERC721AssetName'];\n getERC721AssetSymbol: AssetsContractController['getERC721AssetSymbol'];\n getERC721TokenURI: AssetsContractController['getERC721TokenURI'];\n getERC721OwnerOf: AssetsContractController['getERC721OwnerOf'];\n getERC1155BalanceOf: AssetsContractController['getERC1155BalanceOf'];\n getERC1155TokenURI: AssetsContractController['getERC1155TokenURI'];\n onNftAdded?: (data: {\n address: string;\n symbol: string | undefined;\n tokenId: string;\n standard: string | null;\n source: string;\n }) => void;\n messenger: NftControllerMessenger;\n state?: Partial<NftControllerState>;\n }) {\n super({\n name: controllerName,\n metadata: nftControllerMetadata,\n messenger,\n state: {\n ...getDefaultNftControllerState(),\n ...state,\n },\n });\n\n this.#selectedAccountId = this.messagingSystem.call(\n 'AccountsController:getSelectedAccount',\n ).id;\n this.#chainId = initialChainId;\n this.#ipfsGateway = ipfsGateway;\n this.#openSeaEnabled = openSeaEnabled;\n this.#useIpfsSubdomains = useIpfsSubdomains;\n this.#isIpfsGatewayEnabled = isIpfsGatewayEnabled;\n\n this.#getERC721AssetName = getERC721AssetName;\n this.#getERC721AssetSymbol = getERC721AssetSymbol;\n this.#getERC721TokenURI = getERC721TokenURI;\n this.#getERC721OwnerOf = getERC721OwnerOf;\n this.#getERC1155BalanceOf = getERC1155BalanceOf;\n this.#getERC1155TokenURI = getERC1155TokenURI;\n this.#onNftAdded = onNftAdded;\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 this.#onPreferencesControllerStateChange.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n this.#onNetworkControllerNetworkDidChange.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'AccountsController:selectedEvmAccountChange',\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.#onSelectedAccountChange.bind(this),\n );\n }\n\n /**\n * Handles the network change on the network controller.\n * @param networkState - The new state of the preference controller.\n * @param networkState.selectedNetworkClientId - The current selected network client id.\n */\n #onNetworkControllerNetworkDidChange({\n selectedNetworkClientId,\n }: NetworkState) {\n const {\n configuration: { chainId },\n } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n this.#chainId = chainId;\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.ipfsGateway - The configured IPFS gateway.\n * @param preferencesState.openSeaEnabled - Controls whether the OpenSea API is used.\n * @param preferencesState.isIpfsGatewayEnabled - Controls whether IPFS is enabled or not.\n */\n async #onPreferencesControllerStateChange({\n ipfsGateway,\n openSeaEnabled,\n isIpfsGatewayEnabled,\n }: PreferencesState) {\n const selectedAccount = this.messagingSystem.call(\n 'AccountsController:getSelectedAccount',\n );\n this.#selectedAccountId = selectedAccount.id;\n this.#ipfsGateway = ipfsGateway;\n this.#openSeaEnabled = openSeaEnabled;\n this.#isIpfsGatewayEnabled = isIpfsGatewayEnabled;\n\n const needsUpdateNftMetadata =\n (isIpfsGatewayEnabled && ipfsGateway !== '') || openSeaEnabled;\n\n if (needsUpdateNftMetadata && selectedAccount) {\n await this.#updateNftUpdateForAccount(selectedAccount);\n }\n }\n\n /**\n * Handles the selected account change on the accounts controller.\n * @param internalAccount - The new selected account.\n */\n async #onSelectedAccountChange(internalAccount: InternalAccount) {\n const oldSelectedAccountId = this.#selectedAccountId;\n this.#selectedAccountId = internalAccount.id;\n\n const needsUpdateNftMetadata =\n ((this.#isIpfsGatewayEnabled && this.#ipfsGateway !== '') ||\n this.#openSeaEnabled) &&\n oldSelectedAccountId !== internalAccount.id;\n\n if (needsUpdateNftMetadata) {\n await this.#updateNftUpdateForAccount(internalAccount);\n }\n }\n\n getNftApi() {\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 `${NFT_API_BASE_URL}/tokens`;\n }\n\n /**\n * Helper method to update nested state for allNfts and allNftContracts.\n *\n * @param newCollection - the modified piece of state to update in the controller's store\n * @param baseStateKey - The root key in the store to update.\n * @param passedConfig - An object containing the selectedAddress and chainId that are passed through the auto-detection flow.\n * @param passedConfig.userAddress - the address passed through the NFT detection flow to ensure assets are stored to the correct account\n * @param passedConfig.chainId - the chainId passed through the NFT detection flow to ensure assets are stored to the correct account\n */\n #updateNestedNftState<\n Key extends typeof ALL_NFTS_STATE_KEY | typeof ALL_NFTS_CONTRACTS_STATE_KEY,\n NftCollection extends Key extends typeof ALL_NFTS_STATE_KEY\n ? Nft[]\n : NftContract[],\n >(\n newCollection: NftCollection,\n baseStateKey: Key,\n { userAddress, chainId }: { userAddress: string; chainId: Hex },\n ) {\n // userAddress can be an empty string if it is not set via an account change or in constructor\n // while this doesn't cause any issues, we want to ensure that we don't store assets to an empty string address\n if (!userAddress) {\n return;\n }\n\n this.update((state) => {\n const oldState = state[baseStateKey];\n const addressState = oldState[userAddress] || {};\n const newAddressState = {\n ...addressState,\n [chainId]: newCollection,\n };\n state[baseStateKey] = {\n ...oldState,\n [userAddress]: newAddressState,\n };\n });\n }\n\n /**\n * Fetches NFT Collection Metadata from the NFT API.\n *\n * @param contractAddress - The contract address of the NFT.\n * @param chainId - The chain ID of the network where the NFT is located.\n *\n * @returns The NFT metadata.\n */\n async fetchNftCollectionMetadata(\n contractAddress: string,\n chainId: Hex,\n ): Promise<{\n collection: Collection | null;\n }> {\n return await this.#getNftCollectionInformationFromApi(\n contractAddress,\n chainId,\n );\n }\n\n async #getNftCollectionInformationFromApi(\n contractAddress: string,\n chainId: Hex,\n ) {\n const urlParams = new URLSearchParams({\n chainId: chainId,\n contract: `${contractAddress}`,\n }).toString();\n\n const nftCollectionInformation: {\n collections: Collection[];\n continuation?: string;\n } = await handleFetch(`${this.#getNftCollectionApi()}?${urlParams}`, {\n headers: {\n Version: '1',\n },\n });\n\n if (nftCollectionInformation?.collections.length === 0) {\n return {\n collection: null,\n };\n }\n\n return {\n collection: nftCollectionInformation.collections[0],\n };\n }\n\n #getNftCollectionApi() {\n return `${NFT_API_BASE_URL}/collections`;\n }\n\n /**\n * Request individual NFT information from NFT API.\n *\n * @param contractAddress - Hex address of the NFT contract.\n * @param tokenId - The NFT identifier.\n * @returns Promise resolving to the current NFT name and image.\n */\n async #getNftInformationFromApi(\n contractAddress: string,\n tokenId: string,\n ): Promise<NftMetadata> {\n // TODO Parameterize this by chainId for non-mainnet token detection\n // Attempt to fetch the data with the nft-api\n const urlParams = new URLSearchParams({\n chainIds: '1',\n tokens: `${contractAddress}:${tokenId}`,\n includeTopBid: 'true',\n includeAttributes: 'true',\n includeLastSale: 'true',\n }).toString();\n const nftInformation: ReservoirResponse | undefined =\n await fetchWithErrorHandling({\n url: `${this.getNftApi()}?${urlParams}`,\n options: {\n headers: {\n Version: '1',\n },\n },\n });\n // if we were still unable to fetch the data we return out the default/null of `NftMetadata`\n if (!nftInformation?.tokens?.[0]?.token) {\n return {\n name: null,\n description: null,\n image: null,\n standard: null,\n };\n }\n\n // if we've reached this point, we have successfully fetched some data for nftInformation\n // now we reconfigure the data to conform to the `NftMetadata` type for storage.\n\n const {\n image,\n metadata: { imageOriginal } = {},\n name,\n description,\n collection,\n kind,\n rarityRank,\n rarity,\n attributes,\n lastSale,\n imageSmall,\n } = nftInformation.tokens[0].token;\n\n /* istanbul ignore next */\n const nftMetadata: NftMetadata = Object.assign(\n {},\n { name: name || null },\n { description: description || null },\n { image: image || null },\n collection?.creator && { creator: collection.creator },\n imageOriginal && { imageOriginal },\n imageSmall && { imageThumbnail: imageSmall },\n kind && { standard: kind.toUpperCase() },\n lastSale && { lastSale },\n attributes && { attributes },\n nftInformation.tokens[0].market?.topBid && {\n topBid: nftInformation.tokens[0].market?.topBid,\n },\n rarityRank && { rarityRank },\n rarity && { rarity },\n collection && { collection },\n );\n\n return nftMetadata;\n }\n\n /**\n * Request individual NFT information from contracts that follows Metadata Interface.\n *\n * @param contractAddress - Hex address of the NFT contract.\n * @param tokenId - The NFT identifier.\n * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving to the current NFT name and image.\n */\n async #getNftInformationFromTokenURI(\n contractAddress: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<NftMetadata> {\n const result = await this.#getNftURIAndStandard(\n contractAddress,\n tokenId,\n networkClientId,\n );\n let tokenURI = result[0];\n const standard = result[1];\n\n const hasIpfsTokenURI = tokenURI.startsWith('ipfs://');\n\n if (hasIpfsTokenURI && !this.#isIpfsGatewayEnabled) {\n return {\n image: null,\n name: null,\n description: null,\n standard: standard || null,\n favorite: false,\n tokenURI: tokenURI ?? null,\n };\n }\n\n const isDisplayNFTMediaToggleEnabled = this.#openSeaEnabled;\n if (!hasIpfsTokenURI && !isDisplayNFTMediaToggleEnabled) {\n return {\n image: null,\n name: null,\n description: null,\n standard: standard || null,\n favorite: false,\n tokenURI: tokenURI ?? null,\n };\n }\n\n if (hasIpfsTokenURI) {\n tokenURI = getFormattedIpfsUrl(\n this.#ipfsGateway,\n tokenURI,\n this.#useIpfsSubdomains,\n );\n }\n if (tokenURI.startsWith('data:image/')) {\n return {\n image: tokenURI,\n name: null,\n description: null,\n standard: standard || null,\n favorite: false,\n tokenURI: tokenURI ?? null,\n };\n }\n\n try {\n const object = await handleFetch(tokenURI);\n // TODO: Check image_url existence. This is not part of EIP721 nor EIP1155\n const image = Object.prototype.hasOwnProperty.call(object, 'image')\n ? 'image'\n : /* istanbul ignore next */ 'image_url';\n\n return {\n image: object[image],\n name: object.name,\n description: object.description,\n standard,\n favorite: false,\n tokenURI: tokenURI ?? null,\n };\n } catch {\n return {\n image: null,\n name: null,\n description: null,\n standard: standard || null,\n favorite: false,\n tokenURI: tokenURI ?? null,\n };\n }\n }\n\n /**\n * Retrieve NFT uri with metadata. TODO Update method to use IPFS.\n *\n * @param contractAddress - NFT contract address.\n * @param tokenId - NFT token id.\n * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving NFT uri and token standard.\n */\n async #getNftURIAndStandard(\n contractAddress: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<[string, string]> {\n // try ERC721 uri\n try {\n const uri = await this.#getERC721TokenURI(\n contractAddress,\n tokenId,\n networkClientId,\n );\n return [uri, ERC721];\n } catch {\n // Ignore error\n }\n\n // try ERC1155 uri\n try {\n const tokenURI = await this.#getERC1155TokenURI(\n contractAddress,\n tokenId,\n networkClientId,\n );\n\n /**\n * According to EIP1155 the URI value allows for ID substitution\n * in case the string `{id}` exists.\n * https://eips.ethereum.org/EIPS/eip-1155#metadata\n */\n\n if (!tokenURI.includes('{id}')) {\n return [tokenURI, ERC1155];\n }\n\n const hexTokenId = remove0x(BNToHex(new BN(tokenId)))\n .padStart(64, '0')\n .toLowerCase();\n return [tokenURI.replace('{id}', hexTokenId), ERC1155];\n } catch {\n // Ignore error\n }\n\n return ['', ''];\n }\n\n /**\n * Request individual NFT information (name, image url and description).\n *\n * @param contractAddress - Hex address of the NFT contract.\n * @param tokenId - The NFT identifier.\n * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving to the current NFT name and image.\n */\n async #getNftInformation(\n contractAddress: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<NftMetadata> {\n const chainId = this.#getCorrectChainId({\n networkClientId,\n });\n const [blockchainMetadata, nftApiMetadata] = await Promise.all([\n safelyExecute(() =>\n this.#getNftInformationFromTokenURI(\n contractAddress,\n tokenId,\n networkClientId,\n ),\n ),\n this.#openSeaEnabled && chainId === '0x1'\n ? safelyExecute(() =>\n this.#getNftInformationFromApi(contractAddress, tokenId),\n )\n : undefined,\n ]);\n return {\n ...nftApiMetadata,\n name: blockchainMetadata?.name ?? nftApiMetadata?.name ?? null,\n description:\n blockchainMetadata?.description ?? nftApiMetadata?.description ?? null,\n image: nftApiMetadata?.image ?? blockchainMetadata?.image ?? null,\n standard:\n blockchainMetadata?.standard ?? nftApiMetadata?.standard ?? null,\n tokenURI: blockchainMetadata?.tokenURI ?? null,\n };\n }\n\n /**\n * Request NFT contract information from the contract itself.\n *\n * @param contractAddress - Hex address of the NFT contract.\n * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving to the current NFT name and image.\n */\n async #getNftContractInformationFromContract(\n contractAddress: string,\n networkClientId?: NetworkClientId,\n ): Promise<\n Partial<ApiNftContract> &\n Pick<ApiNftContract, 'address'> &\n Pick<ApiNftContract, 'collection'>\n > {\n const [name, symbol] = await Promise.all([\n this.#getERC721AssetName(contractAddress, networkClientId),\n this.#getERC721AssetSymbol(contractAddress, networkClientId),\n ]);\n\n return {\n collection: { name },\n symbol,\n address: contractAddress,\n };\n }\n\n /**\n * Request NFT contract information from Blockchain and aggregate with received data from NFTMetadata.\n *\n * @param contractAddress - Hex address of the NFT contract.\n * @param nftMetadataFromApi - Received NFT information to be aggregated with blockchain contract information.\n * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving to the NFT contract name, image and description.\n */\n async #getNftContractInformation(\n contractAddress: string,\n nftMetadataFromApi: NftMetadata,\n networkClientId?: NetworkClientId,\n ): Promise<\n Partial<ApiNftContract> &\n Pick<ApiNftContract, 'address'> &\n Pick<ApiNftContract, 'collection'>\n > {\n const blockchainContractData = await safelyExecute(() =>\n this.#getNftContractInformationFromContract(\n contractAddress,\n networkClientId,\n ),\n );\n\n if (\n blockchainContractData ||\n !Object.values(nftMetadataFromApi).every((value) => value === null)\n ) {\n return {\n address: contractAddress,\n ...blockchainContractData,\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: nftMetadataFromApi?.standard ?? null,\n collection: {\n name: 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:\n nftMetadataFromApi?.collection?.image ??\n nftMetadataFromApi?.collection?.imageUrl ??\n null,\n tokenCount: nftMetadataFromApi?.collection?.tokenCount ?? null,\n ...nftMetadataFromApi?.collection,\n ...blockchainContractData?.collection,\n },\n };\n }\n\n /* istanbul ignore next */\n return {\n address: contractAddress,\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: 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: 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: null,\n symbol: 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: null,\n description: 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: 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 collection: { name: null, image_url: null },\n };\n }\n\n /**\n * Adds an individual NFT to the stored NFT list.\n *\n * @param tokenAddress - Hex address of the NFT contract.\n * @param tokenId - The NFT identifier.\n * @param nftMetadata - NFT optional information (name, image and description).\n * @param nftContract - An object containing contract data of the NFT being added.\n * @param chainId - The chainId of the network where the NFT is being added.\n * @param userAddress - The address of the account where the NFT is being added.\n * @param source - Whether the NFT was detected, added manually or suggested by a dapp.\n * @returns A promise resolving to `undefined`.\n */\n async #addIndividualNft(\n tokenAddress: string,\n tokenId: string,\n nftMetadata: NftMetadata,\n nftContract: NftContract,\n chainId: Hex,\n userAddress: string,\n source: Source,\n ): Promise<void> {\n const releaseLock = await this.#mutex.acquire();\n try {\n const checksumHexAddress = toChecksumHexAddress(tokenAddress);\n const { allNfts } = this.state;\n\n const nfts = [...(allNfts[userAddress]?.[chainId] ?? [])];\n\n const existingEntry = nfts.find(\n (nft) =>\n nft.address.toLowerCase() === checksumHexAddress.toLowerCase() &&\n nft.tokenId === tokenId,\n );\n\n if (existingEntry) {\n const differentMetadata = compareNftMetadata(\n nftMetadata,\n existingEntry,\n );\n\n if (!differentMetadata && existingEntry.isCurrentlyOwned) {\n return;\n }\n\n const indexToUpdate = nfts.findIndex(\n (nft) =>\n nft.address.toLowerCase() === checksumHexAddress.toLowerCase() &&\n nft.tokenId === tokenId,\n );\n\n if (indexToUpdate !== -1) {\n nfts[indexToUpdate] = {\n ...existingEntry,\n ...nftMetadata,\n };\n }\n } else {\n const newEntry: Nft = {\n address: checksumHexAddress,\n tokenId,\n favorite: false,\n isCurrentlyOwned: true,\n ...nftMetadata,\n };\n\n nfts.push(newEntry);\n }\n\n this.#updateNestedNftState(nfts, ALL_NFTS_STATE_KEY, {\n chainId,\n userAddress,\n });\n\n if (this.#onNftAdded) {\n this.#onNftAdded({\n address: checksumHexAddress,\n symbol: nftContract.symbol,\n tokenId: tokenId.toString(),\n standard: nftMetadata.standard,\n source,\n });\n }\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Adds an NFT contract to the stored NFT contracts list.\n *\n * @param options - options.\n * @param options.tokenAddress - Hex address of the NFT contract.\n * @param options.userAddress - The address of the account where the NFT is being added.\n * @param options.nftMetadata - The retrieved NFTMetadata from API.\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @param options.source - Whether the NFT was detected, added manually or suggested by a dapp.\n * @returns Promise resolving to the current NFT contracts list.\n */\n async #addNftContract({\n tokenAddress,\n userAddress,\n networkClientId,\n source,\n nftMetadata,\n }: {\n tokenAddress: string;\n userAddress: string;\n nftMetadata: NftMetadata;\n networkClientId?: NetworkClientId;\n source?: Source;\n }): Promise<NftContract[]> {\n const releaseLock = await this.#mutex.acquire();\n try {\n const checksumHexAddress = toChecksumHexAddress(tokenAddress);\n const { allNftContracts } = this.state;\n const chainId = this.#getCorrectChainId({\n networkClientId,\n });\n\n const nftContracts = allNftContracts[userAddress]?.[chainId] || [];\n\n const existingEntry = nftContracts.find(\n (nftContract) =>\n nftContract.address.toLowerCase() ===\n checksumHexAddress.toLowerCase(),\n );\n if (existingEntry) {\n return nftContracts;\n }\n\n // this doesn't work currently for detection if the user switches networks while the detection is processing\n // will be fixed once detection uses networkClientIds\n // get name and symbol if ERC721 then put together the metadata\n const contractInformation = await this.#getNftContractInformation(\n checksumHexAddress,\n nftMetadata,\n networkClientId,\n );\n const {\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,\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,\n symbol,\n description,\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,\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,\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 collection: { name, image_url, tokenCount },\n } = contractInformation;\n\n // If the nft is auto-detected we want some valid metadata to be present\n if (\n source === Source.Detected &&\n 'address' in contractInformation &&\n typeof contractInformation.address === 'string' &&\n 'collection' in contractInformation &&\n contractInformation.collection.name === null &&\n 'image_url' in contractInformation.collection &&\n contractInformation.collection.image_url === null &&\n Object.entries(contractInformation).every(([key, value]) => {\n return key === 'address' || key === 'collection' || !value;\n })\n ) {\n return nftContracts;\n }\n\n /* istanbul ignore next */\n const newEntry: NftContract = Object.assign(\n {},\n { address: checksumHexAddress },\n description && { description },\n name && { name },\n image_url && { logo: image_url },\n symbol && { symbol },\n tokenCount !== null &&\n typeof tokenCount !== 'undefined' && { totalSupply: tokenCount },\n asset_contract_type && { assetContractType: asset_contract_type },\n created_date && { createdDate: created_date },\n schema_name && { schemaName: schema_name },\n external_link && { externalLink: external_link },\n );\n const newNftContracts = [...nftContracts, newEntry];\n this.#updateNestedNftState(\n newNftContracts,\n ALL_NFTS_CONTRACTS_STATE_KEY,\n {\n chainId,\n userAddress,\n },\n );\n\n return newNftContracts;\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Removes an individual NFT from the stored token list and saves it in ignored NFTs list.\n *\n * @param address - Hex address of the NFT contract.\n * @param tokenId - Token identifier of the NFT.\n * @param options - options.\n * @param options.chainId - The chainId of the network where the NFT is being removed.\n * @param options.userAddress - The address of the account where the NFT is being removed.\n */\n #removeAndIgnoreIndividualNft(\n address: string,\n tokenId: string,\n {\n chainId,\n userAddress,\n }: {\n chainId: Hex;\n userAddress: string;\n },\n ) {\n const checksumHexAddress = toChecksumHexAddress(address);\n const { allNfts, ignoredNfts } = this.state;\n const newIgnoredNfts = [...ignoredNfts];\n const nfts = allNfts[userAddress]?.[chainId] || [];\n const newNfts = nfts.filter((nft) => {\n if (\n nft.address.toLowerCase() === checksumHexAddress.toLowerCase() &&\n nft.tokenId === tokenId\n ) {\n const alreadyIgnored = newIgnoredNfts.find(\n (c) => c.address === checksumHexAddress && c.tokenId === tokenId,\n );\n !alreadyIgnored && newIgnoredNfts.push(nft);\n return false;\n }\n return true;\n });\n\n this.#updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY, {\n userAddress,\n chainId,\n });\n\n this.update((state) => {\n state.ignoredNfts = newIgnoredNfts;\n });\n }\n\n /**\n * Removes an individual NFT from the stored token list.\n *\n * @param address - Hex address of the NFT contract.\n * @param tokenId - Token identifier of the NFT.\n * @param options - options.\n * @param options.chainId - The chainId of the network where the NFT is being removed.\n * @param options.userAddress - The address of the account where the NFT is being removed.\n */\n #removeIndividualNft(\n address: string,\n tokenId: string,\n { chainId, userAddress }: { chainId: Hex; userAddress: string },\n ) {\n const checksumHexAddress = toChecksumHexAddress(address);\n const { allNfts } = this.state;\n const nfts = allNfts[userAddress]?.[chainId] || [];\n const newNfts = nfts.filter(\n (nft) =>\n !(\n nft.address.toLowerCase() === checksumHexAddress.toLowerCase() &&\n nft.tokenId === tokenId\n ),\n );\n this.#updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY, {\n userAddress,\n chainId,\n });\n }\n\n /**\n * Removes an NFT contract to the stored NFT contracts list.\n *\n * @param address - Hex address of the NFT contract.\n * @param options - options.\n * @param options.chainId - The chainId of the network where the NFT is being removed.\n * @param options.userAddress - The address of the account where the NFT is being removed.\n * @returns Promise resolving to the current NFT contracts list.\n */\n #removeNftContract(\n address: string,\n { chainId, userAddress }: { chainId: Hex; userAddress: string },\n ): NftContract[] {\n const checksumHexAddress = toChecksumHexAddress(address);\n const { allNftContracts } = this.state;\n const nftContracts = allNftContracts[userAddress]?.[chainId] || [];\n\n const newNftContracts = nftContracts.filter(\n (nftContract) =>\n !(\n nftContract.address.toLowerCase() === checksumHexAddress.toLowerCase()\n ),\n );\n this.#updateNestedNftState(newNftContracts, ALL_NFTS_CONTRACTS_STATE_KEY, {\n chainId,\n userAddress,\n });\n\n return newNftContracts;\n }\n\n async #validateWatchNft(\n asset: NftAsset,\n type: NFTStandardType,\n userAddress: string,\n { networkClientId }: { networkClientId?: NetworkClientId } = {},\n ) {\n const { address: contractAddress, tokenId } = asset;\n\n // Validate parameters\n if (!type) {\n throw rpcErrors.invalidParams('Asset type is required');\n }\n\n if (type !== ERC721 && type !== ERC1155) {\n throw rpcErrors.invalidParams(\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 `Non NFT asset type ${type} not supported by watchNft`,\n );\n }\n\n if (!contractAddress || !tokenId) {\n throw rpcErrors.invalidParams('Both address and tokenId are required');\n }\n\n if (!isAddress(contractAddress)) {\n throw rpcErrors.invalidParams('Invalid address');\n }\n\n if (!/^\\d+$/u.test(tokenId)) {\n throw rpcErrors.invalidParams('Invalid tokenId');\n }\n\n // Check if the user owns the suggested NFT\n try {\n const isOwner = await this.isNftOwner(\n userAddress,\n contractAddress,\n tokenId,\n { networkClientId },\n );\n if (!isOwner) {\n throw rpcErrors.invalidInput(\n 'Suggested NFT is not owned by the selected account',\n );\n }\n } catch (error) {\n // error thrown here: \"Unable to verify ownership. Possibly because the standard is not supported or the user's currently selected network does not match the chain of the asset in question.\"\n if (error instanceof Error) {\n throw rpcErrors.resourceUnavailable(error.message);\n }\n throw error;\n }\n }\n\n // temporary method to get the correct chainId until we remove chainId from the config & the chainId arg from the detection logic\n // Just a helper method to prefer the networkClient chainId first then the chainId argument and then finally the config chainId\n #getCorrectChainId({\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n }) {\n if (networkClientId) {\n const {\n configuration: { chainId },\n } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n return chainId;\n }\n return this.#chainId;\n }\n\n /**\n * Adds a new suggestedAsset to state. Parameters will be validated according to\n * asset type being watched. A `<suggestedNftMeta.id>:pending` hub event will be emitted once added.\n *\n * @param asset - The asset to be watched. For now ERC721 and ERC1155 tokens are accepted.\n * @param asset.address - The address of the asset contract.\n * @param asset.tokenId - The ID of the asset.\n * @param type - The asset type.\n * @param origin - Domain origin to register the asset from.\n * @param options - Options bag.\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @param options.userAddress - The address of the account where the NFT is being added.\n * @returns Object containing a Promise resolving to the suggestedAsset address if accepted.\n */\n async watchNft(\n asset: NftAsset,\n type: NFTStandardType,\n origin: string,\n {\n networkClientId,\n userAddress,\n }: {\n networkClientId?: NetworkClientId;\n userAddress?: string;\n } = {},\n ) {\n const addressToSearch = this.#getAddressOrSelectedAddress(userAddress);\n if (!addressToSearch) {\n return;\n }\n\n await this.#validateWatchNft(asset, type, addressToSearch);\n\n const nftMetadata = await this.#getNftInformation(\n asset.address,\n asset.tokenId,\n networkClientId,\n );\n\n if (nftMetadata.standard && nftMetadata.standard !== type) {\n throw rpcErrors.invalidInput(\n `Suggested NFT of type ${nftMetadata.standard} does not match received type ${type}`,\n );\n }\n\n const suggestedNftMeta: SuggestedNftMeta = {\n asset: { ...asset, ...nftMetadata },\n type,\n id: random(),\n time: Date.now(),\n interactingAddress: addressToSearch,\n origin,\n };\n await this._requestApproval(suggestedNftMeta);\n const { address, tokenId } = asset;\n const { name, standard, description, image } = nftMetadata;\n\n await this.addNft(address, tokenId, {\n nftMetadata: {\n name: name ?? null,\n description: description ?? null,\n image: image ?? null,\n standard: standard ?? null,\n },\n userAddress,\n source: Source.Dapp,\n networkClientId,\n });\n }\n\n /**\n * Sets an OpenSea API key to retrieve NFT information.\n *\n * @param openSeaApiKey - OpenSea API key.\n */\n setApiKey(openSeaApiKey: string) {\n this.openSeaApiKey = openSeaApiKey;\n }\n\n /**\n * Checks the ownership of a ERC-721 or ERC-1155 NFT for a given address.\n *\n * @param ownerAddress - User public address.\n * @param nftAddress - NFT contract address.\n * @param tokenId - NFT token ID.\n * @param options - Options bag.\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving the NFT ownership.\n */\n async isNftOwner(\n ownerAddress: string,\n nftAddress: string,\n tokenId: string,\n {\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {},\n ): Promise<boolean> {\n // Checks the ownership for ERC-721.\n try {\n const owner = await this.#getERC721OwnerOf(\n nftAddress,\n tokenId,\n networkClientId,\n );\n return ownerAddress.toLowerCase() === owner.toLowerCase();\n // eslint-disable-next-line no-empty\n } catch {\n // Ignore ERC-721 contract error\n }\n\n // Checks the ownership for ERC-1155.\n try {\n const balance = await this.#getERC1155BalanceOf(\n ownerAddress,\n nftAddress,\n tokenId,\n networkClientId,\n );\n return !balance.isZero();\n // eslint-disable-next-line no-empty\n } catch {\n // Ignore ERC-1155 contract error\n }\n\n throw new Error(\n `Unable to verify ownership. Possibly because the standard is not supported or the user's currently selected network does not match the chain of the asset in question.`,\n );\n }\n\n /**\n * Verifies currently selected address owns entered NFT address/tokenId combo and\n * adds the NFT and respective NFT contract to the stored NFT and NFT contracts lists.\n *\n * @param address - Hex address of the NFT contract.\n * @param tokenId - The NFT identifier.\n * @param options - an object of arguments\n * @param options.userAddress - The address of the current user.\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @param options.source - Whether the NFT was detected, added manually or suggested by a dapp.\n */\n async addNftVerifyOwnership(\n address: string,\n tokenId: string,\n {\n userAddress,\n networkClientId,\n source,\n }: {\n userAddress?: string;\n networkClientId?: NetworkClientId;\n source?: Source;\n } = {},\n ) {\n const addressToSearch = this.#getAddressOrSelectedAddress(userAddress);\n\n if (\n !(await this.isNftOwner(addressToSearch, address, tokenId, {\n networkClientId,\n }))\n ) {\n throw new Error('This NFT is not owned by the user');\n }\n await this.addNft(address, tokenId, {\n networkClientId,\n userAddress: addressToSearch,\n source,\n });\n }\n\n /**\n * Adds an NFT and respective NFT contract to the stored NFT and NFT contracts lists.\n *\n * @param tokenAddress - Hex address of the NFT contract.\n * @param tokenId - The NFT identifier.\n * @param options - an object of arguments\n * @param options.nftMetadata - NFT optional metadata.\n * @param options.userAddress - The address of the current user.\n * @param options.source - Whether the NFT was detected, added manually or suggested by a dapp.\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving to the current NFT list.\n */\n async addNft(\n tokenAddress: string,\n tokenId: string,\n {\n nftMetadata,\n userAddress,\n source = Source.Custom,\n networkClientId,\n }: {\n nftMetadata?: NftMetadata;\n userAddress?: string;\n source?: Source;\n networkClientId?: NetworkClientId;\n } = {},\n ) {\n const addressToSearch = this.#getAddressOrSelectedAddress(userAddress);\n if (!addressToSearch) {\n return;\n }\n\n const checksumHexAddress = toChecksumHexAddress(tokenAddress);\n\n const chainId = this.#getCorrectChainId({ networkClientId });\n\n nftMetadata =\n nftMetadata ||\n (await this.#getNftInformation(\n checksumHexAddress,\n tokenId,\n networkClientId,\n ));\n\n const newNftContracts = await this.#addNftContract({\n tokenAddress: checksumHexAddress,\n userAddress: addressToSearch,\n networkClientId,\n source,\n nftMetadata,\n });\n\n // If NFT contract was not added, do not add individual NFT\n const nftContract = newNftContracts.find(\n (contract) =>\n contract.address.toLowerCase() === checksumHexAddress.toLowerCase(),\n );\n\n // If NFT contract information, add individual NFT\n if (nftContract) {\n await this.#addIndividualNft(\n checksumHexAddress,\n tokenId,\n nftMetadata,\n nftContract,\n chainId,\n addressToSearch,\n source,\n );\n }\n }\n\n /**\n * Refetches NFT metadata and updates the state\n *\n * @param options - Options for refetching NFT metadata\n * @param options.nfts - nfts to update metadata for.\n * @param options.userAddress - The current user address\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n */\n async updateNftMetadata({\n nfts,\n userAddress,\n networkClientId,\n }: {\n nfts: Nft[];\n userAddress?: string;\n networkClientId?: NetworkClientId;\n }) {\n const addressToSearch = this.#getAddressOrSelectedAddress(userAddress);\n\n const releaseLock = await this.#mutex.acquire();\n\n try {\n const chainId = this.#getCorrectChainId({ networkClientId });\n\n const nftsWithChecksumAdr = nfts.map((nft) => {\n return {\n ...nft,\n address: toChecksumHexAddress(nft.address),\n };\n });\n const nftMetadataResults = await Promise.all(\n nftsWithChecksumAdr.map(async (nft) => {\n const resMetadata = await this.#getNftInformation(\n nft.address,\n nft.tokenId,\n networkClientId,\n );\n return {\n nft,\n newMetadata: resMetadata,\n };\n }),\n );\n\n // We want to avoid updating the state if the state and fetched nft info are the same\n const nftsWithDifferentMetadata: NftUpdate[] = [];\n const { allNfts } = this.state;\n const stateNfts = allNfts[addressToSearch]?.[chainId] || [];\n\n nftMetadataResults.forEach((singleNft) => {\n const existingEntry: Nft | undefined = stateNfts.find(\n (nft) =>\n nft.address.toLowerCase() === singleNft.nft.address.toLowerCase() &&\n nft.tokenId === singleNft.nft.tokenId,\n );\n\n if (existingEntry) {\n const differentMetadata = compareNftMetadata(\n singleNft.newMetadata,\n existingEntry,\n );\n\n if (differentMetadata) {\n nftsWithDifferentMetadata.push(singleNft);\n }\n }\n });\n\n if (nftsWithDifferentMetadata.length !== 0) {\n nftsWithDifferentMetadata.forEach((elm) =>\n this.updateNft(elm.nft, elm.newMetadata, addressToSearch, chainId),\n );\n }\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Removes an NFT from the stored token list.\n *\n * @param address - Hex address of the NFT contract.\n * @param tokenId - Token identifier of the NFT.\n * @param options - an object of arguments\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @param options.userAddress - The address of the account where the NFT is being removed.\n */\n removeNft(\n address: string,\n tokenId: string,\n {\n networkClientId,\n userAddress,\n }: { networkClientId?: NetworkClientId; userAddress?: string } = {},\n ) {\n const addressToSearch = this.#getAddressOrSelectedAddress(userAddress);\n const chainId = this.#getCorrectChainId({ networkClientId });\n const checksumHexAddress = toChecksumHexAddress(address);\n this.#removeIndividualNft(checksumHexAddress, tokenId, {\n chainId,\n userAddress: addressToSearch,\n });\n const { allNfts } = this.state;\n const nfts = allNfts[addressToSearch]?.[chainId] || [];\n const remainingNft = nfts.find(\n (nft) => nft.address.toLowerCase() === checksumHexAddress.toLowerCase(),\n );\n\n if (!remainingNft) {\n this.#removeNftContract(checksumHexAddress, {\n chainId,\n userAddress: addressToSearch,\n });\n }\n }\n\n /**\n * Removes an NFT from the stored token list and saves it in ignored NFTs list.\n *\n * @param address - Hex address of the NFT contract.\n * @param tokenId - Token identifier of the NFT.\n * @param options - an object of arguments\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @param options.userAddress - The address of the account where the NFT is being removed.\n */\n removeAndIgnoreNft(\n address: string,\n tokenId: string,\n {\n networkClientId,\n userAddress,\n }: { networkClientId?: NetworkClientId; userAddress?: string } = {},\n ) {\n const addressToSearch = this.#getAddressOrSelectedAddress(userAddress);\n const chainId = this.#getCorrectChainId({ networkClientId });\n const checksumHexAddress = toChecksumHexAddress(address);\n this.#removeAndIgnoreIndividualNft(checksumHexAddress, tokenId, {\n chainId,\n userAddress: addressToSearch,\n });\n const { allNfts } = this.state;\n const nfts = allNfts[addressToSearch]?.[chainId] || [];\n const remainingNft = nfts.find(\n (nft) => nft.address.toLowerCase() === checksumHexAddress.toLowerCase(),\n );\n if (!remainingNft) {\n this.#removeNftContract(checksumHexAddress, {\n chainId,\n userAddress: addressToSearch,\n });\n }\n }\n\n /**\n * Removes all NFTs from the ignored list.\n */\n clearIgnoredNfts() {\n this.update((state) => {\n state.ignoredNfts = [];\n });\n }\n\n /**\n * Checks whether input NFT is still owned by the user\n * And updates the isCurrentlyOwned value on the NFT object accordingly.\n *\n * @param nft - The NFT object to check and update.\n * @param batch - A boolean indicating whether this method is being called as part of a batch or single update.\n * @param accountParams - The userAddress and chainId to check ownership against\n * @param accountParams.userAddress - the address passed through the confirmed transaction flow to ensure assets are stored to the correct account\n * @param accountParams.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns the NFT with the updated isCurrentlyOwned value\n */\n async checkAndUpdateSingleNftOwnershipStatus(\n nft: Nft,\n batch: boolean,\n {\n userAddress,\n networkClientId,\n }: { networkClientId?: NetworkClientId; userAddress?: string } = {},\n ) {\n const addressToSearch = this.#getAddressOrSelectedAddress(userAddress);\n const chainId = this.#getCorrectChainId({ networkClientId });\n const { address, tokenId } = nft;\n let isOwned = nft.isCurrentlyOwned;\n try {\n isOwned = await this.isNftOwner(addressToSearch, address, tokenId, {\n networkClientId,\n });\n } catch {\n // ignore error\n // this will only throw an error 'Unable to verify ownership' in which case\n // we want to keep the current value of isCurrentlyOwned for this flow.\n }\n\n const updatedNft = {\n ...nft,\n isCurrentlyOwned: isOwned,\n };\n\n if (batch) {\n return updatedNft;\n }\n\n // if this is not part of a batched update we update this one NFT in state\n const { allNfts } = this.state;\n const nfts = [...(allNfts[addressToSearch]?.[chainId] || [])];\n const indexToUpdate = nfts.findIndex(\n (item) =>\n item.tokenId === tokenId &&\n item.address.toLowerCase() === address.toLowerCase(),\n );\n\n if (indexToUpdate !== -1) {\n nfts[indexToUpdate] = updatedNft;\n this.update((state) => {\n state.allNfts[addressToSearch] = Object.assign(\n {},\n state.allNfts[addressToSearch],\n {\n [chainId]: nfts,\n },\n );\n });\n this.#updateNestedNftState(nfts, ALL_NFTS_STATE_KEY, {\n userAddress: addressToSearch,\n chainId,\n });\n }\n\n return updatedNft;\n }\n\n /**\n * Checks whether NFTs associated with current selectedAddress/chainId combination are still owned by the user\n * And updates the isCurrentlyOwned value on each accordingly.\n * @param options - an object of arguments\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @param options.userAddress - The address of the account where the NFT ownership status is checked/updated.\n */\n async checkAndUpdateAllNftsOwnershipStatus({\n networkClientId,\n userAddress,\n }: {\n networkClientId?: NetworkClientId;\n userAddress?: string;\n } = {}) {\n const addressToSearch = this.#getAddressOrSelectedAddress(userAddress);\n const chainId = this.#getCorrectChainId({ networkClientId });\n const { allNfts } = this.state;\n const nfts = allNfts[addressToSearch]?.[chainId] || [];\n const updatedNfts = await Promise.all(\n nfts.map(async (nft) => {\n return (\n (await this.checkAndUpdateSingleNftOwnershipStatus(nft, true, {\n networkClientId,\n userAddress,\n })) ?? nft\n );\n }),\n );\n\n this.#updateNestedNftState(updatedNfts, ALL_NFTS_STATE_KEY, {\n userAddress: addressToSearch,\n chainId,\n });\n }\n\n /**\n * Update NFT favorite status.\n *\n * @param address - Hex address of the NFT contract.\n * @param tokenId - Hex address of the NFT contract.\n * @param favorite - NFT new favorite status.\n * @param options - an object of arguments\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @param options.userAddress - The address of the account where the NFT is being removed.\n */\n updateNftFavoriteStatus(\n address: string,\n tokenId: string,\n favorite: boolean,\n {\n networkClientId,\n userAddress,\n }: {\n networkClientId?: NetworkClientId;\n userAddress?: string;\n } = {},\n ) {\n const addressToSearch = this.#getAddressOrSelectedAddress(userAddress);\n const chainId = this.#getCorrectChainId({ networkClientId });\n const { allNfts } = this.state;\n const nfts = [...(allNfts[addressToSearch]?.[chainId] || [])];\n const index: number = nfts.findIndex(\n (nft) => nft.address === address && nft.tokenId === tokenId,\n );\n\n if (index === -1) {\n return;\n }\n\n const updatedNft: Nft = {\n ...nfts[index],\n favorite,\n };\n\n // Update Nfts array\n nfts[index] = updatedNft;\n\n this.#updateNestedNftState(nfts, ALL_NFTS_STATE_KEY, {\n chainId,\n userAddress: addressToSearch,\n });\n }\n\n /**\n * Returns an NFT by the address and token id.\n *\n * @param address - Hex address of the NFT contract.\n * @param tokenId - Number that represents the id of the token.\n * @param selectedAddress - Hex address of the user account.\n * @param chainId - Id of the current network.\n * @returns Object containing the NFT and its position in the array\n */\n findNftByAddressAndTokenId(\n address: string,\n tokenId: string,\n selectedAddress: string,\n chainId: Hex,\n ): { nft: Nft; index: number } | null {\n const { allNfts } = this.state;\n const nfts = allNfts[selectedAddress]?.[chainId] || [];\n const index: number = nfts.findIndex(\n (nft) =>\n nft.address.toLowerCase() === address.toLowerCase() &&\n nft.tokenId === tokenId,\n );\n\n if (index === -1) {\n return null;\n }\n\n return { nft: nfts[index], index };\n }\n\n /**\n * Update NFT data.\n *\n * @param nft - NFT object to find the right NFT to updates.\n * @param updates - NFT partial object to update properties of the NFT.\n * @param selectedAddress - Hex address of the user account.\n * @param chainId - Id of the current network.\n */\n updateNft(\n nft: Nft,\n updates: Partial<Nft>,\n selectedAddress: string,\n chainId: Hex,\n ) {\n const { allNfts } = this.state;\n const nfts = allNfts[selectedAddress]?.[chainId] || [];\n const nftInfo = this.findNftByAddressAndTokenId(\n nft.address,\n nft.tokenId,\n selectedAddress,\n chainId,\n );\n\n if (!nftInfo) {\n return;\n }\n\n const updatedNft: Nft = {\n ...nft,\n ...updates,\n };\n\n const newNfts = [\n ...nfts.slice(0, nftInfo.index),\n updatedNft,\n ...nfts.slice(nftInfo.index + 1),\n ];\n this.#updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY, {\n chainId,\n userAddress: selectedAddress,\n });\n }\n\n /**\n * Resets the transaction status of an NFT.\n *\n * @param transactionId - NFT transaction id.\n * @param selectedAddress - Hex address of the user account.\n * @param chainId - Id of the current network.\n * @returns a boolean indicating if the reset was well succeeded or not\n */\n resetNftTransactionStatusByTransactionId(\n transactionId: string,\n selectedAddress: string,\n chainId: Hex,\n ): boolean {\n const { allNfts } = this.state;\n const nfts = allNfts[selectedAddress]?.[chainId] || [];\n const index: number = nfts.findIndex(\n (nft) => nft.transactionId === transactionId,\n );\n\n if (index === -1) {\n return false;\n }\n const updatedNft: Nft = {\n ...nfts[index],\n transactionId: undefined,\n };\n\n const newNfts = [\n ...nfts.slice(0, index),\n updatedNft,\n ...nfts.slice(index + 1),\n ];\n\n this.#updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY, {\n chainId,\n userAddress: selectedAddress,\n });\n\n return true;\n }\n\n async _requestApproval(suggestedNftMeta: SuggestedNftMeta) {\n return this.messagingSystem.call(\n 'ApprovalController:addRequest',\n {\n id: suggestedNftMeta.id,\n origin: suggestedNftMeta.origin,\n type: ApprovalType.WatchAsset,\n requestData: {\n id: suggestedNftMeta.id,\n interactingAddress: suggestedNftMeta.interactingAddress,\n asset: {\n address: suggestedNftMeta.asset.address,\n tokenId: suggestedNftMeta.asset.tokenId,\n name: suggestedNftMeta.asset.name,\n description: suggestedNftMeta.asset.description,\n image: suggestedNftMeta.asset.image,\n standard: suggestedNftMeta.asset.standard,\n },\n },\n },\n true,\n );\n }\n\n #getAddressOrSelectedAddress(address: string | undefined): string {\n if (address) {\n return address;\n }\n\n // If the address is not defined (or empty), we fallback to the currently selected account's address\n const selectedAccount = this.messagingSystem.call(\n 'AccountsController:getAccount',\n this.#selectedAccountId,\n );\n return selectedAccount?.address || '';\n }\n\n async #updateNftUpdateForAccount(account: InternalAccount) {\n const nfts: Nft[] =\n this.state.allNfts[account.address]?.[this.#chainId] ?? [];\n\n // Filter only nfts\n const nftsToUpdate = nfts.filter(\n (singleNft) =>\n !singleNft.name && !singleNft.description && !singleNft.image,\n );\n if (nftsToUpdate.length !== 0) {\n await this.updateNftMetadata({\n nfts: nftsToUpdate,\n userAddress: account.address,\n });\n }\n }\n}\n\nexport default NftController;\n"]}
@@ -44,7 +44,7 @@ var getDefaultNftControllerState = () => ({
44
44
  allNfts: {},
45
45
  ignoredNfts: []
46
46
  });
47
- var _mutex, _selectedAccountId, _chainId, _ipfsGateway, _openSeaEnabled, _useIpfsSubdomains, _isIpfsGatewayEnabled, _getERC721AssetName, _getERC721AssetSymbol, _getERC721TokenURI, _getERC721OwnerOf, _getERC1155BalanceOf, _getERC1155TokenURI, _onNftAdded, _onNetworkControllerNetworkDidChange, onNetworkControllerNetworkDidChange_fn, _onPreferencesControllerStateChange, onPreferencesControllerStateChange_fn, _onSelectedAccountChange, onSelectedAccountChange_fn, _updateNestedNftState, updateNestedNftState_fn, _getNftInformationFromApi, getNftInformationFromApi_fn, _getNftInformationFromTokenURI, getNftInformationFromTokenURI_fn, _getNftURIAndStandard, getNftURIAndStandard_fn, _getNftInformation, getNftInformation_fn, _parseNftInfoResults, parseNftInfoResults_fn, _getNftContractInformationFromContract, getNftContractInformationFromContract_fn, _getNftContractInformation, getNftContractInformation_fn, _addIndividualNft, addIndividualNft_fn, _addNftContract, addNftContract_fn, _removeAndIgnoreIndividualNft, removeAndIgnoreIndividualNft_fn, _removeIndividualNft, removeIndividualNft_fn, _removeNftContract, removeNftContract_fn, _validateWatchNft, validateWatchNft_fn, _getCorrectChainId, getCorrectChainId_fn, _getAddressOrSelectedAddress, getAddressOrSelectedAddress_fn, _updateNftUpdateForAccount, updateNftUpdateForAccount_fn;
47
+ var _mutex, _selectedAccountId, _chainId, _ipfsGateway, _openSeaEnabled, _useIpfsSubdomains, _isIpfsGatewayEnabled, _getERC721AssetName, _getERC721AssetSymbol, _getERC721TokenURI, _getERC721OwnerOf, _getERC1155BalanceOf, _getERC1155TokenURI, _onNftAdded, _onNetworkControllerNetworkDidChange, onNetworkControllerNetworkDidChange_fn, _onPreferencesControllerStateChange, onPreferencesControllerStateChange_fn, _onSelectedAccountChange, onSelectedAccountChange_fn, _updateNestedNftState, updateNestedNftState_fn, _getNftCollectionInformationFromApi, getNftCollectionInformationFromApi_fn, _getNftCollectionApi, getNftCollectionApi_fn, _getNftInformationFromApi, getNftInformationFromApi_fn, _getNftInformationFromTokenURI, getNftInformationFromTokenURI_fn, _getNftURIAndStandard, getNftURIAndStandard_fn, _getNftInformation, getNftInformation_fn, _getNftContractInformationFromContract, getNftContractInformationFromContract_fn, _getNftContractInformation, getNftContractInformation_fn, _addIndividualNft, addIndividualNft_fn, _addNftContract, addNftContract_fn, _removeAndIgnoreIndividualNft, removeAndIgnoreIndividualNft_fn, _removeIndividualNft, removeIndividualNft_fn, _removeNftContract, removeNftContract_fn, _validateWatchNft, validateWatchNft_fn, _getCorrectChainId, getCorrectChainId_fn, _getAddressOrSelectedAddress, getAddressOrSelectedAddress_fn, _updateNftUpdateForAccount, updateNftUpdateForAccount_fn;
48
48
  var NftController = class extends BaseController {
49
49
  /**
50
50
  * Creates an NftController instance.
@@ -120,6 +120,8 @@ var NftController = class extends BaseController {
120
120
  * @param passedConfig.chainId - the chainId passed through the NFT detection flow to ensure assets are stored to the correct account
121
121
  */
122
122
  __privateAdd(this, _updateNestedNftState);
123
+ __privateAdd(this, _getNftCollectionInformationFromApi);
124
+ __privateAdd(this, _getNftCollectionApi);
123
125
  /**
124
126
  * Request individual NFT information from NFT API.
125
127
  *
@@ -155,9 +157,6 @@ var NftController = class extends BaseController {
155
157
  * @returns Promise resolving to the current NFT name and image.
156
158
  */
157
159
  __privateAdd(this, _getNftInformation);
158
- // This function is a good candidate for a utility function since it doesn't do anything with context
159
- // But since types are defined here, I will leave it here to prevent circular dependencies
160
- __privateAdd(this, _parseNftInfoResults);
161
160
  /**
162
161
  * Request NFT contract information from the contract itself.
163
162
  *
@@ -285,6 +284,17 @@ var NftController = class extends BaseController {
285
284
  getNftApi() {
286
285
  return `${NFT_API_BASE_URL}/tokens`;
287
286
  }
287
+ /**
288
+ * Fetches NFT Collection Metadata from the NFT API.
289
+ *
290
+ * @param contractAddress - The contract address of the NFT.
291
+ * @param chainId - The chain ID of the network where the NFT is located.
292
+ *
293
+ * @returns The NFT metadata.
294
+ */
295
+ async fetchNftCollectionMetadata(contractAddress, chainId) {
296
+ return await __privateMethod(this, _getNftCollectionInformationFromApi, getNftCollectionInformationFromApi_fn).call(this, contractAddress, chainId);
297
+ }
288
298
  /**
289
299
  * Adds a new suggestedAsset to state. Parameters will be validated according to
290
300
  * asset type being watched. A `<suggestedNftMeta.id>:pending` hub event will be emitted once added.
@@ -795,23 +805,6 @@ var NftController = class extends BaseController {
795
805
  true
796
806
  );
797
807
  }
798
- /**
799
- * Fetches NFT metadata from the NFT API.
800
- *
801
- * @param contractAddress - The contract address of the NFT.
802
- * @param tokenId - The token ID of the NFT.
803
- * @param chainId - The chain ID of the network where the NFT is located.
804
- *
805
- * @returns The NFT metadata.
806
- */
807
- async fetchNftMetadata(contractAddress, tokenId, chainId) {
808
- const nftApiMetadata = await safelyExecute(
809
- () => __privateMethod(this, _getNftInformationFromApi, getNftInformationFromApi_fn).call(this, contractAddress, tokenId, {
810
- chainId
811
- })
812
- );
813
- return __privateMethod(this, _parseNftInfoResults, parseNftInfoResults_fn).call(this, void 0, nftApiMetadata);
814
- }
815
808
  };
816
809
  _mutex = new WeakMap();
817
810
  _selectedAccountId = new WeakMap();
@@ -884,27 +877,39 @@ updateNestedNftState_fn = function(newCollection, baseStateKey, { userAddress, c
884
877
  };
885
878
  });
886
879
  };
887
- _getNftInformationFromApi = new WeakSet();
888
- getNftInformationFromApi_fn = async function(contractAddress, tokenId, {
889
- chainId = "0x1",
890
- includeAttributes = false,
891
- includeLastSale = false,
892
- includeTopBid = false
893
- }) {
880
+ _getNftCollectionInformationFromApi = new WeakSet();
881
+ getNftCollectionInformationFromApi_fn = async function(contractAddress, chainId) {
894
882
  const urlParams = new URLSearchParams({
895
- chainIds: chainId,
896
- tokens: `${contractAddress}:${tokenId}`
897
- });
898
- const optionalBooleanUrlParams = {
899
- includeAttributes,
900
- includeLastSale,
901
- includeTopBid
902
- };
903
- Object.entries(optionalBooleanUrlParams).forEach(([key, value]) => {
904
- if (value) {
905
- urlParams.append(key, "true");
883
+ chainId,
884
+ contract: `${contractAddress}`
885
+ }).toString();
886
+ const nftCollectionInformation = await handleFetch(`${__privateMethod(this, _getNftCollectionApi, getNftCollectionApi_fn).call(this)}?${urlParams}`, {
887
+ headers: {
888
+ Version: "1"
906
889
  }
907
890
  });
891
+ if (nftCollectionInformation?.collections.length === 0) {
892
+ return {
893
+ collection: null
894
+ };
895
+ }
896
+ return {
897
+ collection: nftCollectionInformation.collections[0]
898
+ };
899
+ };
900
+ _getNftCollectionApi = new WeakSet();
901
+ getNftCollectionApi_fn = function() {
902
+ return `${NFT_API_BASE_URL}/collections`;
903
+ };
904
+ _getNftInformationFromApi = new WeakSet();
905
+ getNftInformationFromApi_fn = async function(contractAddress, tokenId) {
906
+ const urlParams = new URLSearchParams({
907
+ chainIds: "1",
908
+ tokens: `${contractAddress}:${tokenId}`,
909
+ includeTopBid: "true",
910
+ includeAttributes: "true",
911
+ includeLastSale: "true"
912
+ }).toString();
908
913
  const nftInformation = await fetchWithErrorHandling({
909
914
  url: `${this.getNftApi()}?${urlParams}`,
910
915
  options: {
@@ -1051,17 +1056,9 @@ getNftInformation_fn = async function(contractAddress, tokenId, networkClientId)
1051
1056
  () => __privateMethod(this, _getNftInformationFromTokenURI, getNftInformationFromTokenURI_fn).call(this, contractAddress, tokenId, networkClientId)
1052
1057
  ),
1053
1058
  __privateGet(this, _openSeaEnabled) && chainId === "0x1" ? safelyExecute(
1054
- () => __privateMethod(this, _getNftInformationFromApi, getNftInformationFromApi_fn).call(this, contractAddress, tokenId, {
1055
- includeAttributes: true,
1056
- includeLastSale: true,
1057
- includeTopBid: true
1058
- })
1059
+ () => __privateMethod(this, _getNftInformationFromApi, getNftInformationFromApi_fn).call(this, contractAddress, tokenId)
1059
1060
  ) : void 0
1060
1061
  ]);
1061
- return __privateMethod(this, _parseNftInfoResults, parseNftInfoResults_fn).call(this, blockchainMetadata, nftApiMetadata);
1062
- };
1063
- _parseNftInfoResults = new WeakSet();
1064
- parseNftInfoResults_fn = function(blockchainMetadata, nftApiMetadata) {
1065
1062
  return {
1066
1063
  ...nftApiMetadata,
1067
1064
  name: blockchainMetadata?.name ?? nftApiMetadata?.name ?? null,
@@ -1395,4 +1392,4 @@ export {
1395
1392
  NftController,
1396
1393
  NftController_default
1397
1394
  };
1398
- //# sourceMappingURL=chunk-C2ZDNCFD.mjs.map
1395
+ //# sourceMappingURL=chunk-HPYR2PGE.mjs.map