@metamask-previews/assets-controllers 11.0.1-preview.3dbf14f

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 (80) hide show
  1. package/CHANGELOG.md +235 -0
  2. package/LICENSE +20 -0
  3. package/README.md +30 -0
  4. package/dist/AccountTrackerController.d.ts +106 -0
  5. package/dist/AccountTrackerController.d.ts.map +1 -0
  6. package/dist/AccountTrackerController.js +163 -0
  7. package/dist/AccountTrackerController.js.map +1 -0
  8. package/dist/AssetsContractController.d.ts +188 -0
  9. package/dist/AssetsContractController.d.ts.map +1 -0
  10. package/dist/AssetsContractController.js +330 -0
  11. package/dist/AssetsContractController.js.map +1 -0
  12. package/dist/CurrencyRateController.d.ts +101 -0
  13. package/dist/CurrencyRateController.d.ts.map +1 -0
  14. package/dist/CurrencyRateController.js +219 -0
  15. package/dist/CurrencyRateController.js.map +1 -0
  16. package/dist/NftController.d.ts +466 -0
  17. package/dist/NftController.d.ts.map +1 -0
  18. package/dist/NftController.js +943 -0
  19. package/dist/NftController.js.map +1 -0
  20. package/dist/NftDetectionController.d.ts +182 -0
  21. package/dist/NftDetectionController.d.ts.map +1 -0
  22. package/dist/NftDetectionController.js +188 -0
  23. package/dist/NftDetectionController.js.map +1 -0
  24. package/dist/Standards/ERC20Standard.d.ts +50 -0
  25. package/dist/Standards/ERC20Standard.d.ts.map +1 -0
  26. package/dist/Standards/ERC20Standard.js +144 -0
  27. package/dist/Standards/ERC20Standard.js.map +1 -0
  28. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts +79 -0
  29. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts.map +1 -0
  30. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js +148 -0
  31. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js.map +1 -0
  32. package/dist/Standards/NftStandards/ERC721/ERC721Standard.d.ts +89 -0
  33. package/dist/Standards/NftStandards/ERC721/ERC721Standard.d.ts.map +1 -0
  34. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js +182 -0
  35. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js.map +1 -0
  36. package/dist/Standards/standards-types.d.ts +15 -0
  37. package/dist/Standards/standards-types.d.ts.map +1 -0
  38. package/dist/Standards/standards-types.js +3 -0
  39. package/dist/Standards/standards-types.js.map +1 -0
  40. package/dist/TokenBalancesController.d.ts +71 -0
  41. package/dist/TokenBalancesController.d.ts.map +1 -0
  42. package/dist/TokenBalancesController.js +94 -0
  43. package/dist/TokenBalancesController.js.map +1 -0
  44. package/dist/TokenDetectionController.d.ts +87 -0
  45. package/dist/TokenDetectionController.d.ts.map +1 -0
  46. package/dist/TokenDetectionController.js +189 -0
  47. package/dist/TokenDetectionController.js.map +1 -0
  48. package/dist/TokenListController.d.ts +117 -0
  49. package/dist/TokenListController.d.ts.map +1 -0
  50. package/dist/TokenListController.js +248 -0
  51. package/dist/TokenListController.js.map +1 -0
  52. package/dist/TokenRatesController.d.ts +172 -0
  53. package/dist/TokenRatesController.d.ts.map +1 -0
  54. package/dist/TokenRatesController.js +327 -0
  55. package/dist/TokenRatesController.js.map +1 -0
  56. package/dist/TokensController.d.ts +250 -0
  57. package/dist/TokensController.d.ts.map +1 -0
  58. package/dist/TokensController.js +550 -0
  59. package/dist/TokensController.js.map +1 -0
  60. package/dist/assetsUtil.d.ts +109 -0
  61. package/dist/assetsUtil.d.ts.map +1 -0
  62. package/dist/assetsUtil.js +227 -0
  63. package/dist/assetsUtil.js.map +1 -0
  64. package/dist/constants.d.ts +6 -0
  65. package/dist/constants.d.ts.map +1 -0
  66. package/dist/constants.js +10 -0
  67. package/dist/constants.js.map +1 -0
  68. package/dist/crypto-compare.d.ts +13 -0
  69. package/dist/crypto-compare.d.ts.map +1 -0
  70. package/dist/crypto-compare.js +67 -0
  71. package/dist/crypto-compare.js.map +1 -0
  72. package/dist/index.d.ts +12 -0
  73. package/dist/index.d.ts.map +1 -0
  74. package/dist/index.js +32 -0
  75. package/dist/index.js.map +1 -0
  76. package/dist/token-service.d.ts +31 -0
  77. package/dist/token-service.d.ts.map +1 -0
  78. package/dist/token-service.js +134 -0
  79. package/dist/token-service.js.map +1 -0
  80. package/package.json +82 -0
@@ -0,0 +1,943 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.NftController = void 0;
13
+ const address_1 = require("@ethersproject/address");
14
+ const base_controller_1 = require("@metamask/base-controller");
15
+ const controller_utils_1 = require("@metamask/controller-utils");
16
+ const rpc_errors_1 = require("@metamask/rpc-errors");
17
+ const async_mutex_1 = require("async-mutex");
18
+ const ethereumjs_util_1 = require("ethereumjs-util");
19
+ const events_1 = require("events");
20
+ const uuid_1 = require("uuid");
21
+ const assetsUtil_1 = require("./assetsUtil");
22
+ const constants_1 = require("./constants");
23
+ const ALL_NFTS_STATE_KEY = 'allNfts';
24
+ const ALL_NFTS_CONTRACTS_STATE_KEY = 'allNftContracts';
25
+ /**
26
+ * The name of the {@link NftController}.
27
+ */
28
+ const controllerName = 'NftController';
29
+ /**
30
+ * Controller that stores assets and exposes convenience methods
31
+ */
32
+ class NftController extends base_controller_1.BaseController {
33
+ /**
34
+ * Creates an NftController instance.
35
+ *
36
+ * @param options - The controller options.
37
+ * @param options.chainId - The chain ID of the current network.
38
+ * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.
39
+ * @param options.onNetworkStateChange - Allows subscribing to network controller state changes.
40
+ * @param options.getERC721AssetName - Gets the name of the asset at the given address.
41
+ * @param options.getERC721AssetSymbol - Gets the symbol of the asset at the given address.
42
+ * @param options.getERC721TokenURI - Gets the URI of the ERC721 token at the given address, with the given ID.
43
+ * @param options.getERC721OwnerOf - Get the owner of a ERC-721 NFT.
44
+ * @param options.getERC1155BalanceOf - Gets balance of a ERC-1155 NFT.
45
+ * @param options.getERC1155TokenURI - Gets the URI of the ERC1155 token at the given address, with the given ID.
46
+ * @param options.onNftAdded - Callback that is called when an NFT is added. Currently used pass data
47
+ * for tracking the NFT added event.
48
+ * @param options.messenger - The controller messenger.
49
+ * @param config - Initial options used to configure this controller.
50
+ * @param state - Initial state to set on this controller.
51
+ */
52
+ constructor({ chainId: initialChainId, onPreferencesStateChange, onNetworkStateChange, getERC721AssetName, getERC721AssetSymbol, getERC721TokenURI, getERC721OwnerOf, getERC1155BalanceOf, getERC1155TokenURI, onNftAdded, messenger, }, config, state) {
53
+ super(config, state);
54
+ this.mutex = new async_mutex_1.Mutex();
55
+ /**
56
+ * EventEmitter instance used to listen to specific EIP747 events
57
+ */
58
+ this.hub = new events_1.EventEmitter();
59
+ /**
60
+ * Name of this controller used during composition
61
+ */
62
+ this.name = 'NftController';
63
+ this.defaultConfig = {
64
+ selectedAddress: '',
65
+ chainId: initialChainId,
66
+ ipfsGateway: controller_utils_1.IPFS_DEFAULT_GATEWAY_URL,
67
+ openSeaEnabled: false,
68
+ useIPFSSubdomains: true,
69
+ isIpfsGatewayEnabled: true,
70
+ };
71
+ this.defaultState = {
72
+ allNftContracts: {},
73
+ allNfts: {},
74
+ ignoredNfts: [],
75
+ };
76
+ this.initialize();
77
+ this.getERC721AssetName = getERC721AssetName;
78
+ this.getERC721AssetSymbol = getERC721AssetSymbol;
79
+ this.getERC721TokenURI = getERC721TokenURI;
80
+ this.getERC721OwnerOf = getERC721OwnerOf;
81
+ this.getERC1155BalanceOf = getERC1155BalanceOf;
82
+ this.getERC1155TokenURI = getERC1155TokenURI;
83
+ this.onNftAdded = onNftAdded;
84
+ this.messagingSystem = messenger;
85
+ onPreferencesStateChange(({ selectedAddress, ipfsGateway, openSeaEnabled, isIpfsGatewayEnabled, }) => {
86
+ this.configure({
87
+ selectedAddress,
88
+ ipfsGateway,
89
+ openSeaEnabled,
90
+ isIpfsGatewayEnabled,
91
+ });
92
+ });
93
+ onNetworkStateChange(({ providerConfig }) => {
94
+ const { chainId } = providerConfig;
95
+ this.configure({ chainId });
96
+ });
97
+ }
98
+ getNftApi({ contractAddress, tokenId, }) {
99
+ return `${controller_utils_1.OPENSEA_PROXY_URL}/asset/${contractAddress}/${tokenId}`;
100
+ }
101
+ getNftContractInformationApi({ contractAddress, useProxy, }) {
102
+ return useProxy
103
+ ? `${controller_utils_1.OPENSEA_PROXY_URL}/asset_contract/${contractAddress}`
104
+ : `${controller_utils_1.OPENSEA_API_URL}/asset_contract/${contractAddress}`;
105
+ }
106
+ /**
107
+ * Helper method to update nested state for allNfts and allNftContracts.
108
+ *
109
+ * @param newCollection - the modified piece of state to update in the controller's store
110
+ * @param baseStateKey - The root key in the store to update.
111
+ * @param passedConfig - An object containing the selectedAddress and chainId that are passed through the auto-detection flow.
112
+ * @param passedConfig.userAddress - the address passed through the NFT detection flow to ensure assets are stored to the correct account
113
+ * @param passedConfig.chainId - the chainId passed through the NFT detection flow to ensure assets are stored to the correct account
114
+ */
115
+ updateNestedNftState(newCollection, baseStateKey, { userAddress, chainId } = {
116
+ userAddress: this.config.selectedAddress,
117
+ chainId: this.config.chainId,
118
+ }) {
119
+ const { [baseStateKey]: oldState } = this.state;
120
+ const addressState = oldState[userAddress];
121
+ const newAddressState = Object.assign(Object.assign({}, addressState), { [chainId]: newCollection });
122
+ const newState = Object.assign(Object.assign({}, oldState), { [userAddress]: newAddressState });
123
+ this.update({
124
+ [baseStateKey]: newState,
125
+ });
126
+ }
127
+ /**
128
+ * Request individual NFT information from OpenSea API.
129
+ *
130
+ * @param contractAddress - Hex address of the NFT contract.
131
+ * @param tokenId - The NFT identifier.
132
+ * @returns Promise resolving to the current NFT name and image.
133
+ */
134
+ getNftInformationFromApi(contractAddress, tokenId) {
135
+ return __awaiter(this, void 0, void 0, function* () {
136
+ // Attempt to fetch the data with the proxy
137
+ const nftInformation = yield (0, controller_utils_1.fetchWithErrorHandling)({
138
+ url: this.getNftApi({
139
+ contractAddress,
140
+ tokenId,
141
+ }),
142
+ });
143
+ // if we were still unable to fetch the data we return out the default/null of `NftMetadata`
144
+ if (!nftInformation) {
145
+ return {
146
+ name: null,
147
+ description: null,
148
+ image: null,
149
+ standard: null,
150
+ };
151
+ }
152
+ // if we've reached this point, we have successfully fetched some data for nftInformation
153
+ // now we reconfigure the data to conform to the `NftMetadata` type for storage.
154
+ const { num_sales, background_color, image_url, image_preview_url, image_thumbnail_url, image_original_url, animation_url, animation_original_url, name, description, external_link, creator, last_sale, asset_contract: { schema_name }, } = nftInformation;
155
+ /* istanbul ignore next */
156
+ const nftMetadata = Object.assign({}, { name: name || null }, { description: description || null }, { image: image_url || null }, creator && { creator }, num_sales && { numberOfSales: num_sales }, background_color && { backgroundColor: background_color }, image_preview_url && { imagePreview: image_preview_url }, image_thumbnail_url && { imageThumbnail: image_thumbnail_url }, image_original_url && { imageOriginal: image_original_url }, animation_url && { animation: animation_url }, animation_original_url && {
157
+ animationOriginal: animation_original_url,
158
+ }, external_link && { externalLink: external_link }, last_sale && { lastSale: last_sale }, schema_name && { standard: schema_name });
159
+ return nftMetadata;
160
+ });
161
+ }
162
+ /**
163
+ * Request individual NFT information from contracts that follows Metadata Interface.
164
+ *
165
+ * @param contractAddress - Hex address of the NFT contract.
166
+ * @param tokenId - The NFT identifier.
167
+ * @returns Promise resolving to the current NFT name and image.
168
+ */
169
+ getNftInformationFromTokenURI(contractAddress, tokenId) {
170
+ return __awaiter(this, void 0, void 0, function* () {
171
+ const { ipfsGateway, useIPFSSubdomains, isIpfsGatewayEnabled } = this.config;
172
+ const result = yield this.getNftURIAndStandard(contractAddress, tokenId);
173
+ let tokenURI = result[0];
174
+ const standard = result[1];
175
+ const hasIpfsTokenURI = tokenURI.startsWith('ipfs://');
176
+ if (hasIpfsTokenURI && !isIpfsGatewayEnabled) {
177
+ return {
178
+ image: null,
179
+ name: null,
180
+ description: null,
181
+ standard: standard || null,
182
+ favorite: false,
183
+ tokenURI: tokenURI !== null && tokenURI !== void 0 ? tokenURI : null,
184
+ };
185
+ }
186
+ if (hasIpfsTokenURI) {
187
+ tokenURI = (0, assetsUtil_1.getFormattedIpfsUrl)(ipfsGateway, tokenURI, useIPFSSubdomains);
188
+ }
189
+ try {
190
+ const object = yield (0, controller_utils_1.handleFetch)(tokenURI);
191
+ // TODO: Check image_url existence. This is not part of EIP721 nor EIP1155
192
+ const image = Object.prototype.hasOwnProperty.call(object, 'image')
193
+ ? 'image'
194
+ : /* istanbul ignore next */ 'image_url';
195
+ return {
196
+ image: object[image],
197
+ name: object.name,
198
+ description: object.description,
199
+ standard,
200
+ favorite: false,
201
+ tokenURI: tokenURI !== null && tokenURI !== void 0 ? tokenURI : null,
202
+ };
203
+ }
204
+ catch (_a) {
205
+ return {
206
+ image: null,
207
+ name: null,
208
+ description: null,
209
+ standard: standard || null,
210
+ favorite: false,
211
+ tokenURI: tokenURI !== null && tokenURI !== void 0 ? tokenURI : null,
212
+ };
213
+ }
214
+ });
215
+ }
216
+ /**
217
+ * Retrieve NFT uri with metadata. TODO Update method to use IPFS.
218
+ *
219
+ * @param contractAddress - NFT contract address.
220
+ * @param tokenId - NFT token id.
221
+ * @returns Promise resolving NFT uri and token standard.
222
+ */
223
+ getNftURIAndStandard(contractAddress, tokenId) {
224
+ return __awaiter(this, void 0, void 0, function* () {
225
+ // try ERC721 uri
226
+ try {
227
+ const uri = yield this.getERC721TokenURI(contractAddress, tokenId);
228
+ return [uri, controller_utils_1.ERC721];
229
+ }
230
+ catch (_a) {
231
+ // Ignore error
232
+ }
233
+ // try ERC1155 uri
234
+ try {
235
+ const tokenURI = yield this.getERC1155TokenURI(contractAddress, tokenId);
236
+ /**
237
+ * According to EIP1155 the URI value allows for ID substitution
238
+ * in case the string `{id}` exists.
239
+ * https://eips.ethereum.org/EIPS/eip-1155#metadata
240
+ */
241
+ if (!tokenURI.includes('{id}')) {
242
+ return [tokenURI, controller_utils_1.ERC1155];
243
+ }
244
+ const hexTokenId = (0, ethereumjs_util_1.stripHexPrefix)((0, controller_utils_1.BNToHex)(new ethereumjs_util_1.BN(tokenId)))
245
+ .padStart(64, '0')
246
+ .toLowerCase();
247
+ return [tokenURI.replace('{id}', hexTokenId), controller_utils_1.ERC1155];
248
+ }
249
+ catch (_b) {
250
+ // Ignore error
251
+ }
252
+ return ['', ''];
253
+ });
254
+ }
255
+ /**
256
+ * Request individual NFT information (name, image url and description).
257
+ *
258
+ * @param contractAddress - Hex address of the NFT contract.
259
+ * @param tokenId - The NFT identifier.
260
+ * @returns Promise resolving to the current NFT name and image.
261
+ */
262
+ getNftInformation(contractAddress, tokenId) {
263
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
264
+ return __awaiter(this, void 0, void 0, function* () {
265
+ const blockchainMetadata = yield (0, controller_utils_1.safelyExecute)(() => __awaiter(this, void 0, void 0, function* () {
266
+ return yield this.getNftInformationFromTokenURI(contractAddress, tokenId);
267
+ }));
268
+ let openSeaMetadata;
269
+ if (this.config.openSeaEnabled) {
270
+ openSeaMetadata = yield (0, controller_utils_1.safelyExecute)(() => __awaiter(this, void 0, void 0, function* () {
271
+ return yield this.getNftInformationFromApi(contractAddress, tokenId);
272
+ }));
273
+ }
274
+ return Object.assign(Object.assign({}, openSeaMetadata), { name: (_b = (_a = blockchainMetadata.name) !== null && _a !== void 0 ? _a : openSeaMetadata === null || openSeaMetadata === void 0 ? void 0 : openSeaMetadata.name) !== null && _b !== void 0 ? _b : null, description: (_d = (_c = blockchainMetadata.description) !== null && _c !== void 0 ? _c : openSeaMetadata === null || openSeaMetadata === void 0 ? void 0 : openSeaMetadata.description) !== null && _d !== void 0 ? _d : null, image: (_f = (_e = blockchainMetadata.image) !== null && _e !== void 0 ? _e : openSeaMetadata === null || openSeaMetadata === void 0 ? void 0 : openSeaMetadata.image) !== null && _f !== void 0 ? _f : null, standard: (_h = (_g = blockchainMetadata.standard) !== null && _g !== void 0 ? _g : openSeaMetadata === null || openSeaMetadata === void 0 ? void 0 : openSeaMetadata.standard) !== null && _h !== void 0 ? _h : null, tokenURI: (_j = blockchainMetadata.tokenURI) !== null && _j !== void 0 ? _j : null });
275
+ });
276
+ }
277
+ /**
278
+ * Request NFT contract information from OpenSea API.
279
+ *
280
+ * @param contractAddress - Hex address of the NFT contract.
281
+ * @returns Promise resolving to the current NFT name and image.
282
+ */
283
+ getNftContractInformationFromApi(contractAddress) {
284
+ return __awaiter(this, void 0, void 0, function* () {
285
+ /* istanbul ignore if */
286
+ let apiNftContractObject = yield (0, controller_utils_1.fetchWithErrorHandling)({
287
+ url: this.getNftContractInformationApi({
288
+ contractAddress,
289
+ useProxy: true,
290
+ }),
291
+ });
292
+ // if we successfully fetched return the fetched data immediately
293
+ if (apiNftContractObject) {
294
+ return apiNftContractObject;
295
+ }
296
+ // if we were unsuccessful in fetching from the API and an OpenSea API key is present
297
+ // attempt to refetch directly against the OpenSea API and if successful return the data immediately
298
+ if (this.openSeaApiKey) {
299
+ apiNftContractObject = yield (0, controller_utils_1.fetchWithErrorHandling)({
300
+ url: this.getNftContractInformationApi({
301
+ contractAddress,
302
+ useProxy: false,
303
+ }),
304
+ options: {
305
+ headers: { 'X-API-KEY': this.openSeaApiKey },
306
+ },
307
+ // catch 403 errors (in case API key is down we don't want to blow up)
308
+ errorCodesToCatch: [403],
309
+ });
310
+ if (apiNftContractObject) {
311
+ return apiNftContractObject;
312
+ }
313
+ }
314
+ // If we've reached this point we were unable to fetch data from either the proxy or opensea so we return
315
+ // the default/null of ApiNftContract
316
+ return {
317
+ address: contractAddress,
318
+ asset_contract_type: null,
319
+ created_date: null,
320
+ schema_name: null,
321
+ symbol: null,
322
+ total_supply: null,
323
+ description: null,
324
+ external_link: null,
325
+ collection: {
326
+ name: null,
327
+ image_url: null,
328
+ },
329
+ };
330
+ });
331
+ }
332
+ /**
333
+ * Request NFT contract information from the contract itself.
334
+ *
335
+ * @param contractAddress - Hex address of the NFT contract.
336
+ * @returns Promise resolving to the current NFT name and image.
337
+ */
338
+ getNftContractInformationFromContract(contractAddress) {
339
+ return __awaiter(this, void 0, void 0, function* () {
340
+ const name = yield this.getERC721AssetName(contractAddress);
341
+ const symbol = yield this.getERC721AssetSymbol(contractAddress);
342
+ return {
343
+ collection: { name },
344
+ symbol,
345
+ address: contractAddress,
346
+ };
347
+ });
348
+ }
349
+ /**
350
+ * Request NFT contract information from OpenSea API.
351
+ *
352
+ * @param contractAddress - Hex address of the NFT contract.
353
+ * @returns Promise resolving to the NFT contract name, image and description.
354
+ */
355
+ getNftContractInformation(contractAddress) {
356
+ return __awaiter(this, void 0, void 0, function* () {
357
+ const blockchainContractData = yield (0, controller_utils_1.safelyExecute)(() => __awaiter(this, void 0, void 0, function* () {
358
+ return yield this.getNftContractInformationFromContract(contractAddress);
359
+ }));
360
+ let openSeaContractData;
361
+ if (this.config.openSeaEnabled) {
362
+ openSeaContractData = yield (0, controller_utils_1.safelyExecute)(() => __awaiter(this, void 0, void 0, function* () {
363
+ return yield this.getNftContractInformationFromApi(contractAddress);
364
+ }));
365
+ }
366
+ if (blockchainContractData || openSeaContractData) {
367
+ return Object.assign(Object.assign(Object.assign({}, openSeaContractData), blockchainContractData), { collection: Object.assign(Object.assign({ image_url: null }, openSeaContractData === null || openSeaContractData === void 0 ? void 0 : openSeaContractData.collection), blockchainContractData === null || blockchainContractData === void 0 ? void 0 : blockchainContractData.collection) });
368
+ }
369
+ /* istanbul ignore next */
370
+ return {
371
+ address: contractAddress,
372
+ asset_contract_type: null,
373
+ created_date: null,
374
+ schema_name: null,
375
+ symbol: null,
376
+ total_supply: null,
377
+ description: null,
378
+ external_link: null,
379
+ collection: { name: null, image_url: null },
380
+ };
381
+ });
382
+ }
383
+ /**
384
+ * Adds an individual NFT to the stored NFT list.
385
+ *
386
+ * @param address - Hex address of the NFT contract.
387
+ * @param tokenId - The NFT identifier.
388
+ * @param nftMetadata - NFT optional information (name, image and description).
389
+ * @param nftContract - An object containing contract data of the NFT being added.
390
+ * @param accountParams - The chain ID and address of network and account to which the nftContract should be added.
391
+ * @param source - Whether the NFT was detected, added manually or suggested by a dapp.
392
+ * @returns Promise resolving to the current NFT list.
393
+ */
394
+ addIndividualNft(address, tokenId, nftMetadata, nftContract, accountParams, source = constants_1.Source.Custom) {
395
+ var _a;
396
+ return __awaiter(this, void 0, void 0, function* () {
397
+ // TODO: Remove unused return
398
+ const releaseLock = yield this.mutex.acquire();
399
+ try {
400
+ address = (0, controller_utils_1.toChecksumHexAddress)(address);
401
+ const { allNfts } = this.state;
402
+ let chainId, selectedAddress;
403
+ if (accountParams) {
404
+ chainId = accountParams.chainId;
405
+ selectedAddress = accountParams.userAddress;
406
+ }
407
+ else {
408
+ chainId = this.config.chainId;
409
+ selectedAddress = this.config.selectedAddress;
410
+ }
411
+ const nfts = ((_a = allNfts[selectedAddress]) === null || _a === void 0 ? void 0 : _a[chainId]) || [];
412
+ const existingEntry = nfts.find((nft) => nft.address.toLowerCase() === address.toLowerCase() &&
413
+ nft.tokenId === tokenId);
414
+ if (existingEntry) {
415
+ const differentMetadata = (0, assetsUtil_1.compareNftMetadata)(nftMetadata, existingEntry);
416
+ if (differentMetadata || !existingEntry.isCurrentlyOwned) {
417
+ // TODO: Switch to indexToUpdate
418
+ const indexToRemove = nfts.findIndex((nft) => nft.address.toLowerCase() === address.toLowerCase() &&
419
+ nft.tokenId === tokenId);
420
+ /* istanbul ignore next */
421
+ if (indexToRemove !== -1) {
422
+ nfts.splice(indexToRemove, 1);
423
+ }
424
+ }
425
+ else {
426
+ return nfts;
427
+ }
428
+ }
429
+ const newEntry = Object.assign({ address,
430
+ tokenId, favorite: (existingEntry === null || existingEntry === void 0 ? void 0 : existingEntry.favorite) || false, isCurrentlyOwned: true }, nftMetadata);
431
+ const newNfts = [...nfts, newEntry];
432
+ this.updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY, {
433
+ chainId,
434
+ userAddress: selectedAddress,
435
+ });
436
+ if (this.onNftAdded) {
437
+ this.onNftAdded({
438
+ address,
439
+ symbol: nftContract.symbol,
440
+ tokenId: tokenId.toString(),
441
+ standard: nftMetadata.standard,
442
+ source,
443
+ });
444
+ }
445
+ return newNfts;
446
+ }
447
+ finally {
448
+ releaseLock();
449
+ }
450
+ });
451
+ }
452
+ /**
453
+ * Adds an NFT contract to the stored NFT contracts list.
454
+ *
455
+ * @param address - Hex address of the NFT contract.
456
+ * @param accountParams - The chain ID and address of network and account to which the nftContract should be added.
457
+ * @param source - Whether the NFT was detected, added manually or suggested by a dapp.
458
+ * @returns Promise resolving to the current NFT contracts list.
459
+ */
460
+ addNftContract(address, accountParams, source) {
461
+ var _a;
462
+ return __awaiter(this, void 0, void 0, function* () {
463
+ const releaseLock = yield this.mutex.acquire();
464
+ try {
465
+ address = (0, controller_utils_1.toChecksumHexAddress)(address);
466
+ const { allNftContracts } = this.state;
467
+ let chainId, selectedAddress;
468
+ if (accountParams) {
469
+ chainId = accountParams.chainId;
470
+ selectedAddress = accountParams.userAddress;
471
+ }
472
+ else {
473
+ chainId = this.config.chainId;
474
+ selectedAddress = this.config.selectedAddress;
475
+ }
476
+ const nftContracts = ((_a = allNftContracts[selectedAddress]) === null || _a === void 0 ? void 0 : _a[chainId]) || [];
477
+ const existingEntry = nftContracts.find((nftContract) => nftContract.address.toLowerCase() === address.toLowerCase());
478
+ if (existingEntry) {
479
+ return nftContracts;
480
+ }
481
+ const contractInformation = yield this.getNftContractInformation(address);
482
+ const { asset_contract_type, created_date, schema_name, symbol, total_supply, description, external_link, collection: { name, image_url }, } = contractInformation;
483
+ // If the nft is auto-detected we want some valid metadata to be present
484
+ if (source === constants_1.Source.Detected &&
485
+ Object.entries(contractInformation).every(([k, v]) => {
486
+ if (k === 'address') {
487
+ return true; // address will always be present
488
+ }
489
+ // collection will always be an object, we need to check the internal values
490
+ if (k === 'collection') {
491
+ return (v === null || v === void 0 ? void 0 : v.name) === null && (v === null || v === void 0 ? void 0 : v.image_url) === null;
492
+ }
493
+ return !v;
494
+ })) {
495
+ return nftContracts;
496
+ }
497
+ /* istanbul ignore next */
498
+ const newEntry = Object.assign({}, { address }, description && { description }, name && { name }, image_url && { logo: image_url }, symbol && { symbol }, total_supply !== null &&
499
+ typeof total_supply !== 'undefined' && { totalSupply: total_supply }, asset_contract_type && { assetContractType: asset_contract_type }, created_date && { createdDate: created_date }, schema_name && { schemaName: schema_name }, external_link && { externalLink: external_link });
500
+ const newNftContracts = [...nftContracts, newEntry];
501
+ this.updateNestedNftState(newNftContracts, ALL_NFTS_CONTRACTS_STATE_KEY, {
502
+ chainId,
503
+ userAddress: selectedAddress,
504
+ });
505
+ return newNftContracts;
506
+ }
507
+ finally {
508
+ releaseLock();
509
+ }
510
+ });
511
+ }
512
+ /**
513
+ * Removes an individual NFT from the stored token list and saves it in ignored NFTs list.
514
+ *
515
+ * @param address - Hex address of the NFT contract.
516
+ * @param tokenId - Token identifier of the NFT.
517
+ */
518
+ removeAndIgnoreIndividualNft(address, tokenId) {
519
+ var _a;
520
+ address = (0, controller_utils_1.toChecksumHexAddress)(address);
521
+ const { allNfts, ignoredNfts } = this.state;
522
+ const { chainId, selectedAddress } = this.config;
523
+ const newIgnoredNfts = [...ignoredNfts];
524
+ const nfts = ((_a = allNfts[selectedAddress]) === null || _a === void 0 ? void 0 : _a[chainId]) || [];
525
+ const newNfts = nfts.filter((nft) => {
526
+ if (nft.address.toLowerCase() === address.toLowerCase() &&
527
+ nft.tokenId === tokenId) {
528
+ const alreadyIgnored = newIgnoredNfts.find((c) => c.address === address && c.tokenId === tokenId);
529
+ !alreadyIgnored && newIgnoredNfts.push(nft);
530
+ return false;
531
+ }
532
+ return true;
533
+ });
534
+ this.updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY);
535
+ this.update({
536
+ ignoredNfts: newIgnoredNfts,
537
+ });
538
+ }
539
+ /**
540
+ * Removes an individual NFT from the stored token list.
541
+ *
542
+ * @param address - Hex address of the NFT contract.
543
+ * @param tokenId - Token identifier of the NFT.
544
+ */
545
+ removeIndividualNft(address, tokenId) {
546
+ var _a;
547
+ address = (0, controller_utils_1.toChecksumHexAddress)(address);
548
+ const { allNfts } = this.state;
549
+ const { chainId, selectedAddress } = this.config;
550
+ const nfts = ((_a = allNfts[selectedAddress]) === null || _a === void 0 ? void 0 : _a[chainId]) || [];
551
+ const newNfts = nfts.filter((nft) => !(nft.address.toLowerCase() === address.toLowerCase() &&
552
+ nft.tokenId === tokenId));
553
+ this.updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY);
554
+ }
555
+ /**
556
+ * Removes an NFT contract to the stored NFT contracts list.
557
+ *
558
+ * @param address - Hex address of the NFT contract.
559
+ * @returns Promise resolving to the current NFT contracts list.
560
+ */
561
+ removeNftContract(address) {
562
+ var _a;
563
+ address = (0, controller_utils_1.toChecksumHexAddress)(address);
564
+ const { allNftContracts } = this.state;
565
+ const { chainId, selectedAddress } = this.config;
566
+ const nftContracts = ((_a = allNftContracts[selectedAddress]) === null || _a === void 0 ? void 0 : _a[chainId]) || [];
567
+ const newNftContracts = nftContracts.filter((nftContract) => !(nftContract.address.toLowerCase() === address.toLowerCase()));
568
+ this.updateNestedNftState(newNftContracts, ALL_NFTS_CONTRACTS_STATE_KEY);
569
+ return newNftContracts;
570
+ }
571
+ validateWatchNft(asset, type, accountAddress) {
572
+ return __awaiter(this, void 0, void 0, function* () {
573
+ const { address: contractAddress, tokenId } = asset;
574
+ // Validate parameters
575
+ if (!type) {
576
+ throw rpc_errors_1.rpcErrors.invalidParams('Asset type is required');
577
+ }
578
+ if (type !== controller_utils_1.ERC721 && type !== controller_utils_1.ERC1155) {
579
+ throw rpc_errors_1.rpcErrors.invalidParams(`Non NFT asset type ${type} not supported by watchNft`);
580
+ }
581
+ if (!contractAddress || !tokenId) {
582
+ throw rpc_errors_1.rpcErrors.invalidParams('Both address and tokenId are required');
583
+ }
584
+ if (!(0, address_1.isAddress)(contractAddress)) {
585
+ throw rpc_errors_1.rpcErrors.invalidParams('Invalid address');
586
+ }
587
+ if (!/^\d+$/u.test(tokenId)) {
588
+ throw rpc_errors_1.rpcErrors.invalidParams('Invalid tokenId');
589
+ }
590
+ // Check if the user owns the suggested NFT
591
+ try {
592
+ const isOwner = yield this.isNftOwner(accountAddress, contractAddress, tokenId);
593
+ if (!isOwner) {
594
+ throw rpc_errors_1.rpcErrors.invalidInput('Suggested NFT is not owned by the selected account');
595
+ }
596
+ }
597
+ catch (error) {
598
+ // 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."
599
+ throw rpc_errors_1.rpcErrors.resourceUnavailable(error.message);
600
+ }
601
+ });
602
+ }
603
+ /**
604
+ * Adds a new suggestedAsset to state. Parameters will be validated according to
605
+ * asset type being watched. A `<suggestedNftMeta.id>:pending` hub event will be emitted once added.
606
+ *
607
+ * @param asset - The asset to be watched. For now ERC721 and ERC1155 tokens are accepted.
608
+ * @param asset.address - The address of the asset contract.
609
+ * @param asset.tokenId - The ID of the asset.
610
+ * @param type - The asset type.
611
+ * @param origin - Domain origin to register the asset from.
612
+ * @returns Object containing a Promise resolving to the suggestedAsset address if accepted.
613
+ */
614
+ watchNft(asset, type, origin) {
615
+ return __awaiter(this, void 0, void 0, function* () {
616
+ const { selectedAddress, chainId } = this.config;
617
+ yield this.validateWatchNft(asset, type, selectedAddress);
618
+ const nftMetadata = yield this.getNftInformation(asset.address, asset.tokenId);
619
+ if (nftMetadata.standard && nftMetadata.standard !== type) {
620
+ throw rpc_errors_1.rpcErrors.invalidInput(`Suggested NFT of type ${nftMetadata.standard} does not match received type ${type}`);
621
+ }
622
+ const suggestedNftMeta = {
623
+ asset: Object.assign(Object.assign({}, asset), nftMetadata),
624
+ type,
625
+ id: (0, uuid_1.v4)(),
626
+ time: Date.now(),
627
+ interactingAddress: selectedAddress,
628
+ origin,
629
+ };
630
+ yield this._requestApproval(suggestedNftMeta);
631
+ const { address, tokenId } = asset;
632
+ const { name, standard, description, image } = nftMetadata;
633
+ yield this.addNft(address, tokenId, {
634
+ name: name !== null && name !== void 0 ? name : null,
635
+ description: description !== null && description !== void 0 ? description : null,
636
+ image: image !== null && image !== void 0 ? image : null,
637
+ standard: standard !== null && standard !== void 0 ? standard : null,
638
+ }, {
639
+ chainId,
640
+ userAddress: selectedAddress,
641
+ }, constants_1.Source.Dapp);
642
+ });
643
+ }
644
+ /**
645
+ * Sets an OpenSea API key to retrieve NFT information.
646
+ *
647
+ * @param openSeaApiKey - OpenSea API key.
648
+ */
649
+ setApiKey(openSeaApiKey) {
650
+ this.openSeaApiKey = openSeaApiKey;
651
+ }
652
+ /**
653
+ * Checks the ownership of a ERC-721 or ERC-1155 NFT for a given address.
654
+ *
655
+ * @param ownerAddress - User public address.
656
+ * @param nftAddress - NFT contract address.
657
+ * @param nftId - NFT token ID.
658
+ * @returns Promise resolving the NFT ownership.
659
+ */
660
+ isNftOwner(ownerAddress, nftAddress, nftId) {
661
+ return __awaiter(this, void 0, void 0, function* () {
662
+ // Checks the ownership for ERC-721.
663
+ try {
664
+ const owner = yield this.getERC721OwnerOf(nftAddress, nftId);
665
+ return ownerAddress.toLowerCase() === owner.toLowerCase();
666
+ // eslint-disable-next-line no-empty
667
+ }
668
+ catch (_a) {
669
+ // Ignore ERC-721 contract error
670
+ }
671
+ // Checks the ownership for ERC-1155.
672
+ try {
673
+ const balance = yield this.getERC1155BalanceOf(ownerAddress, nftAddress, nftId);
674
+ return !balance.isZero();
675
+ // eslint-disable-next-line no-empty
676
+ }
677
+ catch (_b) {
678
+ // Ignore ERC-1155 contract error
679
+ }
680
+ throw new Error(`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.`);
681
+ });
682
+ }
683
+ /**
684
+ * Verifies currently selected address owns entered NFT address/tokenId combo and
685
+ * adds the NFT and respective NFT contract to the stored NFT and NFT contracts lists.
686
+ *
687
+ * @param address - Hex address of the NFT contract.
688
+ * @param tokenId - The NFT identifier.
689
+ */
690
+ addNftVerifyOwnership(address, tokenId) {
691
+ return __awaiter(this, void 0, void 0, function* () {
692
+ const { selectedAddress } = this.config;
693
+ if (!(yield this.isNftOwner(selectedAddress, address, tokenId))) {
694
+ throw new Error('This NFT is not owned by the user');
695
+ }
696
+ yield this.addNft(address, tokenId);
697
+ });
698
+ }
699
+ /**
700
+ * Adds an NFT and respective NFT contract to the stored NFT and NFT contracts lists.
701
+ *
702
+ * @param address - Hex address of the NFT contract.
703
+ * @param tokenId - The NFT identifier.
704
+ * @param nftMetadata - NFT optional metadata.
705
+ * @param accountParams - The chain ID and address of network and account to which the nftContract should be added.
706
+ * @param source - Whether the NFT was detected, added manually or suggested by a dapp.
707
+ * @returns Promise resolving to the current NFT list.
708
+ */
709
+ addNft(address, tokenId, nftMetadata, accountParams, source = constants_1.Source.Custom) {
710
+ return __awaiter(this, void 0, void 0, function* () {
711
+ address = (0, controller_utils_1.toChecksumHexAddress)(address);
712
+ const newNftContracts = yield this.addNftContract(address, accountParams, source);
713
+ nftMetadata =
714
+ nftMetadata || (yield this.getNftInformation(address, tokenId));
715
+ // If NFT contract was not added, do not add individual NFT
716
+ const nftContract = newNftContracts.find((contract) => contract.address.toLowerCase() === address.toLowerCase());
717
+ // If NFT contract information, add individual NFT
718
+ if (nftContract) {
719
+ yield this.addIndividualNft(address, tokenId, nftMetadata, nftContract, accountParams, source);
720
+ }
721
+ });
722
+ }
723
+ /**
724
+ * Removes an NFT from the stored token list.
725
+ *
726
+ * @param address - Hex address of the NFT contract.
727
+ * @param tokenId - Token identifier of the NFT.
728
+ */
729
+ removeNft(address, tokenId) {
730
+ var _a;
731
+ address = (0, controller_utils_1.toChecksumHexAddress)(address);
732
+ this.removeIndividualNft(address, tokenId);
733
+ const { allNfts } = this.state;
734
+ const { chainId, selectedAddress } = this.config;
735
+ const nfts = ((_a = allNfts[selectedAddress]) === null || _a === void 0 ? void 0 : _a[chainId]) || [];
736
+ const remainingNft = nfts.find((nft) => nft.address.toLowerCase() === address.toLowerCase());
737
+ if (!remainingNft) {
738
+ this.removeNftContract(address);
739
+ }
740
+ }
741
+ /**
742
+ * Removes an NFT from the stored token list and saves it in ignored NFTs list.
743
+ *
744
+ * @param address - Hex address of the NFT contract.
745
+ * @param tokenId - Token identifier of the NFT.
746
+ */
747
+ removeAndIgnoreNft(address, tokenId) {
748
+ var _a;
749
+ address = (0, controller_utils_1.toChecksumHexAddress)(address);
750
+ this.removeAndIgnoreIndividualNft(address, tokenId);
751
+ const { allNfts } = this.state;
752
+ const { chainId, selectedAddress } = this.config;
753
+ const nfts = ((_a = allNfts[selectedAddress]) === null || _a === void 0 ? void 0 : _a[chainId]) || [];
754
+ const remainingNft = nfts.find((nft) => nft.address.toLowerCase() === address.toLowerCase());
755
+ if (!remainingNft) {
756
+ this.removeNftContract(address);
757
+ }
758
+ }
759
+ /**
760
+ * Removes all NFTs from the ignored list.
761
+ */
762
+ clearIgnoredNfts() {
763
+ this.update({ ignoredNfts: [] });
764
+ }
765
+ /**
766
+ * Checks whether input NFT is still owned by the user
767
+ * And updates the isCurrentlyOwned value on the NFT object accordingly.
768
+ *
769
+ * @param nft - The NFT object to check and update.
770
+ * @param batch - A boolean indicating whether this method is being called as part of a batch or single update.
771
+ * @param accountParams - The userAddress and chainId to check ownership against
772
+ * @param accountParams.userAddress - the address passed through the confirmed transaction flow to ensure assets are stored to the correct account
773
+ * @param accountParams.chainId - the chainId passed through the confirmed transaction flow to ensure assets are stored to the correct account
774
+ * @returns the NFT with the updated isCurrentlyOwned value
775
+ */
776
+ checkAndUpdateSingleNftOwnershipStatus(nft, batch, { userAddress, chainId } = {
777
+ userAddress: this.config.selectedAddress,
778
+ chainId: this.config.chainId,
779
+ }) {
780
+ var _a;
781
+ return __awaiter(this, void 0, void 0, function* () {
782
+ const { address, tokenId } = nft;
783
+ let isOwned = nft.isCurrentlyOwned;
784
+ try {
785
+ isOwned = yield this.isNftOwner(userAddress, address, tokenId);
786
+ }
787
+ catch (error) {
788
+ if (!(error instanceof Error &&
789
+ error.message.includes('Unable to verify ownership'))) {
790
+ throw error;
791
+ }
792
+ }
793
+ nft.isCurrentlyOwned = isOwned;
794
+ if (batch) {
795
+ return nft;
796
+ }
797
+ // if this is not part of a batched update we update this one NFT in state
798
+ const { allNfts } = this.state;
799
+ const nfts = ((_a = allNfts[userAddress]) === null || _a === void 0 ? void 0 : _a[chainId]) || [];
800
+ const nftToUpdate = nfts.find((item) => item.tokenId === tokenId &&
801
+ item.address.toLowerCase() === address.toLowerCase());
802
+ if (nftToUpdate) {
803
+ nftToUpdate.isCurrentlyOwned = isOwned;
804
+ this.updateNestedNftState(nfts, ALL_NFTS_STATE_KEY, {
805
+ userAddress,
806
+ chainId,
807
+ });
808
+ }
809
+ return nft;
810
+ });
811
+ }
812
+ /**
813
+ * Checks whether NFTs associated with current selectedAddress/chainId combination are still owned by the user
814
+ * And updates the isCurrentlyOwned value on each accordingly.
815
+ */
816
+ checkAndUpdateAllNftsOwnershipStatus() {
817
+ var _a;
818
+ return __awaiter(this, void 0, void 0, function* () {
819
+ const { allNfts } = this.state;
820
+ const { chainId, selectedAddress } = this.config;
821
+ const nfts = ((_a = allNfts[selectedAddress]) === null || _a === void 0 ? void 0 : _a[chainId]) || [];
822
+ const updatedNfts = yield Promise.all(nfts.map((nft) => __awaiter(this, void 0, void 0, function* () {
823
+ var _b;
824
+ return ((_b = (yield this.checkAndUpdateSingleNftOwnershipStatus(nft, true))) !== null && _b !== void 0 ? _b : nft);
825
+ })));
826
+ this.updateNestedNftState(updatedNfts, ALL_NFTS_STATE_KEY);
827
+ });
828
+ }
829
+ /**
830
+ * Update NFT favorite status.
831
+ *
832
+ * @param address - Hex address of the NFT contract.
833
+ * @param tokenId - Hex address of the NFT contract.
834
+ * @param favorite - NFT new favorite status.
835
+ */
836
+ updateNftFavoriteStatus(address, tokenId, favorite) {
837
+ var _a;
838
+ const { allNfts } = this.state;
839
+ const { chainId, selectedAddress } = this.config;
840
+ const nfts = ((_a = allNfts[selectedAddress]) === null || _a === void 0 ? void 0 : _a[chainId]) || [];
841
+ const index = nfts.findIndex((nft) => nft.address === address && nft.tokenId === tokenId);
842
+ if (index === -1) {
843
+ return;
844
+ }
845
+ const updatedNft = Object.assign(Object.assign({}, nfts[index]), { favorite });
846
+ // Update Nfts array
847
+ nfts[index] = updatedNft;
848
+ this.updateNestedNftState(nfts, ALL_NFTS_STATE_KEY);
849
+ }
850
+ /**
851
+ * Returns an NFT by the address and token id.
852
+ *
853
+ * @param address - Hex address of the NFT contract.
854
+ * @param tokenId - Number that represents the id of the token.
855
+ * @param selectedAddress - Hex address of the user account.
856
+ * @param chainId - Id of the current network.
857
+ * @returns Object containing the NFT and its position in the array
858
+ */
859
+ findNftByAddressAndTokenId(address, tokenId, selectedAddress, chainId) {
860
+ var _a;
861
+ const { allNfts } = this.state;
862
+ const nfts = ((_a = allNfts[selectedAddress]) === null || _a === void 0 ? void 0 : _a[chainId]) || [];
863
+ const index = nfts.findIndex((nft) => nft.address.toLowerCase() === address.toLowerCase() &&
864
+ nft.tokenId === tokenId);
865
+ if (index === -1) {
866
+ return null;
867
+ }
868
+ return { nft: nfts[index], index };
869
+ }
870
+ /**
871
+ * Update NFT data.
872
+ *
873
+ * @param nft - NFT object to find the right NFT to updates.
874
+ * @param updates - NFT partial object to update properties of the NFT.
875
+ * @param selectedAddress - Hex address of the user account.
876
+ * @param chainId - Id of the current network.
877
+ */
878
+ updateNft(nft, updates, selectedAddress, chainId) {
879
+ var _a;
880
+ const { allNfts } = this.state;
881
+ const nfts = ((_a = allNfts[selectedAddress]) === null || _a === void 0 ? void 0 : _a[chainId]) || [];
882
+ const nftInfo = this.findNftByAddressAndTokenId(nft.address, nft.tokenId, selectedAddress, chainId);
883
+ if (!nftInfo) {
884
+ return;
885
+ }
886
+ const updatedNft = Object.assign(Object.assign({}, nft), updates);
887
+ const newNfts = [
888
+ ...nfts.slice(0, nftInfo.index),
889
+ updatedNft,
890
+ ...nfts.slice(nftInfo.index + 1),
891
+ ];
892
+ this.updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY);
893
+ }
894
+ /**
895
+ * Resets the transaction status of an NFT.
896
+ *
897
+ * @param transactionId - NFT transaction id.
898
+ * @param selectedAddress - Hex address of the user account.
899
+ * @param chainId - Id of the current network.
900
+ * @returns a boolean indicating if the reset was well succeded or not
901
+ */
902
+ resetNftTransactionStatusByTransactionId(transactionId, selectedAddress, chainId) {
903
+ var _a;
904
+ const { allNfts } = this.state;
905
+ const nfts = ((_a = allNfts[selectedAddress]) === null || _a === void 0 ? void 0 : _a[chainId]) || [];
906
+ const index = nfts.findIndex((nft) => nft.transactionId === transactionId);
907
+ if (index === -1) {
908
+ return false;
909
+ }
910
+ const updatedNft = Object.assign(Object.assign({}, nfts[index]), { transactionId: undefined });
911
+ const newNfts = [
912
+ ...nfts.slice(0, index),
913
+ updatedNft,
914
+ ...nfts.slice(index + 1),
915
+ ];
916
+ this.updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY);
917
+ return true;
918
+ }
919
+ _requestApproval(suggestedNftMeta) {
920
+ return __awaiter(this, void 0, void 0, function* () {
921
+ return this.messagingSystem.call('ApprovalController:addRequest', {
922
+ id: suggestedNftMeta.id,
923
+ origin: suggestedNftMeta.origin,
924
+ type: controller_utils_1.ApprovalType.WatchAsset,
925
+ requestData: {
926
+ id: suggestedNftMeta.id,
927
+ interactingAddress: suggestedNftMeta.interactingAddress,
928
+ asset: {
929
+ address: suggestedNftMeta.asset.address,
930
+ tokenId: suggestedNftMeta.asset.tokenId,
931
+ name: suggestedNftMeta.asset.name,
932
+ description: suggestedNftMeta.asset.description,
933
+ image: suggestedNftMeta.asset.image,
934
+ standard: suggestedNftMeta.asset.standard,
935
+ },
936
+ },
937
+ }, true);
938
+ });
939
+ }
940
+ }
941
+ exports.NftController = NftController;
942
+ exports.default = NftController;
943
+ //# sourceMappingURL=NftController.js.map