@metamask/assets-controllers 26.0.0 → 27.0.1
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.
- package/CHANGELOG.md +29 -1
- package/dist/AccountTrackerController.js +9 -236
- package/dist/AccountTrackerController.js.map +1 -1
- package/dist/AccountTrackerController.mjs +10 -0
- package/dist/AccountTrackerController.mjs.map +1 -0
- package/dist/AssetsContractController.js +17 -384
- package/dist/AssetsContractController.js.map +1 -1
- package/dist/AssetsContractController.mjs +18 -0
- package/dist/AssetsContractController.mjs.map +1 -0
- package/dist/CurrencyRateController.js +10 -157
- package/dist/CurrencyRateController.js.map +1 -1
- package/dist/CurrencyRateController.mjs +11 -0
- package/dist/CurrencyRateController.mjs.map +1 -0
- package/dist/NftController.js +15 -1041
- package/dist/NftController.js.map +1 -1
- package/dist/NftController.mjs +16 -0
- package/dist/NftController.mjs.map +1 -0
- package/dist/NftDetectionController.js +12 -213
- package/dist/NftDetectionController.js.map +1 -1
- package/dist/NftDetectionController.mjs +13 -0
- package/dist/NftDetectionController.mjs.map +1 -0
- package/dist/Standards/ERC20Standard.js +8 -142
- package/dist/Standards/ERC20Standard.js.map +1 -1
- package/dist/Standards/ERC20Standard.mjs +9 -0
- package/dist/Standards/ERC20Standard.mjs.map +1 -0
- package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js +8 -217
- package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js.map +1 -1
- package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.mjs +9 -0
- package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.mjs.map +1 -0
- package/dist/Standards/NftStandards/ERC721/ERC721Standard.js +8 -174
- package/dist/Standards/NftStandards/ERC721/ERC721Standard.js.map +1 -1
- package/dist/Standards/NftStandards/ERC721/ERC721Standard.mjs +9 -0
- package/dist/Standards/NftStandards/ERC721/ERC721Standard.mjs.map +1 -0
- package/dist/TokenBalancesController.js +11 -141
- package/dist/TokenBalancesController.js.map +1 -1
- package/dist/TokenBalancesController.mjs +12 -0
- package/dist/TokenBalancesController.mjs.map +1 -0
- package/dist/TokenDetectionController.js +16 -362
- package/dist/TokenDetectionController.js.map +1 -1
- package/dist/TokenDetectionController.mjs +17 -0
- package/dist/TokenDetectionController.mjs.map +1 -0
- package/dist/TokenListController.js +13 -250
- package/dist/TokenListController.js.map +1 -1
- package/dist/TokenListController.mjs +14 -0
- package/dist/TokenListController.mjs.map +1 -0
- package/dist/TokenRatesController.js +11 -328
- package/dist/TokenRatesController.js.map +1 -1
- package/dist/TokenRatesController.mjs +12 -0
- package/dist/TokenRatesController.mjs.map +1 -0
- package/dist/TokensController.js +15 -629
- package/dist/TokensController.js.map +1 -1
- package/dist/TokensController.mjs +16 -0
- package/dist/TokensController.mjs.map +1 -0
- package/dist/assetsUtil.js +41 -384
- package/dist/assetsUtil.js.map +1 -1
- package/dist/assetsUtil.mjs +42 -0
- package/dist/assetsUtil.mjs.map +1 -0
- package/dist/chunk-23F5W3A2.mjs +157 -0
- package/dist/chunk-23F5W3A2.mjs.map +1 -0
- package/dist/chunk-27KOXCQK.mjs +1 -0
- package/dist/chunk-27KOXCQK.mjs.map +1 -0
- package/dist/chunk-3FMWI46J.mjs +361 -0
- package/dist/chunk-3FMWI46J.mjs.map +1 -0
- package/dist/chunk-3FOTFZIL.mjs +411 -0
- package/dist/chunk-3FOTFZIL.mjs.map +1 -0
- package/dist/chunk-4LY47RPI.mjs +139 -0
- package/dist/chunk-4LY47RPI.mjs.map +1 -0
- package/dist/chunk-5C7ZVZNM.mjs +267 -0
- package/dist/chunk-5C7ZVZNM.mjs.map +1 -0
- package/dist/chunk-64EHFYLM.mjs +245 -0
- package/dist/chunk-64EHFYLM.mjs.map +1 -0
- package/dist/chunk-6C2ZIK7A.js +245 -0
- package/dist/chunk-6C2ZIK7A.js.map +1 -0
- package/dist/chunk-6DTCHPBB.mjs +178 -0
- package/dist/chunk-6DTCHPBB.mjs.map +1 -0
- package/dist/chunk-74IP34EL.js +1177 -0
- package/dist/chunk-74IP34EL.js.map +1 -0
- package/dist/chunk-BZI7P3TD.js +115 -0
- package/dist/chunk-BZI7P3TD.js.map +1 -0
- package/dist/chunk-C4PQK53K.js +32 -0
- package/dist/chunk-C4PQK53K.js.map +1 -0
- package/dist/chunk-CP3HC7AQ.mjs +12 -0
- package/dist/chunk-CP3HC7AQ.mjs.map +1 -0
- package/dist/chunk-GHZX5DE4.js +215 -0
- package/dist/chunk-GHZX5DE4.js.map +1 -0
- package/dist/chunk-GMKIOYCB.js +361 -0
- package/dist/chunk-GMKIOYCB.js.map +1 -0
- package/dist/chunk-H6TOSWUM.js +157 -0
- package/dist/chunk-H6TOSWUM.js.map +1 -0
- package/dist/chunk-HWFBJFHS.js +284 -0
- package/dist/chunk-HWFBJFHS.js.map +1 -0
- package/dist/chunk-J2JQQNHN.mjs +115 -0
- package/dist/chunk-J2JQQNHN.mjs.map +1 -0
- package/dist/chunk-J6HPEQL3.mjs +704 -0
- package/dist/chunk-J6HPEQL3.mjs.map +1 -0
- package/dist/chunk-JC4WAN2J.mjs +1177 -0
- package/dist/chunk-JC4WAN2J.mjs.map +1 -0
- package/dist/chunk-LD4GC7OR.js +139 -0
- package/dist/chunk-LD4GC7OR.js.map +1 -0
- package/dist/chunk-NG2UOKDD.js +178 -0
- package/dist/chunk-NG2UOKDD.js.map +1 -0
- package/dist/chunk-NGIXA5M5.mjs +418 -0
- package/dist/chunk-NGIXA5M5.mjs.map +1 -0
- package/dist/chunk-NLNXQHAU.js +704 -0
- package/dist/chunk-NLNXQHAU.js.map +1 -0
- package/dist/chunk-OBUR4TXH.js +1 -0
- package/dist/chunk-OBUR4TXH.js.map +1 -0
- package/dist/chunk-PAJTKWEC.mjs +246 -0
- package/dist/chunk-PAJTKWEC.mjs.map +1 -0
- package/dist/chunk-PRIXT2R6.js +411 -0
- package/dist/chunk-PRIXT2R6.js.map +1 -0
- package/dist/chunk-PUFSYRJZ.js +74 -0
- package/dist/chunk-PUFSYRJZ.js.map +1 -0
- package/dist/chunk-QHRPRO5U.mjs +74 -0
- package/dist/chunk-QHRPRO5U.mjs.map +1 -0
- package/dist/chunk-QR4CX2JT.mjs +284 -0
- package/dist/chunk-QR4CX2JT.mjs.map +1 -0
- package/dist/chunk-RGHTNZQ6.js +12 -0
- package/dist/chunk-RGHTNZQ6.js.map +1 -0
- package/dist/chunk-TCO22VIO.mjs +32 -0
- package/dist/chunk-TCO22VIO.mjs.map +1 -0
- package/dist/chunk-TDKCVCGP.mjs +215 -0
- package/dist/chunk-TDKCVCGP.mjs.map +1 -0
- package/dist/chunk-UAH5YURZ.js +343 -0
- package/dist/chunk-UAH5YURZ.js.map +1 -0
- package/dist/chunk-V4ZO3F2S.js +246 -0
- package/dist/chunk-V4ZO3F2S.js.map +1 -0
- package/dist/chunk-VDJBJAUB.js +418 -0
- package/dist/chunk-VDJBJAUB.js.map +1 -0
- package/dist/chunk-WRQ7POD7.mjs +343 -0
- package/dist/chunk-WRQ7POD7.mjs.map +1 -0
- package/dist/chunk-XUI43LEZ.mjs +30 -0
- package/dist/chunk-XUI43LEZ.mjs.map +1 -0
- package/dist/chunk-YD3NRMFC.js +267 -0
- package/dist/chunk-YD3NRMFC.js.map +1 -0
- package/dist/chunk-Z4BLTVTB.js +30 -0
- package/dist/chunk-Z4BLTVTB.js.map +1 -0
- package/dist/constants.js +7 -9
- package/dist/constants.js.map +1 -1
- package/dist/constants.mjs +8 -0
- package/dist/constants.mjs.map +1 -0
- package/dist/crypto-compare.js +7 -66
- package/dist/crypto-compare.js.map +1 -1
- package/dist/crypto-compare.mjs +8 -0
- package/dist/crypto-compare.mjs.map +1 -0
- package/dist/index.js +72 -39
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +73 -0
- package/dist/index.mjs.map +1 -0
- package/dist/token-prices-service/abstract-token-prices-service.js +1 -3
- package/dist/token-prices-service/abstract-token-prices-service.js.map +1 -1
- package/dist/token-prices-service/abstract-token-prices-service.mjs +1 -0
- package/dist/token-prices-service/abstract-token-prices-service.mjs.map +1 -0
- package/dist/token-prices-service/codefi-v2.js +11 -353
- package/dist/token-prices-service/codefi-v2.js.map +1 -1
- package/dist/token-prices-service/codefi-v2.mjs +12 -0
- package/dist/token-prices-service/codefi-v2.mjs.map +1 -0
- package/dist/token-prices-service/index.js +8 -5
- package/dist/token-prices-service/index.js.map +1 -1
- package/dist/token-prices-service/index.mjs +9 -0
- package/dist/token-prices-service/index.mjs.map +1 -0
- package/dist/token-service.js +14 -133
- package/dist/token-service.js.map +1 -1
- package/dist/token-service.mjs +15 -0
- package/dist/token-service.mjs.map +1 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -0
- package/dist/types/AccountTrackerController.d.ts.map +1 -0
- package/dist/types/AssetsContractController.d.ts.map +1 -0
- package/dist/types/CurrencyRateController.d.ts.map +1 -0
- package/dist/types/NftController.d.ts.map +1 -0
- package/dist/types/NftDetectionController.d.ts.map +1 -0
- package/dist/types/Standards/ERC20Standard.d.ts.map +1 -0
- package/dist/types/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts.map +1 -0
- package/dist/types/Standards/NftStandards/ERC721/ERC721Standard.d.ts.map +1 -0
- package/dist/types/TokenBalancesController.d.ts.map +1 -0
- package/dist/types/TokenDetectionController.d.ts.map +1 -0
- package/dist/types/TokenListController.d.ts.map +1 -0
- package/dist/types/TokenRatesController.d.ts.map +1 -0
- package/dist/{TokensController.d.ts → types/TokensController.d.ts} +10 -3
- package/dist/types/TokensController.d.ts.map +1 -0
- package/dist/types/assetsUtil.d.ts.map +1 -0
- package/dist/types/constants.d.ts.map +1 -0
- package/dist/types/crypto-compare.d.ts.map +1 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/token-prices-service/abstract-token-prices-service.d.ts.map +1 -0
- package/dist/types/token-prices-service/codefi-v2.d.ts.map +1 -0
- package/dist/types/token-prices-service/index.d.ts.map +1 -0
- package/dist/types/token-service.d.ts.map +1 -0
- package/package.json +25 -15
- package/dist/AccountTrackerController.d.ts.map +0 -1
- package/dist/AssetsContractController.d.ts.map +0 -1
- package/dist/CurrencyRateController.d.ts.map +0 -1
- package/dist/NftController.d.ts.map +0 -1
- package/dist/NftDetectionController.d.ts.map +0 -1
- package/dist/Standards/ERC20Standard.d.ts.map +0 -1
- package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts.map +0 -1
- package/dist/Standards/NftStandards/ERC721/ERC721Standard.d.ts.map +0 -1
- package/dist/TokenBalancesController.d.ts.map +0 -1
- package/dist/TokenDetectionController.d.ts.map +0 -1
- package/dist/TokenListController.d.ts.map +0 -1
- package/dist/TokenRatesController.d.ts.map +0 -1
- package/dist/TokensController.d.ts.map +0 -1
- package/dist/assetsUtil.d.ts.map +0 -1
- package/dist/constants.d.ts.map +0 -1
- package/dist/crypto-compare.d.ts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/token-prices-service/abstract-token-prices-service.d.ts.map +0 -1
- package/dist/token-prices-service/codefi-v2.d.ts.map +0 -1
- package/dist/token-prices-service/index.d.ts.map +0 -1
- package/dist/token-service.d.ts.map +0 -1
- /package/dist/{AccountTrackerController.d.ts → types/AccountTrackerController.d.ts} +0 -0
- /package/dist/{AssetsContractController.d.ts → types/AssetsContractController.d.ts} +0 -0
- /package/dist/{CurrencyRateController.d.ts → types/CurrencyRateController.d.ts} +0 -0
- /package/dist/{NftController.d.ts → types/NftController.d.ts} +0 -0
- /package/dist/{NftDetectionController.d.ts → types/NftDetectionController.d.ts} +0 -0
- /package/dist/{Standards → types/Standards}/ERC20Standard.d.ts +0 -0
- /package/dist/{Standards → types/Standards}/NftStandards/ERC1155/ERC1155Standard.d.ts +0 -0
- /package/dist/{Standards → types/Standards}/NftStandards/ERC721/ERC721Standard.d.ts +0 -0
- /package/dist/{TokenBalancesController.d.ts → types/TokenBalancesController.d.ts} +0 -0
- /package/dist/{TokenDetectionController.d.ts → types/TokenDetectionController.d.ts} +0 -0
- /package/dist/{TokenListController.d.ts → types/TokenListController.d.ts} +0 -0
- /package/dist/{TokenRatesController.d.ts → types/TokenRatesController.d.ts} +0 -0
- /package/dist/{assetsUtil.d.ts → types/assetsUtil.d.ts} +0 -0
- /package/dist/{constants.d.ts → types/constants.d.ts} +0 -0
- /package/dist/{crypto-compare.d.ts → types/crypto-compare.d.ts} +0 -0
- /package/dist/{index.d.ts → types/index.d.ts} +0 -0
- /package/dist/{token-prices-service → types/token-prices-service}/abstract-token-prices-service.d.ts +0 -0
- /package/dist/{token-prices-service → types/token-prices-service}/codefi-v2.d.ts +0 -0
- /package/dist/{token-prices-service → types/token-prices-service}/index.d.ts +0 -0
- /package/dist/{token-service.d.ts → types/token-service.d.ts} +0 -0
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
// src/assetsUtil.ts
|
|
2
|
+
import {
|
|
3
|
+
convertHexToDecimal,
|
|
4
|
+
toChecksumHexAddress
|
|
5
|
+
} from "@metamask/controller-utils";
|
|
6
|
+
import { remove0x } from "@metamask/utils";
|
|
7
|
+
import BN from "bn.js";
|
|
8
|
+
import { CID } from "multiformats/cid";
|
|
9
|
+
var TOKEN_PRICES_BATCH_SIZE = 30;
|
|
10
|
+
function compareNftMetadata(newNftMetadata, nft) {
|
|
11
|
+
const keys = [
|
|
12
|
+
"image",
|
|
13
|
+
"backgroundColor",
|
|
14
|
+
"imagePreview",
|
|
15
|
+
"imageThumbnail",
|
|
16
|
+
"imageOriginal",
|
|
17
|
+
"animation",
|
|
18
|
+
"animationOriginal",
|
|
19
|
+
"externalLink"
|
|
20
|
+
];
|
|
21
|
+
const differentValues = keys.reduce((value, key) => {
|
|
22
|
+
if (newNftMetadata[key] && newNftMetadata[key] !== nft[key]) {
|
|
23
|
+
return value + 1;
|
|
24
|
+
}
|
|
25
|
+
return value;
|
|
26
|
+
}, 0);
|
|
27
|
+
return differentValues > 0;
|
|
28
|
+
}
|
|
29
|
+
var aggregatorNameByKey = {
|
|
30
|
+
aave: "Aave",
|
|
31
|
+
bancor: "Bancor",
|
|
32
|
+
cmc: "CMC",
|
|
33
|
+
cryptocom: "Crypto.com",
|
|
34
|
+
coinGecko: "CoinGecko",
|
|
35
|
+
oneInch: "1inch",
|
|
36
|
+
paraswap: "Paraswap",
|
|
37
|
+
pmm: "PMM",
|
|
38
|
+
zapper: "Zapper",
|
|
39
|
+
zerion: "Zerion",
|
|
40
|
+
zeroEx: "0x",
|
|
41
|
+
synthetix: "Synthetix",
|
|
42
|
+
yearn: "Yearn",
|
|
43
|
+
apeswap: "ApeSwap",
|
|
44
|
+
binanceDex: "BinanceDex",
|
|
45
|
+
pancakeTop100: "PancakeTop100",
|
|
46
|
+
pancakeExtended: "PancakeExtended",
|
|
47
|
+
balancer: "Balancer",
|
|
48
|
+
quickswap: "QuickSwap",
|
|
49
|
+
matcha: "Matcha",
|
|
50
|
+
pangolinDex: "PangolinDex",
|
|
51
|
+
pangolinDexStableCoin: "PangolinDexStableCoin",
|
|
52
|
+
pangolinDexAvaxBridge: "PangolinDexAvaxBridge",
|
|
53
|
+
traderJoe: "TraderJoe",
|
|
54
|
+
airswapLight: "AirswapLight",
|
|
55
|
+
kleros: "Kleros"
|
|
56
|
+
};
|
|
57
|
+
var formatAggregatorNames = (aggregators) => {
|
|
58
|
+
return aggregators.map(
|
|
59
|
+
(key) => aggregatorNameByKey[key] || `${key[0].toUpperCase()}${key.substring(1, key.length)}`
|
|
60
|
+
);
|
|
61
|
+
};
|
|
62
|
+
var formatIconUrlWithProxy = ({
|
|
63
|
+
chainId,
|
|
64
|
+
tokenAddress
|
|
65
|
+
}) => {
|
|
66
|
+
const chainIdDecimal = convertHexToDecimal(chainId).toString();
|
|
67
|
+
return `https://static.metafi.codefi.network/api/v1/tokenIcons/${chainIdDecimal}/${tokenAddress.toLowerCase()}.png`;
|
|
68
|
+
};
|
|
69
|
+
var SupportedTokenDetectionNetworks = /* @__PURE__ */ ((SupportedTokenDetectionNetworks2) => {
|
|
70
|
+
SupportedTokenDetectionNetworks2["mainnet"] = "0x1";
|
|
71
|
+
SupportedTokenDetectionNetworks2["bsc"] = "0x38";
|
|
72
|
+
SupportedTokenDetectionNetworks2["polygon"] = "0x89";
|
|
73
|
+
SupportedTokenDetectionNetworks2["avax"] = "0xa86a";
|
|
74
|
+
SupportedTokenDetectionNetworks2["aurora"] = "0x4e454152";
|
|
75
|
+
SupportedTokenDetectionNetworks2["linea_goerli"] = "0xe704";
|
|
76
|
+
SupportedTokenDetectionNetworks2["linea_mainnet"] = "0xe708";
|
|
77
|
+
SupportedTokenDetectionNetworks2["arbitrum"] = "0xa4b1";
|
|
78
|
+
SupportedTokenDetectionNetworks2["optimism"] = "0xa";
|
|
79
|
+
SupportedTokenDetectionNetworks2["base"] = "0x2105";
|
|
80
|
+
SupportedTokenDetectionNetworks2["zksync"] = "0x144";
|
|
81
|
+
return SupportedTokenDetectionNetworks2;
|
|
82
|
+
})(SupportedTokenDetectionNetworks || {});
|
|
83
|
+
function isTokenDetectionSupportedForNetwork(chainId) {
|
|
84
|
+
return Object.values(SupportedTokenDetectionNetworks).includes(chainId);
|
|
85
|
+
}
|
|
86
|
+
function isTokenListSupportedForNetwork(chainId) {
|
|
87
|
+
return isTokenDetectionSupportedForNetwork(chainId);
|
|
88
|
+
}
|
|
89
|
+
function removeIpfsProtocolPrefix(ipfsUrl) {
|
|
90
|
+
if (ipfsUrl.startsWith("ipfs://ipfs/")) {
|
|
91
|
+
return ipfsUrl.replace("ipfs://ipfs/", "");
|
|
92
|
+
} else if (ipfsUrl.startsWith("ipfs://")) {
|
|
93
|
+
return ipfsUrl.replace("ipfs://", "");
|
|
94
|
+
}
|
|
95
|
+
throw new Error("this method should not be used with non ipfs urls");
|
|
96
|
+
}
|
|
97
|
+
function getIpfsCIDv1AndPath(ipfsUrl) {
|
|
98
|
+
const url = removeIpfsProtocolPrefix(ipfsUrl);
|
|
99
|
+
const index = url.indexOf("/");
|
|
100
|
+
const cid = index !== -1 ? url.substring(0, index) : url;
|
|
101
|
+
const path = index !== -1 ? url.substring(index) : void 0;
|
|
102
|
+
return {
|
|
103
|
+
cid: CID.parse(cid).toV1().toString(),
|
|
104
|
+
path
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
function getFormattedIpfsUrl(ipfsGateway, ipfsUrl, subdomainSupported) {
|
|
108
|
+
const { host, protocol, origin } = new URL(addUrlProtocolPrefix(ipfsGateway));
|
|
109
|
+
if (subdomainSupported) {
|
|
110
|
+
const { cid, path } = getIpfsCIDv1AndPath(ipfsUrl);
|
|
111
|
+
return `${protocol}//${cid}.ipfs.${host}${path ?? ""}`;
|
|
112
|
+
}
|
|
113
|
+
const cidAndPath = removeIpfsProtocolPrefix(ipfsUrl);
|
|
114
|
+
return `${origin}/ipfs/${cidAndPath}`;
|
|
115
|
+
}
|
|
116
|
+
function addUrlProtocolPrefix(urlString) {
|
|
117
|
+
if (!urlString.match(/(^http:\/\/)|(^https:\/\/)/u)) {
|
|
118
|
+
return `https://${urlString}`;
|
|
119
|
+
}
|
|
120
|
+
return urlString;
|
|
121
|
+
}
|
|
122
|
+
function ethersBigNumberToBN(bigNumber) {
|
|
123
|
+
return new BN(remove0x(bigNumber.toHexString()), "hex");
|
|
124
|
+
}
|
|
125
|
+
function divideIntoBatches(values, { batchSize }) {
|
|
126
|
+
const batches = [];
|
|
127
|
+
for (let i = 0; i < values.length; i += batchSize) {
|
|
128
|
+
batches.push(values.slice(i, i + batchSize));
|
|
129
|
+
}
|
|
130
|
+
return batches;
|
|
131
|
+
}
|
|
132
|
+
async function reduceInBatchesSerially({
|
|
133
|
+
values,
|
|
134
|
+
batchSize,
|
|
135
|
+
eachBatch,
|
|
136
|
+
initialResult
|
|
137
|
+
}) {
|
|
138
|
+
const batches = divideIntoBatches(values, { batchSize });
|
|
139
|
+
let workingResult = initialResult;
|
|
140
|
+
for (const [index, batch] of batches.entries()) {
|
|
141
|
+
workingResult = await eachBatch(workingResult, batch, index);
|
|
142
|
+
}
|
|
143
|
+
const finalResult = workingResult;
|
|
144
|
+
return finalResult;
|
|
145
|
+
}
|
|
146
|
+
function mapOpenSeaNftV2ToV1(nft) {
|
|
147
|
+
return {
|
|
148
|
+
token_id: nft.identifier,
|
|
149
|
+
num_sales: null,
|
|
150
|
+
background_color: null,
|
|
151
|
+
image_url: nft.image_url ?? null,
|
|
152
|
+
image_preview_url: null,
|
|
153
|
+
image_thumbnail_url: null,
|
|
154
|
+
image_original_url: null,
|
|
155
|
+
animation_url: null,
|
|
156
|
+
animation_original_url: null,
|
|
157
|
+
name: nft.name,
|
|
158
|
+
description: nft.description,
|
|
159
|
+
external_link: null,
|
|
160
|
+
asset_contract: {
|
|
161
|
+
address: nft.contract,
|
|
162
|
+
asset_contract_type: null,
|
|
163
|
+
created_date: null,
|
|
164
|
+
schema_name: nft.token_standard.toUpperCase(),
|
|
165
|
+
symbol: null,
|
|
166
|
+
total_supply: null,
|
|
167
|
+
description: nft.description,
|
|
168
|
+
external_link: null,
|
|
169
|
+
collection: {
|
|
170
|
+
name: nft.collection,
|
|
171
|
+
image_url: null
|
|
172
|
+
}
|
|
173
|
+
},
|
|
174
|
+
creator: {
|
|
175
|
+
user: { username: "" },
|
|
176
|
+
profile_img_url: "",
|
|
177
|
+
address: ""
|
|
178
|
+
},
|
|
179
|
+
last_sale: null
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
function mapOpenSeaDetailedNftV2ToV1(nft) {
|
|
183
|
+
const mapped = mapOpenSeaNftV2ToV1(nft);
|
|
184
|
+
return {
|
|
185
|
+
...mapped,
|
|
186
|
+
animation_url: nft.animation_url ?? null,
|
|
187
|
+
creator: {
|
|
188
|
+
...mapped.creator,
|
|
189
|
+
address: nft.creator
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
function mapOpenSeaContractV2ToV1(contract, collection) {
|
|
194
|
+
return {
|
|
195
|
+
address: contract.address,
|
|
196
|
+
asset_contract_type: null,
|
|
197
|
+
created_date: null,
|
|
198
|
+
schema_name: contract.contract_standard.toUpperCase(),
|
|
199
|
+
symbol: null,
|
|
200
|
+
total_supply: collection?.total_supply?.toString() ?? contract.total_supply?.toString() ?? null,
|
|
201
|
+
description: collection?.description ?? null,
|
|
202
|
+
external_link: collection?.project_url ?? null,
|
|
203
|
+
collection: {
|
|
204
|
+
name: collection?.name ?? contract.name,
|
|
205
|
+
image_url: collection?.image_url
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
async function fetchTokenContractExchangeRates({
|
|
210
|
+
tokenPricesService,
|
|
211
|
+
nativeCurrency,
|
|
212
|
+
tokenAddresses,
|
|
213
|
+
chainId
|
|
214
|
+
}) {
|
|
215
|
+
const isChainIdSupported = tokenPricesService.validateChainIdSupported(chainId);
|
|
216
|
+
const isCurrencySupported = tokenPricesService.validateCurrencySupported(nativeCurrency);
|
|
217
|
+
if (!isChainIdSupported || !isCurrencySupported) {
|
|
218
|
+
return {};
|
|
219
|
+
}
|
|
220
|
+
const tokenPricesByTokenAddress = await reduceInBatchesSerially({
|
|
221
|
+
values: [...tokenAddresses].sort(),
|
|
222
|
+
batchSize: TOKEN_PRICES_BATCH_SIZE,
|
|
223
|
+
eachBatch: async (allTokenPricesByTokenAddress, batch) => {
|
|
224
|
+
const tokenPricesByTokenAddressForBatch = await tokenPricesService.fetchTokenPrices({
|
|
225
|
+
tokenAddresses: batch,
|
|
226
|
+
chainId,
|
|
227
|
+
currency: nativeCurrency
|
|
228
|
+
});
|
|
229
|
+
return {
|
|
230
|
+
...allTokenPricesByTokenAddress,
|
|
231
|
+
...tokenPricesByTokenAddressForBatch
|
|
232
|
+
};
|
|
233
|
+
},
|
|
234
|
+
initialResult: {}
|
|
235
|
+
});
|
|
236
|
+
return Object.entries(tokenPricesByTokenAddress).reduce(
|
|
237
|
+
(obj, [tokenAddress, tokenPrice]) => {
|
|
238
|
+
return {
|
|
239
|
+
...obj,
|
|
240
|
+
[toChecksumHexAddress(tokenAddress)]: tokenPrice?.value
|
|
241
|
+
};
|
|
242
|
+
},
|
|
243
|
+
{}
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export {
|
|
248
|
+
TOKEN_PRICES_BATCH_SIZE,
|
|
249
|
+
compareNftMetadata,
|
|
250
|
+
formatAggregatorNames,
|
|
251
|
+
formatIconUrlWithProxy,
|
|
252
|
+
SupportedTokenDetectionNetworks,
|
|
253
|
+
isTokenDetectionSupportedForNetwork,
|
|
254
|
+
isTokenListSupportedForNetwork,
|
|
255
|
+
removeIpfsProtocolPrefix,
|
|
256
|
+
getIpfsCIDv1AndPath,
|
|
257
|
+
getFormattedIpfsUrl,
|
|
258
|
+
addUrlProtocolPrefix,
|
|
259
|
+
ethersBigNumberToBN,
|
|
260
|
+
divideIntoBatches,
|
|
261
|
+
reduceInBatchesSerially,
|
|
262
|
+
mapOpenSeaNftV2ToV1,
|
|
263
|
+
mapOpenSeaDetailedNftV2ToV1,
|
|
264
|
+
mapOpenSeaContractV2ToV1,
|
|
265
|
+
fetchTokenContractExchangeRates
|
|
266
|
+
};
|
|
267
|
+
//# sourceMappingURL=chunk-5C7ZVZNM.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/assetsUtil.ts"],"sourcesContent":["import type { BigNumber } from '@ethersproject/bignumber';\nimport {\n convertHexToDecimal,\n toChecksumHexAddress,\n} from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\nimport { remove0x } from '@metamask/utils';\nimport BN from 'bn.js';\nimport { CID } from 'multiformats/cid';\n\nimport type {\n Nft,\n NftMetadata,\n OpenSeaV2Collection,\n OpenSeaV2Contract,\n OpenSeaV2DetailedNft,\n OpenSeaV2Nft,\n} from './NftController';\nimport type { ApiNft, ApiNftContract } from './NftDetectionController';\nimport type { AbstractTokenPricesService } from './token-prices-service';\nimport { type ContractExchangeRates } from './TokenRatesController';\n\n/**\n * The maximum number of token addresses that should be sent to the Price API in\n * a single request.\n */\nexport const TOKEN_PRICES_BATCH_SIZE = 30;\n\n/**\n * Compares nft metadata entries to any nft entry.\n * We need this method when comparing a new fetched nft metadata, in case a entry changed to a defined value,\n * there's a need to update the nft in state.\n *\n * @param newNftMetadata - Nft metadata object.\n * @param nft - Nft object to compare with.\n * @returns Whether there are differences.\n */\nexport function compareNftMetadata(newNftMetadata: NftMetadata, nft: Nft) {\n const keys: (keyof NftMetadata)[] = [\n 'image',\n 'backgroundColor',\n 'imagePreview',\n 'imageThumbnail',\n 'imageOriginal',\n 'animation',\n 'animationOriginal',\n 'externalLink',\n ];\n const differentValues = keys.reduce((value, key) => {\n if (newNftMetadata[key] && newNftMetadata[key] !== nft[key]) {\n return value + 1;\n }\n return value;\n }, 0);\n return differentValues > 0;\n}\n\nconst aggregatorNameByKey: Record<string, string> = {\n aave: 'Aave',\n bancor: 'Bancor',\n cmc: 'CMC',\n cryptocom: 'Crypto.com',\n coinGecko: 'CoinGecko',\n oneInch: '1inch',\n paraswap: 'Paraswap',\n pmm: 'PMM',\n zapper: 'Zapper',\n zerion: 'Zerion',\n zeroEx: '0x',\n synthetix: 'Synthetix',\n yearn: 'Yearn',\n apeswap: 'ApeSwap',\n binanceDex: 'BinanceDex',\n pancakeTop100: 'PancakeTop100',\n pancakeExtended: 'PancakeExtended',\n balancer: 'Balancer',\n quickswap: 'QuickSwap',\n matcha: 'Matcha',\n pangolinDex: 'PangolinDex',\n pangolinDexStableCoin: 'PangolinDexStableCoin',\n pangolinDexAvaxBridge: 'PangolinDexAvaxBridge',\n traderJoe: 'TraderJoe',\n airswapLight: 'AirswapLight',\n kleros: 'Kleros',\n};\n\n/**\n * Formats aggregator names to presentable format.\n *\n * @param aggregators - List of token list names in camelcase.\n * @returns Formatted aggregator names.\n */\nexport const formatAggregatorNames = (aggregators: string[]) => {\n return aggregators.map(\n (key) =>\n aggregatorNameByKey[key] ||\n `${key[0].toUpperCase()}${key.substring(1, key.length)}`,\n );\n};\n\n/**\n * Format token list assets to use image proxy from Codefi.\n *\n * @param params - Object that contains chainID and tokenAddress.\n * @param params.chainId - ChainID of network in 0x-prefixed hexadecimal format.\n * @param params.tokenAddress - Address of token in mixed or lowercase.\n * @returns Formatted image url\n */\nexport const formatIconUrlWithProxy = ({\n chainId,\n tokenAddress,\n}: {\n chainId: Hex;\n tokenAddress: string;\n}) => {\n const chainIdDecimal = convertHexToDecimal(chainId).toString();\n return `https://static.metafi.codefi.network/api/v1/tokenIcons/${chainIdDecimal}/${tokenAddress.toLowerCase()}.png`;\n};\n\n/**\n * Networks where token detection is supported - Values are in decimal format\n */\nexport enum SupportedTokenDetectionNetworks {\n mainnet = '0x1', // decimal: 1\n bsc = '0x38', // decimal: 56\n polygon = '0x89', // decimal: 137\n avax = '0xa86a', // decimal: 43114\n aurora = '0x4e454152', // decimal: 1313161554\n linea_goerli = '0xe704', // decimal: 59140\n linea_mainnet = '0xe708', // decimal: 59144\n arbitrum = '0xa4b1', // decimal: 42161\n optimism = '0xa', // decimal: 10\n base = '0x2105', // decimal: 8453\n zksync = '0x144', // decimal: 324\n}\n\n/**\n * Check if token detection is enabled for certain networks.\n *\n * @param chainId - ChainID of network\n * @returns Whether the current network supports token detection\n */\nexport function isTokenDetectionSupportedForNetwork(chainId: Hex): boolean {\n return Object.values<Hex>(SupportedTokenDetectionNetworks).includes(chainId);\n}\n\n/**\n * Check if token list polling is enabled for a given network.\n * Currently this method is used to support e2e testing for consumers of this package.\n *\n * @param chainId - ChainID of network\n * @returns Whether the current network supports tokenlists\n */\nexport function isTokenListSupportedForNetwork(chainId: Hex): boolean {\n return isTokenDetectionSupportedForNetwork(chainId);\n}\n\n/**\n * Removes IPFS protocol prefix from input string.\n *\n * @param ipfsUrl - An IPFS url (e.g. ipfs://{content id})\n * @returns IPFS content identifier and (possibly) path in a string\n * @throws Will throw if the url passed is not IPFS.\n */\nexport function removeIpfsProtocolPrefix(ipfsUrl: string) {\n if (ipfsUrl.startsWith('ipfs://ipfs/')) {\n return ipfsUrl.replace('ipfs://ipfs/', '');\n } else if (ipfsUrl.startsWith('ipfs://')) {\n return ipfsUrl.replace('ipfs://', '');\n }\n // this method should not be used with non-ipfs urls (i.e. startsWith('ipfs://') === true)\n throw new Error('this method should not be used with non ipfs urls');\n}\n\n/**\n * Extracts content identifier and path from an input string.\n *\n * @param ipfsUrl - An IPFS URL minus the IPFS protocol prefix\n * @returns IFPS content identifier (cid) and sub path as string.\n * @throws Will throw if the url passed is not ipfs.\n */\nexport function getIpfsCIDv1AndPath(ipfsUrl: string): {\n cid: string;\n path?: string;\n} {\n const url = removeIpfsProtocolPrefix(ipfsUrl);\n\n // check if there is a path\n // (CID is everything preceding first forward slash, path is everything after)\n const index = url.indexOf('/');\n const cid = index !== -1 ? url.substring(0, index) : url;\n const path = index !== -1 ? url.substring(index) : undefined;\n\n // We want to ensure that the CID is v1 (https://docs.ipfs.io/concepts/content-addressing/#identifier-formats)\n // because most cid v0s appear to be incompatible with IPFS subdomains\n return {\n cid: CID.parse(cid).toV1().toString(),\n path,\n };\n}\n\n/**\n * Formats URL correctly for use retrieving assets hosted on IPFS.\n *\n * @param ipfsGateway - The users preferred IPFS gateway (full URL or just host).\n * @param ipfsUrl - The IFPS URL pointed at the asset.\n * @param subdomainSupported - Boolean indicating whether the URL should be formatted with subdomains or not.\n * @returns A formatted URL, with the user's preferred IPFS gateway and format (subdomain or not), pointing to an asset hosted on IPFS.\n */\nexport function getFormattedIpfsUrl(\n ipfsGateway: string,\n ipfsUrl: string,\n subdomainSupported: boolean,\n): string {\n const { host, protocol, origin } = new URL(addUrlProtocolPrefix(ipfsGateway));\n if (subdomainSupported) {\n const { cid, path } = getIpfsCIDv1AndPath(ipfsUrl);\n return `${protocol}//${cid}.ipfs.${host}${path ?? ''}`;\n }\n const cidAndPath = removeIpfsProtocolPrefix(ipfsUrl);\n return `${origin}/ipfs/${cidAndPath}`;\n}\n\n/**\n * Adds URL protocol prefix to input URL string if missing.\n *\n * @param urlString - An IPFS URL.\n * @returns A URL with a https:// prepended.\n */\nexport function addUrlProtocolPrefix(urlString: string): string {\n if (!urlString.match(/(^http:\\/\\/)|(^https:\\/\\/)/u)) {\n return `https://${urlString}`;\n }\n return urlString;\n}\n\n/**\n * Converts an Ethers BigNumber to a BN.\n *\n * @param bigNumber - An Ethers BigNumber instance.\n * @returns A BN object.\n */\nexport function ethersBigNumberToBN(bigNumber: BigNumber): BN {\n return new BN(remove0x(bigNumber.toHexString()), 'hex');\n}\n\n/**\n * Partitions a list of values into groups that are at most `batchSize` in\n * length.\n *\n * @param values - The list of values.\n * @param args - The remaining arguments.\n * @param args.batchSize - The desired maximum number of values per batch.\n * @returns The list of batches.\n */\nexport function divideIntoBatches<Value>(\n values: Value[],\n { batchSize }: { batchSize: number },\n): Value[][] {\n const batches = [];\n for (let i = 0; i < values.length; i += batchSize) {\n batches.push(values.slice(i, i + batchSize));\n }\n return batches;\n}\n\n/**\n * Constructs an object from processing batches of the given values\n * sequentially.\n *\n * @param args - The arguments to this function.\n * @param args.values - A list of values to iterate over.\n * @param args.batchSize - The maximum number of values in each batch.\n * @param args.eachBatch - A function to call for each batch. This function is\n * similar to the function that `Array.prototype.reduce` takes, in that it\n * receives the object that is being built, each batch in the list of batches\n * and the index, and should return an updated version of the object.\n * @param args.initialResult - The initial value of the final data structure,\n * i.e., the value that will be fed into the first call of `eachBatch`.\n * @returns The built object.\n */\nexport async function reduceInBatchesSerially<\n Value,\n Result extends Record<PropertyKey, unknown>,\n>({\n values,\n batchSize,\n eachBatch,\n initialResult,\n}: {\n values: Value[];\n batchSize: number;\n eachBatch: (\n workingResult: Partial<Result>,\n batch: Value[],\n index: number,\n ) => Partial<Result> | Promise<Partial<Result>>;\n initialResult: Partial<Result>;\n}): Promise<Result> {\n const batches = divideIntoBatches(values, { batchSize });\n let workingResult = initialResult;\n for (const [index, batch] of batches.entries()) {\n workingResult = await eachBatch(workingResult, batch, index);\n }\n // There's no way around this — we have to assume that in the end, the result\n // matches the intended type.\n const finalResult = workingResult as Result;\n return finalResult;\n}\n\n/**\n * Maps an OpenSea V2 NFT to the V1 schema.\n * @param nft - The V2 NFT to map.\n * @returns The NFT in the V1 schema.\n */\nexport function mapOpenSeaNftV2ToV1(nft: OpenSeaV2Nft): ApiNft {\n return {\n token_id: nft.identifier,\n num_sales: null,\n background_color: null,\n image_url: nft.image_url ?? null,\n image_preview_url: null,\n image_thumbnail_url: null,\n image_original_url: null,\n animation_url: null,\n animation_original_url: null,\n name: nft.name,\n description: nft.description,\n external_link: null,\n asset_contract: {\n address: nft.contract,\n asset_contract_type: null,\n created_date: null,\n schema_name: nft.token_standard.toUpperCase(),\n symbol: null,\n total_supply: null,\n description: nft.description,\n external_link: null,\n collection: {\n name: nft.collection,\n image_url: null,\n },\n },\n creator: {\n user: { username: '' },\n profile_img_url: '',\n address: '',\n },\n last_sale: null,\n };\n}\n\n/**\n * Maps an OpenSea V2 detailed NFT to the V1 schema.\n * @param nft - The V2 detailed NFT to map.\n * @returns The NFT in the V1 schema.\n */\nexport function mapOpenSeaDetailedNftV2ToV1(nft: OpenSeaV2DetailedNft): ApiNft {\n const mapped = mapOpenSeaNftV2ToV1(nft);\n return {\n ...mapped,\n animation_url: nft.animation_url ?? null,\n creator: {\n ...mapped.creator,\n address: nft.creator,\n },\n };\n}\n\n/**\n * Maps an OpenSea V2 contract to the V1 schema.\n * @param contract - The v2 contract data.\n * @param collection - The v2 collection data.\n * @returns The contract in the v1 schema.\n */\nexport function mapOpenSeaContractV2ToV1(\n contract: OpenSeaV2Contract,\n collection?: OpenSeaV2Collection,\n): ApiNftContract {\n return {\n address: contract.address,\n asset_contract_type: null,\n created_date: null,\n schema_name: contract.contract_standard.toUpperCase(),\n symbol: null,\n total_supply:\n collection?.total_supply?.toString() ??\n contract.total_supply?.toString() ??\n null,\n description: collection?.description ?? null,\n external_link: collection?.project_url ?? null,\n collection: {\n name: collection?.name ?? contract.name,\n image_url: collection?.image_url,\n },\n };\n}\n\n/**\n * Retrieves token prices for a set of contract addresses in a specific currency and chainId.\n *\n * @param args - The arguments to function.\n * @param args.tokenPricesService - An object in charge of retrieving token prices.\n * @param args.nativeCurrency - The native currency to request price in.\n * @param args.tokenAddresses - The list of contract addresses.\n * @param args.chainId - The chainId of the tokens.\n * @returns The prices for the requested tokens.\n */\nexport async function fetchTokenContractExchangeRates({\n tokenPricesService,\n nativeCurrency,\n tokenAddresses,\n chainId,\n}: {\n tokenPricesService: AbstractTokenPricesService;\n nativeCurrency: string;\n tokenAddresses: Hex[];\n chainId: Hex;\n}): Promise<ContractExchangeRates> {\n const isChainIdSupported =\n tokenPricesService.validateChainIdSupported(chainId);\n const isCurrencySupported =\n tokenPricesService.validateCurrencySupported(nativeCurrency);\n\n if (!isChainIdSupported || !isCurrencySupported) {\n return {};\n }\n\n const tokenPricesByTokenAddress = await reduceInBatchesSerially<\n Hex,\n Awaited<ReturnType<AbstractTokenPricesService['fetchTokenPrices']>>\n >({\n values: [...tokenAddresses].sort(),\n batchSize: TOKEN_PRICES_BATCH_SIZE,\n eachBatch: async (allTokenPricesByTokenAddress, batch) => {\n const tokenPricesByTokenAddressForBatch =\n await tokenPricesService.fetchTokenPrices({\n tokenAddresses: batch,\n chainId,\n currency: nativeCurrency,\n });\n\n return {\n ...allTokenPricesByTokenAddress,\n ...tokenPricesByTokenAddressForBatch,\n };\n },\n initialResult: {},\n });\n\n return Object.entries(tokenPricesByTokenAddress).reduce(\n (obj, [tokenAddress, tokenPrice]) => {\n return {\n ...obj,\n [toChecksumHexAddress(tokenAddress)]: tokenPrice?.value,\n };\n },\n {},\n );\n}\n"],"mappings":";AACA;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,gBAAgB;AACzB,OAAO,QAAQ;AACf,SAAS,WAAW;AAkBb,IAAM,0BAA0B;AAWhC,SAAS,mBAAmB,gBAA6B,KAAU;AACxE,QAAM,OAA8B;AAAA,IAClC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,QAAM,kBAAkB,KAAK,OAAO,CAAC,OAAO,QAAQ;AAClD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MACL;AAAA,IACF;AAAA,IACA,eAAe,CAAC;AAAA,EAClB,CAAC;AAED,SAAO,OAAO,QAAQ,yBAAyB,EAAE;AAAA,IAC/C,CAAC,KAAK,CAAC,cAAc,UAAU,MAAM;AACnC,aAAO;AAAA,QACL,GAAG;AAAA,QACH,CAAC,qBAAqB,YAAY,CAAC,GAAG,YAAY;AAAA,MACpD;AAAA,IACF;AAAA,IACA,CAAC;AAAA,EACH;AACF;","names":["SupportedTokenDetectionNetworks"]}
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import {
|
|
2
|
+
mapOpenSeaNftV2ToV1
|
|
3
|
+
} from "./chunk-5C7ZVZNM.mjs";
|
|
4
|
+
|
|
5
|
+
// src/NftDetectionController.ts
|
|
6
|
+
import {
|
|
7
|
+
OPENSEA_PROXY_URL,
|
|
8
|
+
fetchWithErrorHandling,
|
|
9
|
+
toChecksumHexAddress,
|
|
10
|
+
ChainId,
|
|
11
|
+
timeoutFetch,
|
|
12
|
+
safelyExecute
|
|
13
|
+
} from "@metamask/controller-utils";
|
|
14
|
+
import { StaticIntervalPollingControllerV1 } from "@metamask/polling-controller";
|
|
15
|
+
var DEFAULT_INTERVAL = 18e4;
|
|
16
|
+
var NftDetectionController = class extends StaticIntervalPollingControllerV1 {
|
|
17
|
+
/**
|
|
18
|
+
* Creates an NftDetectionController instance.
|
|
19
|
+
*
|
|
20
|
+
* @param options - The controller options.
|
|
21
|
+
* @param options.chainId - The chain ID of the current network.
|
|
22
|
+
* @param options.onNftsStateChange - Allows subscribing to assets controller state changes.
|
|
23
|
+
* @param options.onPreferencesStateChange - Allows subscribing to preferences controller state changes.
|
|
24
|
+
* @param options.onNetworkStateChange - Allows subscribing to network controller state changes.
|
|
25
|
+
* @param options.getOpenSeaApiKey - Gets the OpenSea API key, if one is set.
|
|
26
|
+
* @param options.addNft - Add an NFT.
|
|
27
|
+
* @param options.getNftApi - Gets the URL to fetch an NFT from OpenSea.
|
|
28
|
+
* @param options.getNftState - Gets the current state of the Assets controller.
|
|
29
|
+
* @param options.getNetworkClientById - Gets the network client by ID, from the NetworkController.
|
|
30
|
+
* @param config - Initial options used to configure this controller.
|
|
31
|
+
* @param state - Initial state to set on this controller.
|
|
32
|
+
*/
|
|
33
|
+
constructor({
|
|
34
|
+
chainId: initialChainId,
|
|
35
|
+
getNetworkClientById,
|
|
36
|
+
onPreferencesStateChange,
|
|
37
|
+
onNetworkStateChange,
|
|
38
|
+
getOpenSeaApiKey,
|
|
39
|
+
addNft,
|
|
40
|
+
getNftApi,
|
|
41
|
+
getNftState
|
|
42
|
+
}, config, state) {
|
|
43
|
+
super(config, state);
|
|
44
|
+
/**
|
|
45
|
+
* Name of this controller used during composition
|
|
46
|
+
*/
|
|
47
|
+
this.name = "NftDetectionController";
|
|
48
|
+
/**
|
|
49
|
+
* Checks whether network is mainnet or not.
|
|
50
|
+
*
|
|
51
|
+
* @returns Whether current network is mainnet.
|
|
52
|
+
*/
|
|
53
|
+
this.isMainnet = () => this.config.chainId === ChainId.mainnet;
|
|
54
|
+
this.isMainnetByNetworkClientId = (networkClient) => {
|
|
55
|
+
return networkClient.configuration.chainId === ChainId.mainnet;
|
|
56
|
+
};
|
|
57
|
+
this.defaultConfig = {
|
|
58
|
+
interval: DEFAULT_INTERVAL,
|
|
59
|
+
chainId: initialChainId,
|
|
60
|
+
selectedAddress: "",
|
|
61
|
+
disabled: true
|
|
62
|
+
};
|
|
63
|
+
this.initialize();
|
|
64
|
+
this.getNftState = getNftState;
|
|
65
|
+
this.getNetworkClientById = getNetworkClientById;
|
|
66
|
+
onPreferencesStateChange(({ selectedAddress, useNftDetection }) => {
|
|
67
|
+
const { selectedAddress: previouslySelectedAddress, disabled } = this.config;
|
|
68
|
+
if (selectedAddress !== previouslySelectedAddress || !useNftDetection !== disabled) {
|
|
69
|
+
this.configure({ selectedAddress, disabled: !useNftDetection });
|
|
70
|
+
if (useNftDetection) {
|
|
71
|
+
this.start();
|
|
72
|
+
} else {
|
|
73
|
+
this.stop();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
onNetworkStateChange(({ providerConfig }) => {
|
|
78
|
+
this.configure({
|
|
79
|
+
chainId: providerConfig.chainId
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
this.getOpenSeaApiKey = getOpenSeaApiKey;
|
|
83
|
+
this.addNft = addNft;
|
|
84
|
+
this.getNftApi = getNftApi;
|
|
85
|
+
this.setIntervalLength(this.config.interval);
|
|
86
|
+
}
|
|
87
|
+
getOwnerNftApi({
|
|
88
|
+
address,
|
|
89
|
+
next
|
|
90
|
+
}) {
|
|
91
|
+
return `${OPENSEA_PROXY_URL}/chain/${"ethereum" /* ethereum */}/account/${address}/nfts?limit=200&next=${next ?? ""}`;
|
|
92
|
+
}
|
|
93
|
+
async getOwnerNfts(address) {
|
|
94
|
+
let nftApiResponse;
|
|
95
|
+
let nfts = [];
|
|
96
|
+
let next;
|
|
97
|
+
do {
|
|
98
|
+
nftApiResponse = await fetchWithErrorHandling({
|
|
99
|
+
url: this.getOwnerNftApi({ address, next }),
|
|
100
|
+
timeout: 15e3
|
|
101
|
+
});
|
|
102
|
+
if (!nftApiResponse) {
|
|
103
|
+
return nfts;
|
|
104
|
+
}
|
|
105
|
+
const newNfts = await Promise.all(
|
|
106
|
+
nftApiResponse.nfts.map(async (nftV2) => {
|
|
107
|
+
const nftV1 = mapOpenSeaNftV2ToV1(nftV2);
|
|
108
|
+
if (!nftV1.image_url && nftV2.metadata_url) {
|
|
109
|
+
const nftDetails = await safelyExecute(
|
|
110
|
+
() => timeoutFetch(
|
|
111
|
+
this.getNftApi({
|
|
112
|
+
contractAddress: nftV2.contract,
|
|
113
|
+
tokenId: nftV2.identifier
|
|
114
|
+
}),
|
|
115
|
+
void 0,
|
|
116
|
+
1e3
|
|
117
|
+
).then((r) => r.json())
|
|
118
|
+
);
|
|
119
|
+
nftV1.image_original_url = nftDetails?.nft?.image_url ?? null;
|
|
120
|
+
}
|
|
121
|
+
return nftV1;
|
|
122
|
+
})
|
|
123
|
+
);
|
|
124
|
+
nfts = [...nfts, ...newNfts];
|
|
125
|
+
} while (next = nftApiResponse.next);
|
|
126
|
+
return nfts;
|
|
127
|
+
}
|
|
128
|
+
async _executePoll(networkClientId, options) {
|
|
129
|
+
await this.detectNfts({ networkClientId, userAddress: options.address });
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Start polling for the currency rate.
|
|
133
|
+
*/
|
|
134
|
+
async start() {
|
|
135
|
+
if (!this.isMainnet() || this.disabled) {
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
await this.startPolling();
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Stop polling for the currency rate.
|
|
142
|
+
*/
|
|
143
|
+
stop() {
|
|
144
|
+
this.stopPolling();
|
|
145
|
+
}
|
|
146
|
+
stopPolling() {
|
|
147
|
+
if (this.intervalId) {
|
|
148
|
+
clearInterval(this.intervalId);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Starts a new polling interval.
|
|
153
|
+
*
|
|
154
|
+
* @param interval - An interval on which to poll.
|
|
155
|
+
*/
|
|
156
|
+
async startPolling(interval) {
|
|
157
|
+
interval && this.configure({ interval }, false, false);
|
|
158
|
+
this.stopPolling();
|
|
159
|
+
await this.detectNfts();
|
|
160
|
+
this.intervalId = setInterval(async () => {
|
|
161
|
+
await this.detectNfts();
|
|
162
|
+
}, this.config.interval);
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Triggers asset ERC721 token auto detection on mainnet. Any newly detected NFTs are
|
|
166
|
+
* added.
|
|
167
|
+
*
|
|
168
|
+
* @param options - Options bag.
|
|
169
|
+
* @param options.networkClientId - The network client ID to detect NFTs on.
|
|
170
|
+
* @param options.userAddress - The address to detect NFTs for.
|
|
171
|
+
*/
|
|
172
|
+
async detectNfts({
|
|
173
|
+
networkClientId,
|
|
174
|
+
userAddress
|
|
175
|
+
} = { userAddress: this.config.selectedAddress }) {
|
|
176
|
+
if (!this.isMainnet() || this.disabled) {
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (!userAddress) {
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
const apiNfts = await this.getOwnerNfts(userAddress);
|
|
183
|
+
const addNftPromises = apiNfts.map(async (nft) => {
|
|
184
|
+
const {
|
|
185
|
+
token_id,
|
|
186
|
+
num_sales,
|
|
187
|
+
background_color,
|
|
188
|
+
image_url,
|
|
189
|
+
image_preview_url,
|
|
190
|
+
image_thumbnail_url,
|
|
191
|
+
image_original_url,
|
|
192
|
+
animation_url,
|
|
193
|
+
animation_original_url,
|
|
194
|
+
name,
|
|
195
|
+
description,
|
|
196
|
+
external_link,
|
|
197
|
+
creator,
|
|
198
|
+
asset_contract: { address, schema_name },
|
|
199
|
+
last_sale
|
|
200
|
+
} = nft;
|
|
201
|
+
let ignored;
|
|
202
|
+
const { ignoredNfts } = this.getNftState();
|
|
203
|
+
if (ignoredNfts.length) {
|
|
204
|
+
ignored = ignoredNfts.find((c) => {
|
|
205
|
+
return c.address === toChecksumHexAddress(address) && c.tokenId === token_id;
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
if (!ignored) {
|
|
209
|
+
const nftMetadata = Object.assign(
|
|
210
|
+
{},
|
|
211
|
+
{ name },
|
|
212
|
+
creator && { creator },
|
|
213
|
+
description && { description },
|
|
214
|
+
image_url && { image: image_url },
|
|
215
|
+
num_sales && { numberOfSales: num_sales },
|
|
216
|
+
background_color && { backgroundColor: background_color },
|
|
217
|
+
image_preview_url && { imagePreview: image_preview_url },
|
|
218
|
+
image_thumbnail_url && { imageThumbnail: image_thumbnail_url },
|
|
219
|
+
image_original_url && { imageOriginal: image_original_url },
|
|
220
|
+
animation_url && { animation: animation_url },
|
|
221
|
+
animation_original_url && {
|
|
222
|
+
animationOriginal: animation_original_url
|
|
223
|
+
},
|
|
224
|
+
schema_name && { standard: schema_name },
|
|
225
|
+
external_link && { externalLink: external_link },
|
|
226
|
+
last_sale && { lastSale: last_sale }
|
|
227
|
+
);
|
|
228
|
+
await this.addNft(address, token_id, {
|
|
229
|
+
nftMetadata,
|
|
230
|
+
userAddress,
|
|
231
|
+
source: "detected" /* Detected */,
|
|
232
|
+
networkClientId
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
await Promise.all(addNftPromises);
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
var NftDetectionController_default = NftDetectionController;
|
|
240
|
+
|
|
241
|
+
export {
|
|
242
|
+
NftDetectionController,
|
|
243
|
+
NftDetectionController_default
|
|
244
|
+
};
|
|
245
|
+
//# sourceMappingURL=chunk-64EHFYLM.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/NftDetectionController.ts"],"sourcesContent":["import type { BaseConfig, BaseState } from '@metamask/base-controller';\nimport {\n OPENSEA_PROXY_URL,\n fetchWithErrorHandling,\n toChecksumHexAddress,\n ChainId,\n timeoutFetch,\n safelyExecute,\n} from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkController,\n NetworkState,\n NetworkClient,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingControllerV1 } from '@metamask/polling-controller';\nimport type { PreferencesState } from '@metamask/preferences-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport { mapOpenSeaNftV2ToV1 } from './assetsUtil';\nimport { Source } from './constants';\nimport type { OpenSeaV2GetNftResponse } from './NftController';\nimport {\n type NftController,\n type NftState,\n type NftMetadata,\n type OpenSeaV2ListNftsResponse,\n OpenSeaV2ChainIds,\n} from './NftController';\n\nconst DEFAULT_INTERVAL = 180000;\n\n/**\n * @type ApiNft\n *\n * NFT object coming from OpenSea api\n * @property token_id - The NFT identifier\n * @property num_sales - Number of sales\n * @property background_color - The background color to be displayed with the item\n * @property image_url - URI of an image associated with this NFT\n * @property image_preview_url - URI of a smaller image associated with this NFT\n * @property image_thumbnail_url - URI of a thumbnail image associated with this NFT\n * @property image_original_url - URI of the original image associated with this NFT\n * @property animation_url - URI of a animation associated with this NFT\n * @property animation_original_url - URI of the original animation associated with this NFT\n * @property name - The NFT name\n * @property description - The NFT description\n * @property external_link - External link containing additional information\n * @property assetContract - The NFT contract information object\n * @property creator - The NFT owner information object\n * @property lastSale - When this item was last sold\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface ApiNft {\n token_id: string;\n num_sales: number | null;\n background_color: string | null;\n image_url: string | null;\n image_preview_url: string | null;\n image_thumbnail_url: string | null;\n image_original_url: string | null;\n animation_url: string | null;\n animation_original_url: string | null;\n name: string | null;\n description: string | null;\n external_link: string | null;\n asset_contract: ApiNftContract;\n creator: ApiNftCreator;\n last_sale: ApiNftLastSale | null;\n}\n\n/**\n * @type ApiNftContract\n *\n * NFT contract object coming from OpenSea api\n * @property address - Address of the NFT contract\n * @property asset_contract_type - The NFT type, it could be `semi-fungible` or `non-fungible`\n * @property created_date - Creation date\n * @property collection - Object containing the contract name and URI of an image associated\n * @property schema_name - The schema followed by the contract, it could be `ERC721` or `ERC1155`\n * @property symbol - The NFT contract symbol\n * @property total_supply - Total supply of NFTs\n * @property description - The NFT contract description\n * @property external_link - External link containing additional information\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface ApiNftContract {\n address: string;\n asset_contract_type: string | null;\n created_date: string | null;\n schema_name: string | null;\n symbol: string | null;\n total_supply: string | null;\n description: string | null;\n external_link: string | null;\n collection: {\n name: string | null;\n image_url?: string | null;\n };\n}\n\n/**\n * @type ApiNftLastSale\n *\n * NFT sale object coming from OpenSea api\n * @property event_timestamp - Object containing a `username`\n * @property total_price - URI of NFT image associated with this owner\n * @property transaction - Object containing transaction_hash and block_hash\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface ApiNftLastSale {\n event_timestamp: string;\n total_price: string;\n transaction: { transaction_hash: string; block_hash: string };\n}\n\n/**\n * @type ApiNftCreator\n *\n * NFT creator object coming from OpenSea api\n * @property user - Object containing a `username`\n * @property profile_img_url - URI of NFT image associated with this owner\n * @property address - The owner address\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface ApiNftCreator {\n user: { username: string };\n profile_img_url: string;\n address: string;\n}\n\n/**\n * @type NftDetectionConfig\n *\n * NftDetection configuration\n * @property interval - Polling interval used to fetch new token rates\n * @property chainId - Current chain ID\n * @property selectedAddress - Vault selected address\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface NftDetectionConfig extends BaseConfig {\n interval: number;\n chainId: Hex;\n selectedAddress: string;\n}\n\n/**\n * Controller that passively polls on a set interval for NFT auto detection\n */\nexport class NftDetectionController extends StaticIntervalPollingControllerV1<\n NftDetectionConfig,\n BaseState\n> {\n private intervalId?: ReturnType<typeof setTimeout>;\n\n private getOwnerNftApi({\n address,\n next,\n }: {\n address: string;\n next?: string;\n }) {\n return `${OPENSEA_PROXY_URL}/chain/${\n OpenSeaV2ChainIds.ethereum\n }/account/${address}/nfts?limit=200&next=${next ?? ''}`;\n }\n\n private async getOwnerNfts(address: string) {\n let nftApiResponse: OpenSeaV2ListNftsResponse;\n let nfts: ApiNft[] = [];\n let next;\n\n do {\n nftApiResponse = await fetchWithErrorHandling({\n url: this.getOwnerNftApi({ address, next }),\n timeout: 15000,\n });\n\n if (!nftApiResponse) {\n return nfts;\n }\n\n const newNfts = await Promise.all(\n nftApiResponse.nfts.map(async (nftV2) => {\n const nftV1 = mapOpenSeaNftV2ToV1(nftV2);\n\n // If the image hasn't been processed into OpenSea's CDN, the image_url will be null.\n // Try fetching the NFT individually, which returns the original image url from metadata if available.\n if (!nftV1.image_url && nftV2.metadata_url) {\n const nftDetails: OpenSeaV2GetNftResponse | undefined =\n await safelyExecute(() =>\n timeoutFetch(\n this.getNftApi({\n contractAddress: nftV2.contract,\n tokenId: nftV2.identifier,\n }),\n undefined,\n 1000,\n ).then((r) => r.json()),\n );\n\n nftV1.image_original_url = nftDetails?.nft?.image_url ?? null;\n }\n return nftV1;\n }),\n );\n\n nfts = [...nfts, ...newNfts];\n } while ((next = nftApiResponse.next));\n\n return nfts;\n }\n\n /**\n * Name of this controller used during composition\n */\n override name = 'NftDetectionController';\n\n private readonly getOpenSeaApiKey: () => string | undefined;\n\n private readonly addNft: NftController['addNft'];\n\n private readonly getNftApi: NftController['getNftApi'];\n\n private readonly getNftState: () => NftState;\n\n private readonly getNetworkClientById: NetworkController['getNetworkClientById'];\n\n /**\n * Creates an NftDetectionController instance.\n *\n * @param options - The controller options.\n * @param options.chainId - The chain ID of the current network.\n * @param options.onNftsStateChange - Allows subscribing to assets controller state changes.\n * @param options.onPreferencesStateChange - Allows subscribing to preferences controller state changes.\n * @param options.onNetworkStateChange - Allows subscribing to network controller state changes.\n * @param options.getOpenSeaApiKey - Gets the OpenSea API key, if one is set.\n * @param options.addNft - Add an NFT.\n * @param options.getNftApi - Gets the URL to fetch an NFT from OpenSea.\n * @param options.getNftState - Gets the current state of the Assets controller.\n * @param options.getNetworkClientById - Gets the network client by ID, from the NetworkController.\n * @param config - Initial options used to configure this controller.\n * @param state - Initial state to set on this controller.\n */\n constructor(\n {\n chainId: initialChainId,\n getNetworkClientById,\n onPreferencesStateChange,\n onNetworkStateChange,\n getOpenSeaApiKey,\n addNft,\n getNftApi,\n getNftState,\n }: {\n chainId: Hex;\n getNetworkClientById: NetworkController['getNetworkClientById'];\n onNftsStateChange: (listener: (nftsState: NftState) => void) => void;\n onPreferencesStateChange: (\n listener: (preferencesState: PreferencesState) => void,\n ) => void;\n onNetworkStateChange: (\n listener: (networkState: NetworkState) => void,\n ) => void;\n getOpenSeaApiKey: () => string | undefined;\n addNft: NftController['addNft'];\n getNftApi: NftController['getNftApi'];\n getNftState: () => NftState;\n },\n config?: Partial<NftDetectionConfig>,\n state?: Partial<BaseState>,\n ) {\n super(config, state);\n this.defaultConfig = {\n interval: DEFAULT_INTERVAL,\n chainId: initialChainId,\n selectedAddress: '',\n disabled: true,\n };\n this.initialize();\n this.getNftState = getNftState;\n this.getNetworkClientById = getNetworkClientById;\n onPreferencesStateChange(({ selectedAddress, useNftDetection }) => {\n const { selectedAddress: previouslySelectedAddress, disabled } =\n this.config;\n\n if (\n selectedAddress !== previouslySelectedAddress ||\n !useNftDetection !== disabled\n ) {\n this.configure({ selectedAddress, disabled: !useNftDetection });\n if (useNftDetection) {\n this.start();\n } else {\n this.stop();\n }\n }\n });\n\n onNetworkStateChange(({ providerConfig }) => {\n this.configure({\n chainId: providerConfig.chainId,\n });\n });\n this.getOpenSeaApiKey = getOpenSeaApiKey;\n this.addNft = addNft;\n this.getNftApi = getNftApi;\n this.setIntervalLength(this.config.interval);\n }\n\n async _executePoll(\n networkClientId: string,\n options: { address: string },\n ): Promise<void> {\n await this.detectNfts({ networkClientId, userAddress: options.address });\n }\n\n /**\n * Start polling for the currency rate.\n */\n async start() {\n if (!this.isMainnet() || this.disabled) {\n return;\n }\n\n await this.startPolling();\n }\n\n /**\n * Stop polling for the currency rate.\n */\n stop() {\n this.stopPolling();\n }\n\n private stopPolling() {\n if (this.intervalId) {\n clearInterval(this.intervalId);\n }\n }\n\n /**\n * Starts a new polling interval.\n *\n * @param interval - An interval on which to poll.\n */\n private async startPolling(interval?: number): Promise<void> {\n interval && this.configure({ interval }, false, false);\n this.stopPolling();\n await this.detectNfts();\n this.intervalId = setInterval(async () => {\n await this.detectNfts();\n }, this.config.interval);\n }\n\n /**\n * Checks whether network is mainnet or not.\n *\n * @returns Whether current network is mainnet.\n */\n isMainnet = (): boolean => this.config.chainId === ChainId.mainnet;\n\n isMainnetByNetworkClientId = (networkClient: NetworkClient): boolean => {\n return networkClient.configuration.chainId === ChainId.mainnet;\n };\n\n /**\n * Triggers asset ERC721 token auto detection on mainnet. Any newly detected NFTs are\n * added.\n *\n * @param options - Options bag.\n * @param options.networkClientId - The network client ID to detect NFTs on.\n * @param options.userAddress - The address to detect NFTs for.\n */\n async detectNfts(\n {\n networkClientId,\n userAddress,\n }: {\n networkClientId?: NetworkClientId;\n userAddress: string;\n } = { userAddress: this.config.selectedAddress },\n ) {\n /* istanbul ignore if */\n if (!this.isMainnet() || this.disabled) {\n return;\n }\n /* istanbul ignore else */\n if (!userAddress) {\n return;\n }\n\n const apiNfts = await this.getOwnerNfts(userAddress);\n const addNftPromises = apiNfts.map(async (nft: ApiNft) => {\n const {\n token_id,\n num_sales,\n background_color,\n image_url,\n image_preview_url,\n image_thumbnail_url,\n image_original_url,\n animation_url,\n animation_original_url,\n name,\n description,\n external_link,\n creator,\n asset_contract: { address, schema_name },\n last_sale,\n } = nft;\n\n let ignored;\n /* istanbul ignore else */\n const { ignoredNfts } = this.getNftState();\n if (ignoredNfts.length) {\n ignored = ignoredNfts.find((c) => {\n /* istanbul ignore next */\n return (\n c.address === toChecksumHexAddress(address) &&\n c.tokenId === token_id\n );\n });\n }\n\n /* istanbul ignore else */\n if (!ignored) {\n /* istanbul ignore next */\n const nftMetadata: NftMetadata = Object.assign(\n {},\n { name },\n creator && { creator },\n description && { description },\n image_url && { image: image_url },\n num_sales && { numberOfSales: num_sales },\n background_color && { backgroundColor: background_color },\n image_preview_url && { imagePreview: image_preview_url },\n image_thumbnail_url && { imageThumbnail: image_thumbnail_url },\n image_original_url && { imageOriginal: image_original_url },\n animation_url && { animation: animation_url },\n animation_original_url && {\n animationOriginal: animation_original_url,\n },\n schema_name && { standard: schema_name },\n external_link && { externalLink: external_link },\n last_sale && { lastSale: last_sale },\n );\n\n await this.addNft(address, token_id, {\n nftMetadata,\n userAddress,\n source: Source.Detected,\n networkClientId,\n });\n }\n });\n await Promise.all(addNftPromises);\n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