@metamask/assets-controllers 30.0.0 → 31.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 (93) hide show
  1. package/CHANGELOG.md +81 -1
  2. package/dist/AccountTrackerController.js +2 -2
  3. package/dist/AccountTrackerController.mjs +1 -1
  4. package/dist/AssetsContractController.js +2 -2
  5. package/dist/AssetsContractController.mjs +1 -1
  6. package/dist/NftController.js +2 -2
  7. package/dist/NftController.mjs +3 -3
  8. package/dist/NftDetectionController.js +2 -2
  9. package/dist/NftDetectionController.mjs +1 -1
  10. package/dist/TokenBalancesController.js +2 -2
  11. package/dist/TokenBalancesController.mjs +1 -1
  12. package/dist/TokenListController.js +3 -3
  13. package/dist/TokenListController.mjs +2 -2
  14. package/dist/TokenRatesController.js +2 -2
  15. package/dist/TokenRatesController.mjs +1 -1
  16. package/dist/TokensController.js +3 -3
  17. package/dist/TokensController.mjs +2 -2
  18. package/dist/chunk-4AC3X2U5.js +771 -0
  19. package/dist/chunk-4AC3X2U5.js.map +1 -0
  20. package/dist/chunk-543CC74T.mjs +253 -0
  21. package/dist/chunk-543CC74T.mjs.map +1 -0
  22. package/dist/{chunk-Z3OQU4XW.mjs → chunk-5W5OO2Q5.mjs} +2 -2
  23. package/dist/chunk-5W5OO2Q5.mjs.map +1 -0
  24. package/dist/chunk-62T7RKU3.mjs +1265 -0
  25. package/dist/chunk-62T7RKU3.mjs.map +1 -0
  26. package/dist/{chunk-PAJTKWEC.mjs → chunk-65PB33TE.mjs} +1 -1
  27. package/dist/chunk-65PB33TE.mjs.map +1 -0
  28. package/dist/{chunk-7MMEHAKG.mjs → chunk-73F3SN5O.mjs} +332 -265
  29. package/dist/chunk-73F3SN5O.mjs.map +1 -0
  30. package/dist/{chunk-XHMM35YT.mjs → chunk-A2DDWXMS.mjs} +2 -2
  31. package/dist/chunk-CGLUTXI7.js +1265 -0
  32. package/dist/chunk-CGLUTXI7.js.map +1 -0
  33. package/dist/{chunk-X4FFNQHE.mjs → chunk-E4ECCGJV.mjs} +1 -1
  34. package/dist/chunk-E4ECCGJV.mjs.map +1 -0
  35. package/dist/{chunk-V4ZO3F2S.js → chunk-GU53EI7A.js} +1 -1
  36. package/dist/chunk-GU53EI7A.js.map +1 -0
  37. package/dist/{chunk-MHN7CJCZ.mjs → chunk-HLCGZGPA.mjs} +1 -1
  38. package/dist/chunk-HLCGZGPA.mjs.map +1 -0
  39. package/dist/{chunk-LD4GC7OR.js → chunk-IBK6AXPP.js} +8 -9
  40. package/dist/chunk-IBK6AXPP.js.map +1 -0
  41. package/dist/{chunk-5F5EQAX5.js → chunk-JUI3XNEF.js} +3 -3
  42. package/dist/{chunk-3R43XIIX.js → chunk-PYMUBJQX.js} +2 -2
  43. package/dist/chunk-PYMUBJQX.js.map +1 -0
  44. package/dist/chunk-QFDTOEYR.js +253 -0
  45. package/dist/chunk-QFDTOEYR.js.map +1 -0
  46. package/dist/{chunk-4ODKGWYQ.js → chunk-QHWKLZUC.js} +1 -1
  47. package/dist/chunk-QHWKLZUC.js.map +1 -0
  48. package/dist/{chunk-6W5EQ3JQ.js → chunk-UEDNQBJN.js} +1 -1
  49. package/dist/chunk-UEDNQBJN.js.map +1 -0
  50. package/dist/{chunk-4LY47RPI.mjs → chunk-WCCLSUOI.mjs} +8 -9
  51. package/dist/{chunk-4LY47RPI.mjs.map → chunk-WCCLSUOI.mjs.map} +1 -1
  52. package/dist/index.js +10 -12
  53. package/dist/index.mjs +11 -13
  54. package/dist/token-service.js +2 -2
  55. package/dist/token-service.mjs +1 -1
  56. package/dist/tsconfig.build.tsbuildinfo +1 -1
  57. package/dist/types/AccountTrackerController.d.ts +1 -1
  58. package/dist/types/AccountTrackerController.d.ts.map +1 -1
  59. package/dist/types/AssetsContractController.d.ts +1 -1
  60. package/dist/types/AssetsContractController.d.ts.map +1 -1
  61. package/dist/types/NftController.d.ts +65 -184
  62. package/dist/types/NftController.d.ts.map +1 -1
  63. package/dist/types/NftDetectionController.d.ts +34 -75
  64. package/dist/types/NftDetectionController.d.ts.map +1 -1
  65. package/dist/types/TokenRatesController.d.ts +6 -6
  66. package/dist/types/TokenRatesController.d.ts.map +1 -1
  67. package/dist/types/TokensController.d.ts +27 -131
  68. package/dist/types/TokensController.d.ts.map +1 -1
  69. package/dist/types/index.d.ts +5 -3
  70. package/dist/types/index.d.ts.map +1 -1
  71. package/package.json +12 -12
  72. package/dist/chunk-3R43XIIX.js.map +0 -1
  73. package/dist/chunk-46UZDIXW.mjs +0 -1205
  74. package/dist/chunk-46UZDIXW.mjs.map +0 -1
  75. package/dist/chunk-4ODKGWYQ.js.map +0 -1
  76. package/dist/chunk-6W5EQ3JQ.js.map +0 -1
  77. package/dist/chunk-7MMEHAKG.mjs.map +0 -1
  78. package/dist/chunk-FMZML3V5.js +0 -237
  79. package/dist/chunk-FMZML3V5.js.map +0 -1
  80. package/dist/chunk-KOKB6U4Z.mjs +0 -237
  81. package/dist/chunk-KOKB6U4Z.mjs.map +0 -1
  82. package/dist/chunk-LAU6ZDZR.js +0 -1205
  83. package/dist/chunk-LAU6ZDZR.js.map +0 -1
  84. package/dist/chunk-LD4GC7OR.js.map +0 -1
  85. package/dist/chunk-MBCN3MNX.js +0 -704
  86. package/dist/chunk-MBCN3MNX.js.map +0 -1
  87. package/dist/chunk-MHN7CJCZ.mjs.map +0 -1
  88. package/dist/chunk-PAJTKWEC.mjs.map +0 -1
  89. package/dist/chunk-V4ZO3F2S.js.map +0 -1
  90. package/dist/chunk-X4FFNQHE.mjs.map +0 -1
  91. package/dist/chunk-Z3OQU4XW.mjs.map +0 -1
  92. /package/dist/{chunk-XHMM35YT.mjs.map → chunk-A2DDWXMS.mjs.map} +0 -0
  93. /package/dist/{chunk-5F5EQAX5.js.map → chunk-JUI3XNEF.js.map} +0 -0
@@ -1,1205 +0,0 @@
1
- import {
2
- compareNftMetadata,
3
- getFormattedIpfsUrl
4
- } from "./chunk-Q5JRBGWO.mjs";
5
-
6
- // src/NftController.ts
7
- import { isAddress } from "@ethersproject/address";
8
- import { BaseControllerV1 } from "@metamask/base-controller";
9
- import {
10
- safelyExecute,
11
- handleFetch,
12
- toChecksumHexAddress,
13
- BNToHex,
14
- fetchWithErrorHandling,
15
- IPFS_DEFAULT_GATEWAY_URL,
16
- ERC721,
17
- ERC1155,
18
- ApprovalType,
19
- NFT_API_BASE_URL
20
- } from "@metamask/controller-utils";
21
- import { rpcErrors } from "@metamask/rpc-errors";
22
- import { remove0x } from "@metamask/utils";
23
- import { Mutex } from "async-mutex";
24
- import BN from "bn.js";
25
- import { EventEmitter } from "events";
26
- import { v4 as random } from "uuid";
27
- var ALL_NFTS_STATE_KEY = "allNfts";
28
- var ALL_NFTS_CONTRACTS_STATE_KEY = "allNftContracts";
29
- var getDefaultNftState = () => {
30
- return {
31
- allNftContracts: {},
32
- allNfts: {},
33
- ignoredNfts: []
34
- };
35
- };
36
- var NftController = class extends BaseControllerV1 {
37
- /**
38
- * Creates an NftController instance.
39
- *
40
- * @param options - The controller options.
41
- * @param options.chainId - The chain ID of the current network.
42
- * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.
43
- * @param options.onNetworkStateChange - Allows subscribing to network controller state changes.
44
- * @param options.getERC721AssetName - Gets the name of the asset at the given address.
45
- * @param options.getERC721AssetSymbol - Gets the symbol of the asset at the given address.
46
- * @param options.getERC721TokenURI - Gets the URI of the ERC721 token at the given address, with the given ID.
47
- * @param options.getERC721OwnerOf - Get the owner of a ERC-721 NFT.
48
- * @param options.getERC1155BalanceOf - Gets balance of a ERC-1155 NFT.
49
- * @param options.getERC1155TokenURI - Gets the URI of the ERC1155 token at the given address, with the given ID.
50
- * @param options.getNetworkClientById - Gets the network client for the given networkClientId.
51
- * @param options.onNftAdded - Callback that is called when an NFT is added. Currently used pass data
52
- * for tracking the NFT added event.
53
- * @param options.messenger - The controller messenger.
54
- * @param config - Initial options used to configure this controller.
55
- * @param state - Initial state to set on this controller.
56
- */
57
- constructor({
58
- chainId: initialChainId,
59
- onPreferencesStateChange,
60
- onNetworkStateChange,
61
- getERC721AssetName,
62
- getERC721AssetSymbol,
63
- getERC721TokenURI,
64
- getERC721OwnerOf,
65
- getERC1155BalanceOf,
66
- getERC1155TokenURI,
67
- getNetworkClientById,
68
- onNftAdded,
69
- messenger
70
- }, config, state) {
71
- super(config, state);
72
- this.mutex = new Mutex();
73
- /**
74
- * EventEmitter instance used to listen to specific EIP747 events
75
- */
76
- this.hub = new EventEmitter();
77
- /**
78
- * Name of this controller used during composition
79
- */
80
- this.name = "NftController";
81
- this.defaultConfig = {
82
- selectedAddress: "",
83
- chainId: initialChainId,
84
- ipfsGateway: IPFS_DEFAULT_GATEWAY_URL,
85
- openSeaEnabled: false,
86
- useIPFSSubdomains: true,
87
- isIpfsGatewayEnabled: true
88
- };
89
- this.defaultState = getDefaultNftState();
90
- this.initialize();
91
- this.getERC721AssetName = getERC721AssetName;
92
- this.getERC721AssetSymbol = getERC721AssetSymbol;
93
- this.getERC721TokenURI = getERC721TokenURI;
94
- this.getERC721OwnerOf = getERC721OwnerOf;
95
- this.getERC1155BalanceOf = getERC1155BalanceOf;
96
- this.getERC1155TokenURI = getERC1155TokenURI;
97
- this.getNetworkClientById = getNetworkClientById;
98
- this.onNftAdded = onNftAdded;
99
- this.messagingSystem = messenger;
100
- onPreferencesStateChange(
101
- async ({
102
- selectedAddress,
103
- ipfsGateway,
104
- openSeaEnabled,
105
- isIpfsGatewayEnabled
106
- }) => {
107
- this.configure({
108
- selectedAddress,
109
- ipfsGateway,
110
- openSeaEnabled,
111
- isIpfsGatewayEnabled
112
- });
113
- const needsUpdateNftMetadata = isIpfsGatewayEnabled && ipfsGateway !== "" || openSeaEnabled;
114
- if (needsUpdateNftMetadata) {
115
- const { chainId } = this.config;
116
- const nfts = this.state.allNfts[selectedAddress]?.[chainId] ?? [];
117
- const nftsToUpdate = nfts.filter(
118
- (singleNft) => !singleNft.name && !singleNft.description && !singleNft.image
119
- );
120
- if (nftsToUpdate.length !== 0) {
121
- await this.updateNftMetadata({
122
- nfts: nftsToUpdate,
123
- userAddress: selectedAddress
124
- });
125
- }
126
- }
127
- }
128
- );
129
- onNetworkStateChange(({ selectedNetworkClientId }) => {
130
- const selectedNetworkClient = getNetworkClientById(
131
- selectedNetworkClientId
132
- );
133
- const { chainId } = selectedNetworkClient.configuration;
134
- this.configure({ chainId });
135
- });
136
- }
137
- getNftApi() {
138
- return `${NFT_API_BASE_URL}/tokens`;
139
- }
140
- /**
141
- * Helper method to update nested state for allNfts and allNftContracts.
142
- *
143
- * @param newCollection - the modified piece of state to update in the controller's store
144
- * @param baseStateKey - The root key in the store to update.
145
- * @param passedConfig - An object containing the selectedAddress and chainId that are passed through the auto-detection flow.
146
- * @param passedConfig.userAddress - the address passed through the NFT detection flow to ensure assets are stored to the correct account
147
- * @param passedConfig.chainId - the chainId passed through the NFT detection flow to ensure assets are stored to the correct account
148
- */
149
- updateNestedNftState(newCollection, baseStateKey, { userAddress, chainId }) {
150
- const { [baseStateKey]: oldState } = this.state;
151
- const addressState = oldState[userAddress];
152
- const newAddressState = {
153
- ...addressState,
154
- ...{ [chainId]: newCollection }
155
- };
156
- const newState = {
157
- ...oldState,
158
- ...{ [userAddress]: newAddressState }
159
- };
160
- this.update({
161
- [baseStateKey]: newState
162
- });
163
- }
164
- /**
165
- * Request individual NFT information from NFT API.
166
- *
167
- * @param contractAddress - Hex address of the NFT contract.
168
- * @param tokenId - The NFT identifier.
169
- * @returns Promise resolving to the current NFT name and image.
170
- */
171
- async getNftInformationFromApi(contractAddress, tokenId) {
172
- const urlParams = new URLSearchParams({
173
- chainIds: "1",
174
- tokens: `${contractAddress}:${tokenId}`,
175
- includeTopBid: "true",
176
- includeAttributes: "true",
177
- includeLastSale: "true"
178
- }).toString();
179
- const nftInformation = await fetchWithErrorHandling({
180
- url: `${this.getNftApi()}?${urlParams}`,
181
- options: {
182
- headers: {
183
- Version: "1"
184
- }
185
- }
186
- });
187
- if (!nftInformation?.tokens?.[0]?.token) {
188
- return {
189
- name: null,
190
- description: null,
191
- image: null,
192
- standard: null
193
- };
194
- }
195
- const {
196
- image,
197
- metadata: { imageOriginal } = {},
198
- name,
199
- description,
200
- collection,
201
- kind,
202
- rarityRank,
203
- rarity,
204
- attributes,
205
- lastSale,
206
- imageSmall
207
- } = nftInformation.tokens[0].token;
208
- const nftMetadata = Object.assign(
209
- {},
210
- { name: name || null },
211
- { description: description || null },
212
- { image: image || null },
213
- collection?.creator && { creator: collection.creator },
214
- imageOriginal && { imageOriginal },
215
- imageSmall && { imageThumbnail: imageSmall },
216
- kind && { standard: kind.toUpperCase() },
217
- lastSale && { lastSale },
218
- attributes && { attributes },
219
- nftInformation.tokens[0].market?.topBid && {
220
- topBid: nftInformation.tokens[0].market?.topBid
221
- },
222
- rarityRank && { rarityRank },
223
- rarity && { rarity },
224
- collection && { collection }
225
- );
226
- return nftMetadata;
227
- }
228
- /**
229
- * Request individual NFT information from contracts that follows Metadata Interface.
230
- *
231
- * @param contractAddress - Hex address of the NFT contract.
232
- * @param tokenId - The NFT identifier.
233
- * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.
234
- * @returns Promise resolving to the current NFT name and image.
235
- */
236
- async getNftInformationFromTokenURI(contractAddress, tokenId, networkClientId) {
237
- const { ipfsGateway, useIPFSSubdomains, isIpfsGatewayEnabled } = this.config;
238
- const result = await this.getNftURIAndStandard(
239
- contractAddress,
240
- tokenId,
241
- networkClientId
242
- );
243
- let tokenURI = result[0];
244
- const standard = result[1];
245
- const hasIpfsTokenURI = tokenURI.startsWith("ipfs://");
246
- if (hasIpfsTokenURI && !isIpfsGatewayEnabled) {
247
- return {
248
- image: null,
249
- name: null,
250
- description: null,
251
- standard: standard || null,
252
- favorite: false,
253
- tokenURI: tokenURI ?? null
254
- };
255
- }
256
- const isDisplayNFTMediaToggleEnabled = this.config.openSeaEnabled;
257
- if (!hasIpfsTokenURI && !isDisplayNFTMediaToggleEnabled) {
258
- return {
259
- image: null,
260
- name: null,
261
- description: null,
262
- standard: standard || null,
263
- favorite: false,
264
- tokenURI: tokenURI ?? null
265
- };
266
- }
267
- if (hasIpfsTokenURI) {
268
- tokenURI = getFormattedIpfsUrl(ipfsGateway, tokenURI, useIPFSSubdomains);
269
- }
270
- try {
271
- const object = await handleFetch(tokenURI);
272
- const image = Object.prototype.hasOwnProperty.call(object, "image") ? "image" : (
273
- /* istanbul ignore next */
274
- "image_url"
275
- );
276
- return {
277
- image: object[image],
278
- name: object.name,
279
- description: object.description,
280
- standard,
281
- favorite: false,
282
- tokenURI: tokenURI ?? null
283
- };
284
- } catch {
285
- return {
286
- image: null,
287
- name: null,
288
- description: null,
289
- standard: standard || null,
290
- favorite: false,
291
- tokenURI: tokenURI ?? null
292
- };
293
- }
294
- }
295
- /**
296
- * Retrieve NFT uri with metadata. TODO Update method to use IPFS.
297
- *
298
- * @param contractAddress - NFT contract address.
299
- * @param tokenId - NFT token id.
300
- * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.
301
- * @returns Promise resolving NFT uri and token standard.
302
- */
303
- async getNftURIAndStandard(contractAddress, tokenId, networkClientId) {
304
- try {
305
- const uri = await this.getERC721TokenURI(
306
- contractAddress,
307
- tokenId,
308
- networkClientId
309
- );
310
- return [uri, ERC721];
311
- } catch {
312
- }
313
- try {
314
- const tokenURI = await this.getERC1155TokenURI(
315
- contractAddress,
316
- tokenId,
317
- networkClientId
318
- );
319
- if (!tokenURI.includes("{id}")) {
320
- return [tokenURI, ERC1155];
321
- }
322
- const hexTokenId = remove0x(BNToHex(new BN(tokenId))).padStart(64, "0").toLowerCase();
323
- return [tokenURI.replace("{id}", hexTokenId), ERC1155];
324
- } catch {
325
- }
326
- return ["", ""];
327
- }
328
- /**
329
- * Request individual NFT information (name, image url and description).
330
- *
331
- * @param contractAddress - Hex address of the NFT contract.
332
- * @param tokenId - The NFT identifier.
333
- * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.
334
- * @returns Promise resolving to the current NFT name and image.
335
- */
336
- async getNftInformation(contractAddress, tokenId, networkClientId) {
337
- const chainId = this.getCorrectChainId({
338
- networkClientId
339
- });
340
- const [blockchainMetadata, nftApiMetadata] = await Promise.all([
341
- safelyExecute(
342
- () => this.getNftInformationFromTokenURI(
343
- contractAddress,
344
- tokenId,
345
- networkClientId
346
- )
347
- ),
348
- this.config.openSeaEnabled && chainId === "0x1" ? safelyExecute(
349
- () => this.getNftInformationFromApi(contractAddress, tokenId)
350
- ) : void 0
351
- ]);
352
- return {
353
- ...nftApiMetadata,
354
- name: blockchainMetadata?.name ?? nftApiMetadata?.name ?? null,
355
- description: blockchainMetadata?.description ?? nftApiMetadata?.description ?? null,
356
- image: blockchainMetadata?.image ?? nftApiMetadata?.image ?? null,
357
- standard: blockchainMetadata?.standard ?? nftApiMetadata?.standard ?? null,
358
- tokenURI: blockchainMetadata?.tokenURI ?? null
359
- };
360
- }
361
- /**
362
- * Request NFT contract information from the contract itself.
363
- *
364
- * @param contractAddress - Hex address of the NFT contract.
365
- * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.
366
- * @returns Promise resolving to the current NFT name and image.
367
- */
368
- async getNftContractInformationFromContract(contractAddress, networkClientId) {
369
- const [name, symbol] = await Promise.all([
370
- this.getERC721AssetName(contractAddress, networkClientId),
371
- this.getERC721AssetSymbol(contractAddress, networkClientId)
372
- ]);
373
- return {
374
- collection: { name },
375
- symbol,
376
- address: contractAddress
377
- };
378
- }
379
- /**
380
- * Request NFT contract information from Blockchain and aggregate with received data from NFTMetadata.
381
- *
382
- * @param contractAddress - Hex address of the NFT contract.
383
- * @param nftMetadataFromApi - Received NFT information to be aggregated with blockchain contract information.
384
- * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.
385
- * @returns Promise resolving to the NFT contract name, image and description.
386
- */
387
- async getNftContractInformation(contractAddress, nftMetadataFromApi, networkClientId) {
388
- const blockchainContractData = await safelyExecute(
389
- () => this.getNftContractInformationFromContract(
390
- contractAddress,
391
- networkClientId
392
- )
393
- );
394
- if (blockchainContractData || !Object.values(nftMetadataFromApi).every((value) => value === null)) {
395
- return {
396
- address: contractAddress,
397
- ...blockchainContractData,
398
- schema_name: nftMetadataFromApi?.standard ?? null,
399
- collection: {
400
- name: null,
401
- image_url: nftMetadataFromApi?.collection?.image ?? nftMetadataFromApi?.collection?.imageUrl ?? null,
402
- tokenCount: nftMetadataFromApi?.collection?.tokenCount ?? null,
403
- ...nftMetadataFromApi?.collection,
404
- ...blockchainContractData?.collection
405
- }
406
- };
407
- }
408
- return {
409
- address: contractAddress,
410
- asset_contract_type: null,
411
- created_date: null,
412
- schema_name: null,
413
- symbol: null,
414
- total_supply: null,
415
- description: null,
416
- external_link: null,
417
- collection: { name: null, image_url: null }
418
- };
419
- }
420
- /**
421
- * Adds an individual NFT to the stored NFT list.
422
- *
423
- * @param tokenAddress - Hex address of the NFT contract.
424
- * @param tokenId - The NFT identifier.
425
- * @param nftMetadata - NFT optional information (name, image and description).
426
- * @param nftContract - An object containing contract data of the NFT being added.
427
- * @param chainId - The chainId of the network where the NFT is being added.
428
- * @param userAddress - The address of the account where the NFT is being added.
429
- * @param source - Whether the NFT was detected, added manually or suggested by a dapp.
430
- * @returns Promise resolving to the current NFT list.
431
- */
432
- async addIndividualNft(tokenAddress, tokenId, nftMetadata, nftContract, chainId, userAddress, source) {
433
- const releaseLock = await this.mutex.acquire();
434
- try {
435
- tokenAddress = toChecksumHexAddress(tokenAddress);
436
- const { allNfts } = this.state;
437
- const nfts = allNfts[userAddress]?.[chainId] || [];
438
- const existingEntry = nfts.find(
439
- (nft) => nft.address.toLowerCase() === tokenAddress.toLowerCase() && nft.tokenId === tokenId
440
- );
441
- if (existingEntry) {
442
- const differentMetadata = compareNftMetadata(
443
- nftMetadata,
444
- existingEntry
445
- );
446
- if (differentMetadata || !existingEntry.isCurrentlyOwned) {
447
- const indexToRemove = nfts.findIndex(
448
- (nft) => nft.address.toLowerCase() === tokenAddress.toLowerCase() && nft.tokenId === tokenId
449
- );
450
- if (indexToRemove !== -1) {
451
- nfts.splice(indexToRemove, 1);
452
- }
453
- } else {
454
- return nfts;
455
- }
456
- }
457
- const newEntry = {
458
- address: tokenAddress,
459
- tokenId,
460
- favorite: existingEntry?.favorite || false,
461
- isCurrentlyOwned: true,
462
- ...nftMetadata
463
- };
464
- const newNfts = [...nfts, newEntry];
465
- this.updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY, {
466
- chainId,
467
- userAddress
468
- });
469
- if (this.onNftAdded) {
470
- this.onNftAdded({
471
- address: tokenAddress,
472
- symbol: nftContract.symbol,
473
- tokenId: tokenId.toString(),
474
- standard: nftMetadata.standard,
475
- source
476
- });
477
- }
478
- return newNfts;
479
- } finally {
480
- releaseLock();
481
- }
482
- }
483
- /**
484
- * Adds an NFT contract to the stored NFT contracts list.
485
- *
486
- * @param options - options.
487
- * @param options.tokenAddress - Hex address of the NFT contract.
488
- * @param options.userAddress - The address of the account where the NFT is being added.
489
- * @param options.nftMetadata - The retrieved NFTMetadata from API.
490
- * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.
491
- * @param options.source - Whether the NFT was detected, added manually or suggested by a dapp.
492
- * @returns Promise resolving to the current NFT contracts list.
493
- */
494
- async addNftContract({
495
- tokenAddress,
496
- userAddress,
497
- networkClientId,
498
- source,
499
- nftMetadata
500
- }) {
501
- const releaseLock = await this.mutex.acquire();
502
- try {
503
- tokenAddress = toChecksumHexAddress(tokenAddress);
504
- const { allNftContracts } = this.state;
505
- const chainId = this.getCorrectChainId({
506
- networkClientId
507
- });
508
- const nftContracts = allNftContracts[userAddress]?.[chainId] || [];
509
- const existingEntry = nftContracts.find(
510
- (nftContract) => nftContract.address.toLowerCase() === tokenAddress.toLowerCase()
511
- );
512
- if (existingEntry) {
513
- return nftContracts;
514
- }
515
- const contractInformation = await this.getNftContractInformation(
516
- tokenAddress,
517
- nftMetadata,
518
- networkClientId
519
- );
520
- const {
521
- asset_contract_type,
522
- created_date,
523
- symbol,
524
- description,
525
- external_link,
526
- schema_name,
527
- collection: { name, image_url, tokenCount }
528
- } = contractInformation;
529
- if (source === "detected" /* Detected */ && "address" in contractInformation && typeof contractInformation.address === "string" && "collection" in contractInformation && contractInformation.collection.name === null && "image_url" in contractInformation.collection && contractInformation.collection.image_url === null && Object.entries(contractInformation).every(([key, value]) => {
530
- return key === "address" || key === "collection" || !value;
531
- })) {
532
- return nftContracts;
533
- }
534
- const newEntry = Object.assign(
535
- {},
536
- { address: tokenAddress },
537
- description && { description },
538
- name && { name },
539
- image_url && { logo: image_url },
540
- symbol && { symbol },
541
- tokenCount !== null && typeof tokenCount !== "undefined" && { totalSupply: tokenCount },
542
- asset_contract_type && { assetContractType: asset_contract_type },
543
- created_date && { createdDate: created_date },
544
- schema_name && { schemaName: schema_name },
545
- external_link && { externalLink: external_link }
546
- );
547
- const newNftContracts = [...nftContracts, newEntry];
548
- this.updateNestedNftState(newNftContracts, ALL_NFTS_CONTRACTS_STATE_KEY, {
549
- chainId,
550
- userAddress
551
- });
552
- return newNftContracts;
553
- } finally {
554
- releaseLock();
555
- }
556
- }
557
- /**
558
- * Removes an individual NFT from the stored token list and saves it in ignored NFTs list.
559
- *
560
- * @param address - Hex address of the NFT contract.
561
- * @param tokenId - Token identifier of the NFT.
562
- * @param options - options.
563
- * @param options.chainId - The chainId of the network where the NFT is being removed.
564
- * @param options.userAddress - The address of the account where the NFT is being removed.
565
- */
566
- removeAndIgnoreIndividualNft(address, tokenId, {
567
- chainId,
568
- userAddress
569
- }) {
570
- address = toChecksumHexAddress(address);
571
- const { allNfts, ignoredNfts } = this.state;
572
- const newIgnoredNfts = [...ignoredNfts];
573
- const nfts = allNfts[userAddress]?.[chainId] || [];
574
- const newNfts = nfts.filter((nft) => {
575
- if (nft.address.toLowerCase() === address.toLowerCase() && nft.tokenId === tokenId) {
576
- const alreadyIgnored = newIgnoredNfts.find(
577
- (c) => c.address === address && c.tokenId === tokenId
578
- );
579
- !alreadyIgnored && newIgnoredNfts.push(nft);
580
- return false;
581
- }
582
- return true;
583
- });
584
- this.updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY, {
585
- userAddress,
586
- chainId
587
- });
588
- this.update({
589
- ignoredNfts: newIgnoredNfts
590
- });
591
- }
592
- /**
593
- * Removes an individual NFT from the stored token list.
594
- *
595
- * @param address - Hex address of the NFT contract.
596
- * @param tokenId - Token identifier of the NFT.
597
- * @param options - options.
598
- * @param options.chainId - The chainId of the network where the NFT is being removed.
599
- * @param options.userAddress - The address of the account where the NFT is being removed.
600
- */
601
- removeIndividualNft(address, tokenId, { chainId, userAddress }) {
602
- address = toChecksumHexAddress(address);
603
- const { allNfts } = this.state;
604
- const nfts = allNfts[userAddress]?.[chainId] || [];
605
- const newNfts = nfts.filter(
606
- (nft) => !(nft.address.toLowerCase() === address.toLowerCase() && nft.tokenId === tokenId)
607
- );
608
- this.updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY, {
609
- userAddress,
610
- chainId
611
- });
612
- }
613
- /**
614
- * Removes an NFT contract to the stored NFT contracts list.
615
- *
616
- * @param address - Hex address of the NFT contract.
617
- * @param options - options.
618
- * @param options.chainId - The chainId of the network where the NFT is being removed.
619
- * @param options.userAddress - The address of the account where the NFT is being removed.
620
- * @returns Promise resolving to the current NFT contracts list.
621
- */
622
- removeNftContract(address, { chainId, userAddress }) {
623
- address = toChecksumHexAddress(address);
624
- const { allNftContracts } = this.state;
625
- const nftContracts = allNftContracts[userAddress]?.[chainId] || [];
626
- const newNftContracts = nftContracts.filter(
627
- (nftContract) => !(nftContract.address.toLowerCase() === address.toLowerCase())
628
- );
629
- this.updateNestedNftState(newNftContracts, ALL_NFTS_CONTRACTS_STATE_KEY, {
630
- chainId,
631
- userAddress
632
- });
633
- return newNftContracts;
634
- }
635
- async validateWatchNft(asset, type, userAddress, { networkClientId } = {}) {
636
- const { address: contractAddress, tokenId } = asset;
637
- if (!type) {
638
- throw rpcErrors.invalidParams("Asset type is required");
639
- }
640
- if (type !== ERC721 && type !== ERC1155) {
641
- throw rpcErrors.invalidParams(
642
- `Non NFT asset type ${type} not supported by watchNft`
643
- );
644
- }
645
- if (!contractAddress || !tokenId) {
646
- throw rpcErrors.invalidParams("Both address and tokenId are required");
647
- }
648
- if (!isAddress(contractAddress)) {
649
- throw rpcErrors.invalidParams("Invalid address");
650
- }
651
- if (!/^\d+$/u.test(tokenId)) {
652
- throw rpcErrors.invalidParams("Invalid tokenId");
653
- }
654
- try {
655
- const isOwner = await this.isNftOwner(
656
- userAddress,
657
- contractAddress,
658
- tokenId,
659
- { networkClientId }
660
- );
661
- if (!isOwner) {
662
- throw rpcErrors.invalidInput(
663
- "Suggested NFT is not owned by the selected account"
664
- );
665
- }
666
- } catch (error) {
667
- if (error instanceof Error) {
668
- throw rpcErrors.resourceUnavailable(error.message);
669
- }
670
- throw error;
671
- }
672
- }
673
- // temporary method to get the correct chainId until we remove chainId from the config & the chainId arg from the detection logic
674
- // Just a helper method to prefer the networkClient chainId first then the chainId argument and then finally the config chainId
675
- getCorrectChainId({
676
- networkClientId
677
- }) {
678
- if (networkClientId) {
679
- return this.getNetworkClientById(networkClientId).configuration.chainId;
680
- }
681
- return this.config.chainId;
682
- }
683
- /**
684
- * Adds a new suggestedAsset to state. Parameters will be validated according to
685
- * asset type being watched. A `<suggestedNftMeta.id>:pending` hub event will be emitted once added.
686
- *
687
- * @param asset - The asset to be watched. For now ERC721 and ERC1155 tokens are accepted.
688
- * @param asset.address - The address of the asset contract.
689
- * @param asset.tokenId - The ID of the asset.
690
- * @param type - The asset type.
691
- * @param origin - Domain origin to register the asset from.
692
- * @param options - Options bag.
693
- * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.
694
- * @param options.userAddress - The address of the account where the NFT is being added.
695
- * @returns Object containing a Promise resolving to the suggestedAsset address if accepted.
696
- */
697
- async watchNft(asset, type, origin, {
698
- networkClientId,
699
- userAddress = this.config.selectedAddress
700
- } = {
701
- userAddress: this.config.selectedAddress
702
- }) {
703
- await this.validateWatchNft(asset, type, userAddress);
704
- const nftMetadata = await this.getNftInformation(
705
- asset.address,
706
- asset.tokenId,
707
- networkClientId
708
- );
709
- if (nftMetadata.standard && nftMetadata.standard !== type) {
710
- throw rpcErrors.invalidInput(
711
- `Suggested NFT of type ${nftMetadata.standard} does not match received type ${type}`
712
- );
713
- }
714
- const suggestedNftMeta = {
715
- asset: { ...asset, ...nftMetadata },
716
- type,
717
- id: random(),
718
- time: Date.now(),
719
- interactingAddress: userAddress,
720
- origin
721
- };
722
- await this._requestApproval(suggestedNftMeta);
723
- const { address, tokenId } = asset;
724
- const { name, standard, description, image } = nftMetadata;
725
- await this.addNft(address, tokenId, {
726
- nftMetadata: {
727
- name: name ?? null,
728
- description: description ?? null,
729
- image: image ?? null,
730
- standard: standard ?? null
731
- },
732
- userAddress,
733
- source: "dapp" /* Dapp */,
734
- networkClientId
735
- });
736
- }
737
- /**
738
- * Sets an OpenSea API key to retrieve NFT information.
739
- *
740
- * @param openSeaApiKey - OpenSea API key.
741
- */
742
- setApiKey(openSeaApiKey) {
743
- this.openSeaApiKey = openSeaApiKey;
744
- }
745
- /**
746
- * Checks the ownership of a ERC-721 or ERC-1155 NFT for a given address.
747
- *
748
- * @param ownerAddress - User public address.
749
- * @param nftAddress - NFT contract address.
750
- * @param tokenId - NFT token ID.
751
- * @param options - Options bag.
752
- * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.
753
- * @returns Promise resolving the NFT ownership.
754
- */
755
- async isNftOwner(ownerAddress, nftAddress, tokenId, {
756
- networkClientId
757
- } = {}) {
758
- try {
759
- const owner = await this.getERC721OwnerOf(
760
- nftAddress,
761
- tokenId,
762
- networkClientId
763
- );
764
- return ownerAddress.toLowerCase() === owner.toLowerCase();
765
- } catch {
766
- }
767
- try {
768
- const balance = await this.getERC1155BalanceOf(
769
- ownerAddress,
770
- nftAddress,
771
- tokenId,
772
- networkClientId
773
- );
774
- return !balance.isZero();
775
- } catch {
776
- }
777
- throw new Error(
778
- `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.`
779
- );
780
- }
781
- /**
782
- * Verifies currently selected address owns entered NFT address/tokenId combo and
783
- * adds the NFT and respective NFT contract to the stored NFT and NFT contracts lists.
784
- *
785
- * @param address - Hex address of the NFT contract.
786
- * @param tokenId - The NFT identifier.
787
- * @param options - an object of arguments
788
- * @param options.userAddress - The address of the current user.
789
- * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.
790
- * @param options.source - Whether the NFT was detected, added manually or suggested by a dapp.
791
- */
792
- async addNftVerifyOwnership(address, tokenId, {
793
- userAddress = this.config.selectedAddress,
794
- networkClientId,
795
- source
796
- } = {
797
- userAddress: this.config.selectedAddress
798
- }) {
799
- if (!await this.isNftOwner(userAddress, address, tokenId, {
800
- networkClientId
801
- })) {
802
- throw new Error("This NFT is not owned by the user");
803
- }
804
- await this.addNft(address, tokenId, {
805
- networkClientId,
806
- userAddress,
807
- source
808
- });
809
- }
810
- /**
811
- * Adds an NFT and respective NFT contract to the stored NFT and NFT contracts lists.
812
- *
813
- * @param tokenAddress - Hex address of the NFT contract.
814
- * @param tokenId - The NFT identifier.
815
- * @param options - an object of arguments
816
- * @param options.nftMetadata - NFT optional metadata.
817
- * @param options.userAddress - The address of the current user.
818
- * @param options.source - Whether the NFT was detected, added manually or suggested by a dapp.
819
- * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.
820
- * @returns Promise resolving to the current NFT list.
821
- */
822
- async addNft(tokenAddress, tokenId, {
823
- nftMetadata,
824
- userAddress = this.config.selectedAddress,
825
- source = "custom" /* Custom */,
826
- networkClientId
827
- } = { userAddress: this.config.selectedAddress }) {
828
- tokenAddress = toChecksumHexAddress(tokenAddress);
829
- const chainId = this.getCorrectChainId({ networkClientId });
830
- nftMetadata = nftMetadata || await this.getNftInformation(tokenAddress, tokenId, networkClientId);
831
- const newNftContracts = await this.addNftContract({
832
- tokenAddress,
833
- userAddress,
834
- networkClientId,
835
- source,
836
- nftMetadata
837
- });
838
- const nftContract = newNftContracts.find(
839
- (contract) => contract.address.toLowerCase() === tokenAddress.toLowerCase()
840
- );
841
- if (nftContract) {
842
- await this.addIndividualNft(
843
- tokenAddress,
844
- tokenId,
845
- nftMetadata,
846
- nftContract,
847
- chainId,
848
- userAddress,
849
- source
850
- );
851
- }
852
- }
853
- /**
854
- * Refetches NFT metadata and updates the state
855
- *
856
- * @param options - Options for refetching NFT metadata
857
- * @param options.nfts - nfts to update metadata for.
858
- * @param options.userAddress - The current user address
859
- * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.
860
- */
861
- async updateNftMetadata({
862
- nfts,
863
- userAddress = this.config.selectedAddress,
864
- networkClientId
865
- }) {
866
- const chainId = this.getCorrectChainId({ networkClientId });
867
- const nftsWithChecksumAdr = nfts.map((nft) => {
868
- return {
869
- ...nft,
870
- address: toChecksumHexAddress(nft.address)
871
- };
872
- });
873
- const nftMetadataResults = await Promise.allSettled(
874
- nftsWithChecksumAdr.map(async (nft) => {
875
- const resMetadata = await this.getNftInformation(
876
- nft.address,
877
- nft.tokenId,
878
- networkClientId
879
- );
880
- return {
881
- nft,
882
- newMetadata: resMetadata
883
- };
884
- })
885
- );
886
- const successfulNewFetchedNfts = nftMetadataResults.filter(
887
- (result) => result.status === "fulfilled"
888
- );
889
- const nftsWithDifferentMetadata = [];
890
- const { allNfts } = this.state;
891
- const stateNfts = allNfts[userAddress]?.[chainId] || [];
892
- successfulNewFetchedNfts.forEach((singleNft) => {
893
- const existingEntry = stateNfts.find(
894
- (nft) => nft.address.toLowerCase() === singleNft.value.nft.address.toLowerCase() && nft.tokenId === singleNft.value.nft.tokenId
895
- );
896
- if (existingEntry) {
897
- const differentMetadata = compareNftMetadata(
898
- singleNft.value.newMetadata,
899
- existingEntry
900
- );
901
- if (differentMetadata) {
902
- nftsWithDifferentMetadata.push(singleNft);
903
- }
904
- }
905
- });
906
- if (nftsWithDifferentMetadata.length !== 0) {
907
- nftsWithDifferentMetadata.forEach(
908
- (elm) => this.updateNft(
909
- elm.value.nft,
910
- elm.value.newMetadata,
911
- userAddress,
912
- chainId
913
- )
914
- );
915
- }
916
- }
917
- /**
918
- * Removes an NFT from the stored token list.
919
- *
920
- * @param address - Hex address of the NFT contract.
921
- * @param tokenId - Token identifier of the NFT.
922
- * @param options - an object of arguments
923
- * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.
924
- * @param options.userAddress - The address of the account where the NFT is being removed.
925
- */
926
- removeNft(address, tokenId, {
927
- networkClientId,
928
- userAddress = this.config.selectedAddress
929
- } = {
930
- userAddress: this.config.selectedAddress
931
- }) {
932
- const chainId = this.getCorrectChainId({ networkClientId });
933
- address = toChecksumHexAddress(address);
934
- this.removeIndividualNft(address, tokenId, { chainId, userAddress });
935
- const { allNfts } = this.state;
936
- const nfts = allNfts[userAddress]?.[chainId] || [];
937
- const remainingNft = nfts.find(
938
- (nft) => nft.address.toLowerCase() === address.toLowerCase()
939
- );
940
- if (!remainingNft) {
941
- this.removeNftContract(address, { chainId, userAddress });
942
- }
943
- }
944
- /**
945
- * Removes an NFT from the stored token list and saves it in ignored NFTs list.
946
- *
947
- * @param address - Hex address of the NFT contract.
948
- * @param tokenId - Token identifier of the NFT.
949
- * @param options - an object of arguments
950
- * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.
951
- * @param options.userAddress - The address of the account where the NFT is being removed.
952
- */
953
- removeAndIgnoreNft(address, tokenId, {
954
- networkClientId,
955
- userAddress = this.config.selectedAddress
956
- } = {
957
- userAddress: this.config.selectedAddress
958
- }) {
959
- const chainId = this.getCorrectChainId({ networkClientId });
960
- address = toChecksumHexAddress(address);
961
- this.removeAndIgnoreIndividualNft(address, tokenId, {
962
- chainId,
963
- userAddress
964
- });
965
- const { allNfts } = this.state;
966
- const nfts = allNfts[userAddress]?.[chainId] || [];
967
- const remainingNft = nfts.find(
968
- (nft) => nft.address.toLowerCase() === address.toLowerCase()
969
- );
970
- if (!remainingNft) {
971
- this.removeNftContract(address, { chainId, userAddress });
972
- }
973
- }
974
- /**
975
- * Removes all NFTs from the ignored list.
976
- */
977
- clearIgnoredNfts() {
978
- this.update({ ignoredNfts: [] });
979
- }
980
- /**
981
- * Checks whether input NFT is still owned by the user
982
- * And updates the isCurrentlyOwned value on the NFT object accordingly.
983
- *
984
- * @param nft - The NFT object to check and update.
985
- * @param batch - A boolean indicating whether this method is being called as part of a batch or single update.
986
- * @param accountParams - The userAddress and chainId to check ownership against
987
- * @param accountParams.userAddress - the address passed through the confirmed transaction flow to ensure assets are stored to the correct account
988
- * @param accountParams.networkClientId - The networkClientId that can be used to identify the network client to use for this request.
989
- * @returns the NFT with the updated isCurrentlyOwned value
990
- */
991
- async checkAndUpdateSingleNftOwnershipStatus(nft, batch, {
992
- userAddress = this.config.selectedAddress,
993
- networkClientId
994
- } = {
995
- userAddress: this.config.selectedAddress
996
- }) {
997
- const chainId = this.getCorrectChainId({ networkClientId });
998
- const { address, tokenId } = nft;
999
- let isOwned = nft.isCurrentlyOwned;
1000
- try {
1001
- isOwned = await this.isNftOwner(userAddress, address, tokenId, {
1002
- networkClientId
1003
- });
1004
- } catch {
1005
- }
1006
- nft.isCurrentlyOwned = isOwned;
1007
- if (batch) {
1008
- return nft;
1009
- }
1010
- const { allNfts } = this.state;
1011
- const nfts = allNfts[userAddress]?.[chainId] || [];
1012
- const nftToUpdate = nfts.find(
1013
- (item) => item.tokenId === tokenId && item.address.toLowerCase() === address.toLowerCase()
1014
- );
1015
- if (nftToUpdate) {
1016
- nftToUpdate.isCurrentlyOwned = isOwned;
1017
- this.updateNestedNftState(nfts, ALL_NFTS_STATE_KEY, {
1018
- userAddress,
1019
- chainId
1020
- });
1021
- }
1022
- return nft;
1023
- }
1024
- /**
1025
- * Checks whether NFTs associated with current selectedAddress/chainId combination are still owned by the user
1026
- * And updates the isCurrentlyOwned value on each accordingly.
1027
- * @param options - an object of arguments
1028
- * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.
1029
- * @param options.userAddress - The address of the account where the NFT ownership status is checked/updated.
1030
- */
1031
- async checkAndUpdateAllNftsOwnershipStatus({
1032
- networkClientId,
1033
- userAddress = this.config.selectedAddress
1034
- } = {
1035
- userAddress: this.config.selectedAddress
1036
- }) {
1037
- const chainId = this.getCorrectChainId({ networkClientId });
1038
- const { allNfts } = this.state;
1039
- const nfts = allNfts[userAddress]?.[chainId] || [];
1040
- const updatedNfts = await Promise.all(
1041
- nfts.map(async (nft) => {
1042
- return await this.checkAndUpdateSingleNftOwnershipStatus(nft, true, {
1043
- networkClientId,
1044
- userAddress
1045
- }) ?? nft;
1046
- })
1047
- );
1048
- this.updateNestedNftState(updatedNfts, ALL_NFTS_STATE_KEY, {
1049
- userAddress,
1050
- chainId
1051
- });
1052
- }
1053
- /**
1054
- * Update NFT favorite status.
1055
- *
1056
- * @param address - Hex address of the NFT contract.
1057
- * @param tokenId - Hex address of the NFT contract.
1058
- * @param favorite - NFT new favorite status.
1059
- * @param options - an object of arguments
1060
- * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.
1061
- * @param options.userAddress - The address of the account where the NFT is being removed.
1062
- */
1063
- updateNftFavoriteStatus(address, tokenId, favorite, {
1064
- networkClientId,
1065
- userAddress = this.config.selectedAddress
1066
- } = {
1067
- userAddress: this.config.selectedAddress
1068
- }) {
1069
- const chainId = this.getCorrectChainId({ networkClientId });
1070
- const { allNfts } = this.state;
1071
- const nfts = allNfts[userAddress]?.[chainId] || [];
1072
- const index = nfts.findIndex(
1073
- (nft) => nft.address === address && nft.tokenId === tokenId
1074
- );
1075
- if (index === -1) {
1076
- return;
1077
- }
1078
- const updatedNft = {
1079
- ...nfts[index],
1080
- favorite
1081
- };
1082
- nfts[index] = updatedNft;
1083
- this.updateNestedNftState(nfts, ALL_NFTS_STATE_KEY, {
1084
- chainId,
1085
- userAddress
1086
- });
1087
- }
1088
- /**
1089
- * Returns an NFT by the address and token id.
1090
- *
1091
- * @param address - Hex address of the NFT contract.
1092
- * @param tokenId - Number that represents the id of the token.
1093
- * @param selectedAddress - Hex address of the user account.
1094
- * @param chainId - Id of the current network.
1095
- * @returns Object containing the NFT and its position in the array
1096
- */
1097
- findNftByAddressAndTokenId(address, tokenId, selectedAddress, chainId) {
1098
- const { allNfts } = this.state;
1099
- const nfts = allNfts[selectedAddress]?.[chainId] || [];
1100
- const index = nfts.findIndex(
1101
- (nft) => nft.address.toLowerCase() === address.toLowerCase() && nft.tokenId === tokenId
1102
- );
1103
- if (index === -1) {
1104
- return null;
1105
- }
1106
- return { nft: nfts[index], index };
1107
- }
1108
- /**
1109
- * Update NFT data.
1110
- *
1111
- * @param nft - NFT object to find the right NFT to updates.
1112
- * @param updates - NFT partial object to update properties of the NFT.
1113
- * @param selectedAddress - Hex address of the user account.
1114
- * @param chainId - Id of the current network.
1115
- */
1116
- updateNft(nft, updates, selectedAddress, chainId) {
1117
- const { allNfts } = this.state;
1118
- const nfts = allNfts[selectedAddress]?.[chainId] || [];
1119
- const nftInfo = this.findNftByAddressAndTokenId(
1120
- nft.address,
1121
- nft.tokenId,
1122
- selectedAddress,
1123
- chainId
1124
- );
1125
- if (!nftInfo) {
1126
- return;
1127
- }
1128
- const updatedNft = {
1129
- ...nft,
1130
- ...updates
1131
- };
1132
- const newNfts = [
1133
- ...nfts.slice(0, nftInfo.index),
1134
- updatedNft,
1135
- ...nfts.slice(nftInfo.index + 1)
1136
- ];
1137
- this.updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY, {
1138
- chainId,
1139
- userAddress: selectedAddress
1140
- });
1141
- }
1142
- /**
1143
- * Resets the transaction status of an NFT.
1144
- *
1145
- * @param transactionId - NFT transaction id.
1146
- * @param selectedAddress - Hex address of the user account.
1147
- * @param chainId - Id of the current network.
1148
- * @returns a boolean indicating if the reset was well succeeded or not
1149
- */
1150
- resetNftTransactionStatusByTransactionId(transactionId, selectedAddress, chainId) {
1151
- const { allNfts } = this.state;
1152
- const nfts = allNfts[selectedAddress]?.[chainId] || [];
1153
- const index = nfts.findIndex(
1154
- (nft) => nft.transactionId === transactionId
1155
- );
1156
- if (index === -1) {
1157
- return false;
1158
- }
1159
- const updatedNft = {
1160
- ...nfts[index],
1161
- transactionId: void 0
1162
- };
1163
- const newNfts = [
1164
- ...nfts.slice(0, index),
1165
- updatedNft,
1166
- ...nfts.slice(index + 1)
1167
- ];
1168
- this.updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY, {
1169
- chainId,
1170
- userAddress: selectedAddress
1171
- });
1172
- return true;
1173
- }
1174
- async _requestApproval(suggestedNftMeta) {
1175
- return this.messagingSystem.call(
1176
- "ApprovalController:addRequest",
1177
- {
1178
- id: suggestedNftMeta.id,
1179
- origin: suggestedNftMeta.origin,
1180
- type: ApprovalType.WatchAsset,
1181
- requestData: {
1182
- id: suggestedNftMeta.id,
1183
- interactingAddress: suggestedNftMeta.interactingAddress,
1184
- asset: {
1185
- address: suggestedNftMeta.asset.address,
1186
- tokenId: suggestedNftMeta.asset.tokenId,
1187
- name: suggestedNftMeta.asset.name,
1188
- description: suggestedNftMeta.asset.description,
1189
- image: suggestedNftMeta.asset.image,
1190
- standard: suggestedNftMeta.asset.standard
1191
- }
1192
- }
1193
- },
1194
- true
1195
- );
1196
- }
1197
- };
1198
- var NftController_default = NftController;
1199
-
1200
- export {
1201
- getDefaultNftState,
1202
- NftController,
1203
- NftController_default
1204
- };
1205
- //# sourceMappingURL=chunk-46UZDIXW.mjs.map