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