@metamask/assets-controllers 31.0.0 → 33.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.
- package/CHANGELOG.md +68 -1
- package/dist/AccountTrackerController.js +2 -2
- package/dist/AccountTrackerController.mjs +1 -1
- package/dist/AssetsContractController.js +6 -6
- package/dist/AssetsContractController.mjs +5 -5
- package/dist/CurrencyRateController.js +3 -3
- package/dist/CurrencyRateController.mjs +2 -2
- package/dist/NftController.js +3 -3
- package/dist/NftController.mjs +2 -2
- package/dist/NftDetectionController.js +2 -2
- package/dist/NftDetectionController.mjs +1 -1
- package/dist/RatesController/RatesController.js +3 -3
- package/dist/RatesController/RatesController.mjs +2 -2
- package/dist/RatesController/index.js +3 -3
- package/dist/RatesController/index.mjs +2 -2
- package/dist/Standards/ERC20Standard.js +3 -3
- package/dist/Standards/ERC20Standard.mjs +2 -2
- package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js +3 -3
- package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.mjs +2 -2
- package/dist/Standards/NftStandards/ERC721/ERC721Standard.js +3 -3
- package/dist/Standards/NftStandards/ERC721/ERC721Standard.mjs +2 -2
- package/dist/TokenBalancesController.js +2 -2
- package/dist/TokenBalancesController.mjs +1 -1
- package/dist/TokenDetectionController.js +3 -3
- package/dist/TokenDetectionController.mjs +2 -2
- package/dist/TokenListController.js +4 -4
- package/dist/TokenListController.mjs +3 -3
- package/dist/TokenRatesController.js +9 -5
- package/dist/TokenRatesController.mjs +10 -6
- package/dist/TokensController.js +6 -6
- package/dist/TokensController.mjs +5 -5
- package/dist/assetsUtil.js +2 -2
- package/dist/assetsUtil.mjs +1 -1
- package/dist/chunk-2IIQTSLV.mjs +236 -0
- package/dist/chunk-2IIQTSLV.mjs.map +1 -0
- package/dist/chunk-354SINOH.js +236 -0
- package/dist/chunk-354SINOH.js.map +1 -0
- package/dist/{chunk-MR6EF4B7.mjs → chunk-3K3LE2CZ.mjs} +14 -2
- package/dist/chunk-3K3LE2CZ.mjs.map +1 -0
- package/dist/{chunk-5W5OO2Q5.mjs → chunk-47CRHAUE.mjs} +2 -2
- package/dist/chunk-47CRHAUE.mjs.map +1 -0
- package/dist/{chunk-65PB33TE.mjs → chunk-526TATMH.mjs} +25 -17
- package/dist/chunk-526TATMH.mjs.map +1 -0
- package/dist/{chunk-D3K5MPMW.mjs → chunk-56O7BVZV.mjs} +2 -2
- package/dist/{chunk-B5YY22QQ.js → chunk-6PPM4ETZ.js} +3 -3
- package/dist/{chunk-CGLUTXI7.js → chunk-7JWDWDXT.js} +190 -107
- package/dist/chunk-7JWDWDXT.js.map +1 -0
- package/dist/{chunk-JUI3XNEF.js → chunk-7OZL6IDY.js} +16 -9
- package/dist/chunk-7OZL6IDY.js.map +1 -0
- package/dist/{chunk-GU53EI7A.js → chunk-AZ6SRJVI.js} +24 -16
- package/dist/chunk-AZ6SRJVI.js.map +1 -0
- package/dist/{chunk-YIFA2HXH.js → chunk-F6L3DFOZ.js} +5 -3
- package/dist/chunk-F6L3DFOZ.js.map +1 -0
- package/dist/{chunk-UEDNQBJN.js → chunk-FGAZXVKS.js} +200 -104
- package/dist/chunk-FGAZXVKS.js.map +1 -0
- package/dist/{chunk-B6W4CQOR.mjs → chunk-HJ5GXVDT.mjs} +2 -2
- package/dist/chunk-HJ5GXVDT.mjs.map +1 -0
- package/dist/{chunk-BOTVAG4A.js → chunk-JBF4XEGR.js} +5 -5
- package/dist/{chunk-ASA5RLBY.mjs → chunk-JEIAMJGS.mjs} +2 -2
- package/dist/{chunk-CNKVITJO.mjs → chunk-JTXPJ6TK.mjs} +4 -2
- package/dist/chunk-JTXPJ6TK.mjs.map +1 -0
- package/dist/{chunk-U3DJJN4X.js → chunk-LBJTMJFA.js} +4 -4
- package/dist/{chunk-IBK6AXPP.js → chunk-NWVMFCSC.js} +1 -1
- package/dist/{chunk-IBK6AXPP.js.map → chunk-NWVMFCSC.js.map} +1 -1
- package/dist/{chunk-NEXY7SE2.js → chunk-NYVA7ZTQ.js} +2 -2
- package/dist/chunk-NYVA7ZTQ.js.map +1 -0
- package/dist/{chunk-WCCLSUOI.mjs → chunk-OEEFNXR7.mjs} +1 -1
- package/dist/{chunk-WCCLSUOI.mjs.map → chunk-OEEFNXR7.mjs.map} +1 -1
- package/dist/{chunk-E4ECCGJV.mjs → chunk-P3O5CVAH.mjs} +195 -99
- package/dist/chunk-P3O5CVAH.mjs.map +1 -0
- package/dist/{chunk-4AC3X2U5.js → chunk-RJBYLTY5.js} +29 -14
- package/dist/chunk-RJBYLTY5.js.map +1 -0
- package/dist/{chunk-B5YVX5IO.mjs → chunk-SBWPU4VT.mjs} +4 -2
- package/dist/chunk-SBWPU4VT.mjs.map +1 -0
- package/dist/{chunk-ELSMS5S7.js → chunk-T5ZX5BV7.js} +3 -3
- package/dist/{chunk-ELSMS5S7.js.map → chunk-T5ZX5BV7.js.map} +1 -1
- package/dist/{chunk-HLCGZGPA.mjs → chunk-TWR6P5WG.mjs} +11 -7
- package/dist/chunk-TWR6P5WG.mjs.map +1 -0
- package/dist/{chunk-73F3SN5O.mjs → chunk-UVE4XY5Y.mjs} +23 -8
- package/dist/chunk-UVE4XY5Y.mjs.map +1 -0
- package/dist/{chunk-LZ5ZGQEX.mjs → chunk-UYH6NWKB.mjs} +2 -2
- package/dist/{chunk-Z6TBQQE5.js → chunk-V6DNVROD.js} +4 -4
- package/dist/chunk-V6DNVROD.js.map +1 -0
- package/dist/{chunk-Q5JRBGWO.mjs → chunk-VELPHITE.mjs} +2 -2
- package/dist/chunk-VELPHITE.mjs.map +1 -0
- package/dist/{chunk-HDI4L2DD.js → chunk-VZF43NDM.js} +17 -5
- package/dist/chunk-VZF43NDM.js.map +1 -0
- package/dist/{chunk-62T7RKU3.mjs → chunk-W57QXOHJ.mjs} +188 -105
- package/dist/chunk-W57QXOHJ.mjs.map +1 -0
- package/dist/{chunk-PYMUBJQX.js → chunk-X4RMS365.js} +3 -3
- package/dist/chunk-X4RMS365.js.map +1 -0
- package/dist/{chunk-Y35SM7TO.mjs → chunk-XQO3EG4J.mjs} +4 -4
- package/dist/chunk-XQO3EG4J.mjs.map +1 -0
- package/dist/{chunk-QHWKLZUC.js → chunk-XSNGD5US.js} +14 -10
- package/dist/chunk-XSNGD5US.js.map +1 -0
- package/dist/{chunk-A2DDWXMS.mjs → chunk-Y45HQET7.mjs} +12 -5
- package/dist/chunk-Y45HQET7.mjs.map +1 -0
- package/dist/{chunk-WB6KJX4N.js → chunk-ZG5MS2TO.js} +4 -2
- package/dist/chunk-ZG5MS2TO.js.map +1 -0
- package/dist/crypto-compare-service/crypto-compare.js +2 -2
- package/dist/crypto-compare-service/crypto-compare.mjs +1 -1
- package/dist/crypto-compare-service/index.js +2 -2
- package/dist/crypto-compare-service/index.mjs +1 -1
- package/dist/index.js +21 -19
- package/dist/index.mjs +21 -19
- package/dist/token-prices-service/codefi-v2.js +2 -2
- package/dist/token-prices-service/codefi-v2.mjs +1 -1
- package/dist/token-prices-service/index.js +2 -2
- package/dist/token-prices-service/index.mjs +1 -1
- package/dist/token-service.js +3 -3
- package/dist/token-service.mjs +2 -2
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/AccountTrackerController.d.ts +13 -12
- package/dist/types/AccountTrackerController.d.ts.map +1 -1
- package/dist/types/AssetsContractController.d.ts.map +1 -1
- package/dist/types/CurrencyRateController.d.ts.map +1 -1
- package/dist/types/NftController.d.ts +4 -5
- package/dist/types/NftController.d.ts.map +1 -1
- package/dist/types/NftDetectionController.d.ts +7 -18
- package/dist/types/NftDetectionController.d.ts.map +1 -1
- package/dist/types/RatesController/RatesController.d.ts.map +1 -1
- package/dist/types/TokenBalancesController.d.ts.map +1 -1
- package/dist/types/TokenDetectionController.d.ts.map +1 -1
- package/dist/types/TokenListController.d.ts.map +1 -1
- package/dist/types/TokenRatesController.d.ts +72 -65
- package/dist/types/TokenRatesController.d.ts.map +1 -1
- package/dist/types/TokensController.d.ts.map +1 -1
- package/dist/types/assetsUtil.d.ts.map +1 -1
- package/dist/types/crypto-compare-service/crypto-compare.d.ts.map +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/token-prices-service/abstract-token-prices-service.d.ts +0 -1
- package/dist/types/token-prices-service/abstract-token-prices-service.d.ts.map +1 -1
- package/dist/types/token-prices-service/codefi-v2.d.ts +1 -1
- package/dist/types/token-prices-service/codefi-v2.d.ts.map +1 -1
- package/dist/types/token-service.d.ts.map +1 -1
- package/package.json +16 -16
- package/dist/chunk-4AC3X2U5.js.map +0 -1
- package/dist/chunk-543CC74T.mjs +0 -253
- package/dist/chunk-543CC74T.mjs.map +0 -1
- package/dist/chunk-5W5OO2Q5.mjs.map +0 -1
- package/dist/chunk-62T7RKU3.mjs.map +0 -1
- package/dist/chunk-65PB33TE.mjs.map +0 -1
- package/dist/chunk-73F3SN5O.mjs.map +0 -1
- package/dist/chunk-A2DDWXMS.mjs.map +0 -1
- package/dist/chunk-B5YVX5IO.mjs.map +0 -1
- package/dist/chunk-B6W4CQOR.mjs.map +0 -1
- package/dist/chunk-CGLUTXI7.js.map +0 -1
- package/dist/chunk-CNKVITJO.mjs.map +0 -1
- package/dist/chunk-E4ECCGJV.mjs.map +0 -1
- package/dist/chunk-GU53EI7A.js.map +0 -1
- package/dist/chunk-HDI4L2DD.js.map +0 -1
- package/dist/chunk-HLCGZGPA.mjs.map +0 -1
- package/dist/chunk-JUI3XNEF.js.map +0 -1
- package/dist/chunk-MR6EF4B7.mjs.map +0 -1
- package/dist/chunk-NEXY7SE2.js.map +0 -1
- package/dist/chunk-PYMUBJQX.js.map +0 -1
- package/dist/chunk-Q5JRBGWO.mjs.map +0 -1
- package/dist/chunk-QFDTOEYR.js +0 -253
- package/dist/chunk-QFDTOEYR.js.map +0 -1
- package/dist/chunk-QHWKLZUC.js.map +0 -1
- package/dist/chunk-UEDNQBJN.js.map +0 -1
- package/dist/chunk-WB6KJX4N.js.map +0 -1
- package/dist/chunk-Y35SM7TO.mjs.map +0 -1
- package/dist/chunk-YIFA2HXH.js.map +0 -1
- package/dist/chunk-Z6TBQQE5.js.map +0 -1
- /package/dist/{chunk-D3K5MPMW.mjs.map → chunk-56O7BVZV.mjs.map} +0 -0
- /package/dist/{chunk-B5YY22QQ.js.map → chunk-6PPM4ETZ.js.map} +0 -0
- /package/dist/{chunk-BOTVAG4A.js.map → chunk-JBF4XEGR.js.map} +0 -0
- /package/dist/{chunk-ASA5RLBY.mjs.map → chunk-JEIAMJGS.mjs.map} +0 -0
- /package/dist/{chunk-U3DJJN4X.js.map → chunk-LBJTMJFA.js.map} +0 -0
- /package/dist/{chunk-LZ5ZGQEX.mjs.map → chunk-UYH6NWKB.mjs.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/token-service.ts"],"names":[],"mappings":";;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAKA,IAAM,sBAAsB;AAC5B,IAAM,kCACX;AAQF,SAAS,aAAa,SAAc;AAClC,QAAM,kBAAkB,YAAY,QAAQ,eAAe,IAAI,IAAI;AACnE,SAAO,GAAG,mBAAmB,WAAW;AAAA,IACtC;AAAA,EACF,CAAC,oBAAoB,eAAe;AACtC;AASA,SAAS,oBAAoB,SAAc,cAAsB;AAC/D,SAAO,GAAG,mBAAmB,UAAU;AAAA,IACrC;AAAA,EACF,CAAC,YAAY,YAAY;AAC3B;AAEA,IAAM,2BAA2B;AAIjC,IAAM,iBAAiB;AAYvB,eAAsB,wBACpB,SACA,aACA,EAAE,UAAU,eAAe,IAAI,CAAC,GACd;AAClB,QAAM,WAAW,aAAa,OAAO;AACrC,QAAM,WAAW,MAAM,SAAS,UAAU,aAAa,OAAO;AAC9D,MAAI,UAAU;AACZ,UAAM,SAAS,MAAM,kBAAkB,QAAQ;AAC/C,QAAI,MAAM,QAAQ,MAAM,KAAK,YAAY,QAAQ,eAAe,GAAG;AACjE,aAAO,OAAO;AAAA,QACZ,CAAC,QACC,IAAI,YAAY,SAAS,WAAW,KAAK,IAAI,YAAY,UAAU;AAAA,MACvE;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAaA,eAAsB,mBACpB,SACA,cACA,aACA,EAAE,UAAU,eAAe,IAAI,CAAC,GACR;AACxB,MAAI,CAAC,+BAA+B,OAAO,GAAG;AAC5C,UAAM,IAAI,MAAM,+BAA+B;AAAA,EACjD;AACA,QAAM,mBAAmB,oBAAoB,SAAS,YAAY;AAClE,QAAM,WAAW,MAAM,SAAS,kBAAkB,aAAa,OAAO;AACtE,MAAI,UAAU;AACZ,WAAO,kBAAkB,QAAQ;AAAA,EACnC;AACA,SAAO;AACT;AAUA,eAAe,SACb,QACA,aACA,SAC+B;AAC/B,QAAM,eAA4B;AAAA,IAChC,UAAU;AAAA,IACV,gBAAgB;AAAA,IAChB,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,OAAO;AAAA,EACT;AACA,eAAa,UAAU,IAAI,OAAO,QAAQ;AAC1C,eAAa,QAAQ,IAAI,gBAAgB,kBAAkB;AAC3D,MAAI;AACF,WAAO,MAAM,aAAa,QAAQ,cAAc,OAAO;AAAA,EACzD,SAAS,OAAO;AACd,QAAI,iBAAiB,SAAS,MAAM,SAAS,cAAc;AACzD,cAAQ,IAAI,oBAAoB;AAAA,IAClC;AAAA,EACF;AACA,SAAO;AACT;AASA,eAAe,kBAAkB,aAAyC;AACxE,QAAM,cAAc,MAAM,YAAY,KAAK;AAE3C,MAAI,aAAa,OAAO;AACtB,UAAM,IAAI,MAAM,uBAAuB,YAAY,KAAK,EAAE;AAAA,EAC5D;AACA,SAAO;AACT","sourcesContent":["import {\n ChainId,\n convertHexToDecimal,\n timeoutFetch,\n} from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\n\nimport { isTokenListSupportedForNetwork } from './assetsUtil';\n\nexport const TOKEN_END_POINT_API = 'https://token.api.cx.metamask.io';\nexport const TOKEN_METADATA_NO_SUPPORT_ERROR =\n 'TokenService Error: Network does not support fetchTokenMetadata';\n\n/**\n * Get the tokens URL for a specific network.\n *\n * @param chainId - The chain ID of the network the tokens requested are on.\n * @returns The tokens URL.\n */\nfunction getTokensURL(chainId: Hex) {\n const occurrenceFloor = chainId === ChainId['linea-mainnet'] ? 1 : 3;\n return `${TOKEN_END_POINT_API}/tokens/${convertHexToDecimal(\n chainId,\n )}?occurrenceFloor=${occurrenceFloor}&includeNativeAssets=false&includeDuplicateSymbolAssets=false&includeTokenFees=false&includeAssetType=false&includeERC20Permit=false&includeStorage=false`;\n}\n\n/**\n * Get the token metadata URL for the given network and token.\n *\n * @param chainId - The chain ID of the network the token is on.\n * @param tokenAddress - The token address.\n * @returns The token metadata URL.\n */\nfunction getTokenMetadataURL(chainId: Hex, tokenAddress: string) {\n return `${TOKEN_END_POINT_API}/token/${convertHexToDecimal(\n chainId,\n )}?address=${tokenAddress}`;\n}\n\nconst tenSecondsInMilliseconds = 10_000;\n\n// Token list averages 1.6 MB in size\n// timeoutFetch by default has a 500ms timeout, which will almost always timeout given the response size.\nconst defaultTimeout = tenSecondsInMilliseconds;\n\n/**\n * Fetch the list of token metadata for a given network. This request is cancellable using the\n * abort signal passed in.\n *\n * @param chainId - The chain ID of the network the requested tokens are on.\n * @param abortSignal - The abort signal used to cancel the request if necessary.\n * @param options - Additional fetch options.\n * @param options.timeout - The fetch timeout.\n * @returns The token list, or `undefined` if the request was cancelled.\n */\nexport async function fetchTokenListByChainId(\n chainId: Hex,\n abortSignal: AbortSignal,\n { timeout = defaultTimeout } = {},\n): Promise<unknown> {\n const tokenURL = getTokensURL(chainId);\n const response = await queryApi(tokenURL, abortSignal, timeout);\n if (response) {\n const result = await parseJsonResponse(response);\n if (Array.isArray(result) && chainId === ChainId['linea-mainnet']) {\n return result.filter(\n (elm) =>\n elm.aggregators.includes('lineaTeam') || elm.aggregators.length >= 3,\n );\n }\n return result;\n }\n return undefined;\n}\n\n/**\n * Fetch metadata for the token address provided for a given network. This request is cancellable\n * using the abort signal passed in.\n *\n * @param chainId - The chain ID of the network the token is on.\n * @param tokenAddress - The address of the token to fetch metadata for.\n * @param abortSignal - The abort signal used to cancel the request if necessary.\n * @param options - Additional fetch options.\n * @param options.timeout - The fetch timeout.\n * @returns The token metadata, or `undefined` if the request was either aborted or failed.\n */\nexport async function fetchTokenMetadata<T>(\n chainId: Hex,\n tokenAddress: string,\n abortSignal: AbortSignal,\n { timeout = defaultTimeout } = {},\n): Promise<T | undefined> {\n if (!isTokenListSupportedForNetwork(chainId)) {\n throw new Error(TOKEN_METADATA_NO_SUPPORT_ERROR);\n }\n const tokenMetadataURL = getTokenMetadataURL(chainId, tokenAddress);\n const response = await queryApi(tokenMetadataURL, abortSignal, timeout);\n if (response) {\n return parseJsonResponse(response) as Promise<T>;\n }\n return undefined;\n}\n\n/**\n * Perform fetch request against the api.\n *\n * @param apiURL - The URL of the API to fetch.\n * @param abortSignal - The abort signal used to cancel the request if necessary.\n * @param timeout - The fetch timeout.\n * @returns Promise resolving request response.\n */\nasync function queryApi(\n apiURL: string,\n abortSignal: AbortSignal,\n timeout: number,\n): Promise<Response | undefined> {\n const fetchOptions: RequestInit = {\n referrer: apiURL,\n referrerPolicy: 'no-referrer-when-downgrade',\n method: 'GET',\n mode: 'cors',\n signal: abortSignal,\n cache: 'default',\n };\n fetchOptions.headers = new window.Headers();\n fetchOptions.headers.set('Content-Type', 'application/json');\n try {\n return await timeoutFetch(apiURL, fetchOptions, timeout);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n console.log('Request is aborted');\n }\n }\n return undefined;\n}\n\n/**\n * Parse an API response and return the response JSON data.\n *\n * @param apiResponse - The API response to parse.\n * @returns The response JSON data.\n * @throws Will throw if the response includes an error.\n */\nasync function parseJsonResponse(apiResponse: Response): Promise<unknown> {\n const responseObj = await apiResponse.json();\n // api may return errors as json without setting an error http status code\n if (responseObj?.error) {\n throw new Error(`TokenService Error: ${responseObj.error}`);\n }\n return responseObj;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
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 { Nft, NftMetadata } from './NftController';\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 'tokenURI',\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.cx.metamask.io/api/v1/tokenIcons/${chainIdDecimal}/${tokenAddress.toLowerCase()}.png`;\n};\n\n/**\n * Networks where token detection is supported - Values are in hex 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 cronos = '0x19', // decimal: 25\n celo = '0xa4ec', // decimal: 42220\n gnosis = '0x64', // decimal: 100\n fantom = '0xfa', // decimal: 250\n polygon_zkevm = '0x44d', // decimal: 1101\n moonbeam = '0x504', // decimal: 1284\n moonriver = '0x505', // decimal: 1285\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 * 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;AAUb,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,IACA;AAAA,EACF;AACA,QAAM,kBAAkB,KAAK,OAAO,CAAC,OAAO,QAAQ;AAClD,QAAI,eAAe,GAAG,KAAK,eAAe,GAAG,MAAM,IAAI,GAAG,GAAG;AAC3D,aAAO,QAAQ;AAAA,IACjB;AACA,WAAO;AAAA,EACT,GAAG,CAAC;AACJ,SAAO,kBAAkB;AAC3B;AAEA,IAAM,sBAA8C;AAAA,EAClD,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,KAAK;AAAA,EACL,WAAW;AAAA,EACX,WAAW;AAAA,EACX,SAAS;AAAA,EACT,UAAU;AAAA,EACV,KAAK;AAAA,EACL,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,WAAW;AAAA,EACX,OAAO;AAAA,EACP,SAAS;AAAA,EACT,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,iBAAiB;AAAA,EACjB,UAAU;AAAA,EACV,WAAW;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AACT;AAiBA,eAAsB,wBAGpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GASoB;AAClB,QAAM,UAAU,kBAAkB,QAAQ,EAAE,UAAU,CAAC;AACvD,MAAI,gBAAgB;AACpB,aAAW,CAAC,OAAO,KAAK,KAAK,QAAQ,QAAQ,GAAG;AAC9C,oBAAgB,MAAM,UAAU,eAAe,OAAO,KAAK;AAAA,EAC7D;AAGA,QAAM,cAAc;AACpB,SAAO;AACT;AAYA,eAAsB,gCAAgC;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAKmC;AACjC,QAAM,qBACJ,mBAAmB,yBAAyB,OAAO;AACrD,QAAM,sBACJ,mBAAmB,0BAA0B,cAAc;AAE7D,MAAI,CAAC,sBAAsB,CAAC,qBAAqB;AAC/C,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,4BAA4B,MAAM,wBAGtC;AAAA,IACA,QAAQ,CAAC,GAAG,cAAc,EAAE,KAAK;AAAA,IACjC,WAAW;AAAA,IACX,WAAW,OAAO,8BAA8B,UAAU;AACxD,YAAM,oCACJ,MAAM,mBAAmB,iBAAiB;AAAA,QACxC,gBAAgB;AAAA,QAChB;AAAA,QACA,UAAU;AAAA,MACZ,CAAC;AAEH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,GAAG;AAAA,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"]}
|
package/dist/chunk-QFDTOEYR.js
DELETED
|
@@ -1,253 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
var _chunkZ4BLTVTBjs = require('./chunk-Z4BLTVTB.js');
|
|
7
|
-
|
|
8
|
-
// src/NftDetectionController.ts
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
var _controllerutils = require('@metamask/controller-utils');
|
|
17
|
-
var _pollingcontroller = require('@metamask/polling-controller');
|
|
18
|
-
var DEFAULT_INTERVAL = 18e4;
|
|
19
|
-
var controllerName = "NftDetectionController";
|
|
20
|
-
var BlockaidResultType = /* @__PURE__ */ ((BlockaidResultType2) => {
|
|
21
|
-
BlockaidResultType2["Benign"] = "Benign";
|
|
22
|
-
BlockaidResultType2["Spam"] = "Spam";
|
|
23
|
-
BlockaidResultType2["Warning"] = "Warning";
|
|
24
|
-
BlockaidResultType2["Malicious"] = "Malicious";
|
|
25
|
-
return BlockaidResultType2;
|
|
26
|
-
})(BlockaidResultType || {});
|
|
27
|
-
var _intervalId, _interval, _disabled, _addNft, _getNftState, _stopPolling, stopPolling_fn, _startPolling, startPolling_fn, _onPreferencesControllerStateChange, onPreferencesControllerStateChange_fn, _getOwnerNftApi, getOwnerNftApi_fn, _getOwnerNfts, getOwnerNfts_fn;
|
|
28
|
-
var NftDetectionController = class extends _pollingcontroller.StaticIntervalPollingController {
|
|
29
|
-
/**
|
|
30
|
-
* The controller options
|
|
31
|
-
*
|
|
32
|
-
* @param options - The controller options.
|
|
33
|
-
* @param options.interval - The pooling interval.
|
|
34
|
-
* @param options.messenger - A reference to the messaging system.
|
|
35
|
-
* @param options.disabled - Represents previous value of useNftDetection. Used to detect changes of useNftDetection. Default value is true.
|
|
36
|
-
* @param options.addNft - Add an NFT.
|
|
37
|
-
* @param options.getNftState - Gets the current state of the Assets controller.
|
|
38
|
-
*/
|
|
39
|
-
constructor({
|
|
40
|
-
interval = DEFAULT_INTERVAL,
|
|
41
|
-
messenger,
|
|
42
|
-
disabled = false,
|
|
43
|
-
addNft,
|
|
44
|
-
getNftState
|
|
45
|
-
}) {
|
|
46
|
-
super({
|
|
47
|
-
name: controllerName,
|
|
48
|
-
messenger,
|
|
49
|
-
metadata: {},
|
|
50
|
-
state: {}
|
|
51
|
-
});
|
|
52
|
-
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _stopPolling);
|
|
53
|
-
/**
|
|
54
|
-
* Starts a new polling interval.
|
|
55
|
-
*
|
|
56
|
-
*/
|
|
57
|
-
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _startPolling);
|
|
58
|
-
/**
|
|
59
|
-
* Handles the state change of the preference controller.
|
|
60
|
-
* @param preferencesState - The new state of the preference controller.
|
|
61
|
-
* @param preferencesState.useNftDetection - Boolean indicating user preference on NFT detection.
|
|
62
|
-
*/
|
|
63
|
-
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _onPreferencesControllerStateChange);
|
|
64
|
-
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _getOwnerNftApi);
|
|
65
|
-
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _getOwnerNfts);
|
|
66
|
-
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _intervalId, void 0);
|
|
67
|
-
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _interval, void 0);
|
|
68
|
-
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _disabled, void 0);
|
|
69
|
-
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _addNft, void 0);
|
|
70
|
-
_chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _getNftState, void 0);
|
|
71
|
-
_chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _interval, interval);
|
|
72
|
-
_chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _disabled, disabled);
|
|
73
|
-
_chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _getNftState, getNftState);
|
|
74
|
-
_chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _addNft, addNft);
|
|
75
|
-
this.messagingSystem.subscribe(
|
|
76
|
-
"PreferencesController:stateChange",
|
|
77
|
-
_chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _onPreferencesControllerStateChange, onPreferencesControllerStateChange_fn).bind(this)
|
|
78
|
-
);
|
|
79
|
-
this.setIntervalLength(_chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _interval));
|
|
80
|
-
}
|
|
81
|
-
async _executePoll(networkClientId, options) {
|
|
82
|
-
await this.detectNfts({ networkClientId, userAddress: options.address });
|
|
83
|
-
}
|
|
84
|
-
/**
|
|
85
|
-
* Start polling for the currency rate.
|
|
86
|
-
*/
|
|
87
|
-
async start() {
|
|
88
|
-
if (!this.isMainnet() || _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _disabled)) {
|
|
89
|
-
return;
|
|
90
|
-
}
|
|
91
|
-
await _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _startPolling, startPolling_fn).call(this);
|
|
92
|
-
}
|
|
93
|
-
/**
|
|
94
|
-
* Stop polling for the currency rate.
|
|
95
|
-
*/
|
|
96
|
-
stop() {
|
|
97
|
-
_chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _stopPolling, stopPolling_fn).call(this);
|
|
98
|
-
}
|
|
99
|
-
/**
|
|
100
|
-
* Checks whether network is mainnet or not.
|
|
101
|
-
*
|
|
102
|
-
* @returns Whether current network is mainnet.
|
|
103
|
-
*/
|
|
104
|
-
isMainnet() {
|
|
105
|
-
const { selectedNetworkClientId } = this.messagingSystem.call(
|
|
106
|
-
"NetworkController:getState"
|
|
107
|
-
);
|
|
108
|
-
const {
|
|
109
|
-
configuration: { chainId }
|
|
110
|
-
} = this.messagingSystem.call(
|
|
111
|
-
"NetworkController:getNetworkClientById",
|
|
112
|
-
selectedNetworkClientId
|
|
113
|
-
);
|
|
114
|
-
return chainId === _controllerutils.ChainId.mainnet;
|
|
115
|
-
}
|
|
116
|
-
isMainnetByNetworkClientId(networkClient) {
|
|
117
|
-
return networkClient.configuration.chainId === _controllerutils.ChainId.mainnet;
|
|
118
|
-
}
|
|
119
|
-
/**
|
|
120
|
-
* Triggers asset ERC721 token auto detection on mainnet. Any newly detected NFTs are
|
|
121
|
-
* added.
|
|
122
|
-
*
|
|
123
|
-
* @param options - Options bag.
|
|
124
|
-
* @param options.networkClientId - The network client ID to detect NFTs on.
|
|
125
|
-
* @param options.userAddress - The address to detect NFTs for.
|
|
126
|
-
*/
|
|
127
|
-
async detectNfts(options) {
|
|
128
|
-
const userAddress = options?.userAddress ?? this.messagingSystem.call("PreferencesController:getState").selectedAddress;
|
|
129
|
-
if (!this.isMainnet() || _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _disabled)) {
|
|
130
|
-
return;
|
|
131
|
-
}
|
|
132
|
-
if (!userAddress) {
|
|
133
|
-
return;
|
|
134
|
-
}
|
|
135
|
-
const apiNfts = await _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getOwnerNfts, getOwnerNfts_fn).call(this, userAddress);
|
|
136
|
-
const addNftPromises = apiNfts.map(async (nft) => {
|
|
137
|
-
const {
|
|
138
|
-
tokenId: token_id,
|
|
139
|
-
contract,
|
|
140
|
-
kind,
|
|
141
|
-
image: image_url,
|
|
142
|
-
imageSmall: image_thumbnail_url,
|
|
143
|
-
metadata: { imageOriginal: image_original_url } = {},
|
|
144
|
-
name,
|
|
145
|
-
description,
|
|
146
|
-
attributes,
|
|
147
|
-
topBid,
|
|
148
|
-
lastSale,
|
|
149
|
-
rarityRank,
|
|
150
|
-
rarityScore,
|
|
151
|
-
collection
|
|
152
|
-
} = nft.token;
|
|
153
|
-
let ignored;
|
|
154
|
-
const { ignoredNfts } = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _getNftState).call(this);
|
|
155
|
-
if (ignoredNfts.length > 0) {
|
|
156
|
-
ignored = ignoredNfts.find((c) => {
|
|
157
|
-
return c.address === _controllerutils.toChecksumHexAddress.call(void 0, contract) && c.tokenId === token_id;
|
|
158
|
-
});
|
|
159
|
-
}
|
|
160
|
-
if (!ignored) {
|
|
161
|
-
const nftMetadata = Object.assign(
|
|
162
|
-
{},
|
|
163
|
-
{ name },
|
|
164
|
-
description && { description },
|
|
165
|
-
image_url && { image: image_url },
|
|
166
|
-
image_thumbnail_url && { imageThumbnail: image_thumbnail_url },
|
|
167
|
-
image_original_url && { imageOriginal: image_original_url },
|
|
168
|
-
kind && { standard: kind.toUpperCase() },
|
|
169
|
-
lastSale && { lastSale },
|
|
170
|
-
attributes && { attributes },
|
|
171
|
-
topBid && { topBid },
|
|
172
|
-
rarityRank && { rarityRank },
|
|
173
|
-
rarityScore && { rarityScore },
|
|
174
|
-
collection && { collection }
|
|
175
|
-
);
|
|
176
|
-
await _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _addNft).call(this, contract, token_id, {
|
|
177
|
-
nftMetadata,
|
|
178
|
-
userAddress,
|
|
179
|
-
source: "detected" /* Detected */,
|
|
180
|
-
networkClientId: options?.networkClientId
|
|
181
|
-
});
|
|
182
|
-
}
|
|
183
|
-
});
|
|
184
|
-
await Promise.all(addNftPromises);
|
|
185
|
-
}
|
|
186
|
-
};
|
|
187
|
-
_intervalId = new WeakMap();
|
|
188
|
-
_interval = new WeakMap();
|
|
189
|
-
_disabled = new WeakMap();
|
|
190
|
-
_addNft = new WeakMap();
|
|
191
|
-
_getNftState = new WeakMap();
|
|
192
|
-
_stopPolling = new WeakSet();
|
|
193
|
-
stopPolling_fn = function() {
|
|
194
|
-
if (_chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _intervalId)) {
|
|
195
|
-
clearInterval(_chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _intervalId));
|
|
196
|
-
}
|
|
197
|
-
};
|
|
198
|
-
_startPolling = new WeakSet();
|
|
199
|
-
startPolling_fn = async function() {
|
|
200
|
-
_chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _stopPolling, stopPolling_fn).call(this);
|
|
201
|
-
await this.detectNfts();
|
|
202
|
-
_chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _intervalId, setInterval(async () => {
|
|
203
|
-
await this.detectNfts();
|
|
204
|
-
}, _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _interval)));
|
|
205
|
-
};
|
|
206
|
-
_onPreferencesControllerStateChange = new WeakSet();
|
|
207
|
-
onPreferencesControllerStateChange_fn = function({ useNftDetection }) {
|
|
208
|
-
if (!useNftDetection !== _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _disabled)) {
|
|
209
|
-
_chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _disabled, !useNftDetection);
|
|
210
|
-
if (useNftDetection) {
|
|
211
|
-
this.start();
|
|
212
|
-
} else {
|
|
213
|
-
this.stop();
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
};
|
|
217
|
-
_getOwnerNftApi = new WeakSet();
|
|
218
|
-
getOwnerNftApi_fn = function({ address, next }) {
|
|
219
|
-
return `${_controllerutils.NFT_API_BASE_URL}/users/${address}/tokens?chainIds=1&limit=50&includeTopBid=true&continuation=${next ?? ""}`;
|
|
220
|
-
};
|
|
221
|
-
_getOwnerNfts = new WeakSet();
|
|
222
|
-
getOwnerNfts_fn = async function(address) {
|
|
223
|
-
let nftApiResponse;
|
|
224
|
-
let nfts = [];
|
|
225
|
-
let next;
|
|
226
|
-
do {
|
|
227
|
-
nftApiResponse = await _controllerutils.fetchWithErrorHandling.call(void 0, {
|
|
228
|
-
url: _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getOwnerNftApi, getOwnerNftApi_fn).call(this, { address, next }),
|
|
229
|
-
options: {
|
|
230
|
-
headers: {
|
|
231
|
-
Version: _controllerutils.NFT_API_VERSION
|
|
232
|
-
}
|
|
233
|
-
},
|
|
234
|
-
timeout: _controllerutils.NFT_API_TIMEOUT
|
|
235
|
-
});
|
|
236
|
-
if (!nftApiResponse) {
|
|
237
|
-
return nfts;
|
|
238
|
-
}
|
|
239
|
-
const newNfts = nftApiResponse.tokens?.filter(
|
|
240
|
-
(elm) => elm.token.isSpam === false && (elm.blockaidResult?.result_type ? elm.blockaidResult?.result_type === "Benign" /* Benign */ : true)
|
|
241
|
-
) ?? [];
|
|
242
|
-
nfts = [...nfts, ...newNfts];
|
|
243
|
-
} while (next = nftApiResponse.continuation);
|
|
244
|
-
return nfts;
|
|
245
|
-
};
|
|
246
|
-
var NftDetectionController_default = NftDetectionController;
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
exports.BlockaidResultType = BlockaidResultType; exports.NftDetectionController = NftDetectionController; exports.NftDetectionController_default = NftDetectionController_default;
|
|
253
|
-
//# sourceMappingURL=chunk-QFDTOEYR.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/NftDetectionController.ts"],"names":["BlockaidResultType"],"mappings":";;;;;;;;AAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAQP,SAAS,uCAAuC;AAchD,IAAM,mBAAmB;AAEzB,IAAM,iBAAiB;AAgIhB,IAAK,qBAAL,kBAAKA,wBAAL;AACL,EAAAA,oBAAA,YAAS;AACT,EAAAA,oBAAA,UAAO;AACP,EAAAA,oBAAA,aAAU;AACV,EAAAA,oBAAA,eAAY;AAJF,SAAAA;AAAA,GAAA;AAjKZ;AA8VO,IAAM,yBAAN,cAAqC,gCAI1C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqBA,YAAY;AAAA,IACV,WAAW;AAAA,IACX;AAAA,IACA,WAAW;AAAA,IACX;AAAA,IACA;AAAA,EACF,GAMG;AACD,UAAM;AAAA,MACJ,MAAM;AAAA,MACN;AAAA,MACA,UAAU,CAAC;AAAA,MACX,OAAO,CAAC;AAAA,IACV,CAAC;AAwCH;AAUA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T;AA0FF,IAAO,iCAAQ","sourcesContent":["import type { AddApprovalRequest } from '@metamask/approval-controller';\nimport type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport {\n fetchWithErrorHandling,\n toChecksumHexAddress,\n ChainId,\n NFT_API_BASE_URL,\n NFT_API_VERSION,\n NFT_API_TIMEOUT,\n} from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkClient,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerStateChangeEvent,\n NetworkControllerGetStateAction,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type {\n PreferencesControllerGetStateAction,\n PreferencesControllerStateChangeEvent,\n PreferencesState,\n} from '@metamask/preferences-controller';\n\nimport { Source } from './constants';\nimport {\n type NftController,\n type NftControllerState,\n type NftMetadata,\n} from './NftController';\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst controllerName = 'NftDetectionController';\n\nexport type AllowedActions =\n | AddApprovalRequest\n | NetworkControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | PreferencesControllerGetStateAction;\n\nexport type AllowedEvents =\n | PreferencesControllerStateChangeEvent\n | NetworkControllerStateChangeEvent;\n\nexport type NftDetectionControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n AllowedActions,\n AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\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 */\nexport type 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 */\nexport type 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 tokenCount?: 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 */\nexport type 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 */\nexport type ApiNftCreator = {\n user: { username: string };\n profile_img_url: string;\n address: string;\n};\n\nexport type ReservoirResponse = {\n tokens: TokensResponse[];\n continuation?: string;\n};\n\nexport type TokensResponse = {\n token: TokenResponse;\n ownership: Ownership;\n market?: Market;\n blockaidResult?: Blockaid;\n};\n\nexport enum BlockaidResultType {\n Benign = 'Benign',\n Spam = 'Spam',\n Warning = 'Warning',\n Malicious = 'Malicious',\n}\n\nexport type Blockaid = {\n contract: string;\n chainId: number;\n result_type: BlockaidResultType;\n malicious_score: string;\n attack_types: object;\n};\n\nexport type Market = {\n floorAsk?: FloorAsk;\n topBid?: TopBid;\n};\n\nexport type TokenResponse = {\n chainId: number;\n contract: string;\n tokenId: string;\n kind?: string;\n name?: string;\n image?: string;\n imageSmall?: string;\n imageLarge?: string;\n metadata?: Metadata;\n description?: string;\n supply?: number;\n remainingSupply?: number;\n rarityScore?: number;\n rarity?: number;\n rarityRank?: number;\n media?: string;\n isFlagged?: boolean;\n isSpam?: boolean;\n isNsfw?: boolean;\n metadataDisabled?: boolean;\n lastFlagUpdate?: string;\n lastFlagChange?: string;\n collection?: Collection;\n lastSale?: LastSale;\n topBid?: TopBid;\n lastAppraisalValue?: number;\n attributes?: Attributes[];\n};\n\nexport type TopBid = {\n id?: string;\n price?: Price;\n source?: {\n id?: string;\n domain?: string;\n name?: string;\n icon?: string;\n url?: string;\n };\n};\n\nexport type LastSale = {\n saleId?: string;\n token?: {\n contract?: string;\n tokenId?: string;\n name?: string;\n image?: string;\n collection?: {\n id?: string;\n name?: string;\n };\n };\n orderSource?: string;\n orderSide?: 'ask' | 'bid';\n orderKind?: string;\n orderId?: string;\n from?: string;\n to?: string;\n amount?: string;\n fillSource?: string;\n block?: number;\n txHash?: string;\n logIndex?: number;\n batchIndex?: number;\n timestamp?: number;\n price?: Price;\n washTradingScore?: number;\n royaltyFeeBps?: number;\n marketplaceFeeBps?: number;\n paidFullRoyalty?: boolean;\n feeBreakdown?: FeeBreakdown[];\n isDeleted?: boolean;\n createdAt?: string;\n updatedAt?: string;\n};\n\nexport type FeeBreakdown = {\n kind?: string;\n bps?: number;\n recipient?: string;\n source?: string;\n rawAmount?: string;\n};\n\nexport type Attributes = {\n key?: string;\n kind?: string;\n value: string;\n tokenCount?: number;\n onSaleCount?: number;\n floorAskPrice?: Price | null;\n topBidValue?: number | null;\n createdAt?: string;\n};\n\nexport type Collection = {\n id?: string;\n name?: string;\n slug?: string;\n symbol?: string;\n imageUrl?: string;\n image?: string;\n isSpam?: boolean;\n isNsfw?: boolean;\n creator?: string;\n tokenCount?: string;\n metadataDisabled?: boolean;\n openseaVerificationStatus?: string;\n floorAskPrice?: Price;\n royaltiesBps?: number;\n royalties?: Royalties[];\n};\n\nexport type Royalties = {\n bps?: number;\n recipient?: string;\n};\n\nexport type Ownership = {\n tokenCount?: string;\n onSaleCount?: string;\n floorAsk?: FloorAsk;\n acquiredAt?: string;\n};\n\nexport type FloorAsk = {\n id?: string;\n price?: Price;\n maker?: string;\n kind?: string;\n validFrom?: number;\n validUntil?: number;\n source?: Source;\n rawData?: Metadata;\n isNativeOffChainCancellable?: boolean;\n};\n\nexport type Price = {\n currency?: {\n contract?: string;\n name?: string;\n symbol?: string;\n decimals?: number;\n chainId?: number;\n };\n amount?: {\n raw?: string;\n decimal?: number;\n usd?: number;\n native?: number;\n };\n netAmount?: {\n raw?: string;\n decimal?: number;\n usd?: number;\n native?: number;\n };\n};\n\nexport type Metadata = {\n imageOriginal?: string;\n tokenURI?: string;\n};\n\n/**\n * Controller that passively polls on a set interval for NFT auto detection\n */\nexport class NftDetectionController extends StaticIntervalPollingController<\n typeof controllerName,\n Record<never, never>,\n NftDetectionControllerMessenger\n> {\n #intervalId?: ReturnType<typeof setTimeout>;\n\n #interval: number;\n\n #disabled: boolean;\n\n readonly #addNft: NftController['addNft'];\n\n readonly #getNftState: () => NftControllerState;\n\n /**\n * The controller options\n *\n * @param options - The controller options.\n * @param options.interval - The pooling interval.\n * @param options.messenger - A reference to the messaging system.\n * @param options.disabled - Represents previous value of useNftDetection. Used to detect changes of useNftDetection. Default value is true.\n * @param options.addNft - Add an NFT.\n * @param options.getNftState - Gets the current state of the Assets controller.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n messenger,\n disabled = false,\n addNft,\n getNftState,\n }: {\n interval?: number;\n messenger: NftDetectionControllerMessenger;\n disabled: boolean;\n addNft: NftController['addNft'];\n getNftState: () => NftControllerState;\n }) {\n super({\n name: controllerName,\n messenger,\n metadata: {},\n state: {},\n });\n this.#interval = interval;\n this.#disabled = disabled;\n\n this.#getNftState = getNftState;\n this.#addNft = addNft;\n\n this.messagingSystem.subscribe(\n 'PreferencesController:stateChange',\n this.#onPreferencesControllerStateChange.bind(this),\n );\n\n this.setIntervalLength(this.#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 #stopPolling() {\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n }\n }\n\n /**\n * Starts a new polling interval.\n *\n */\n async #startPolling(): Promise<void> {\n this.#stopPolling();\n await this.detectNfts();\n this.#intervalId = setInterval(async () => {\n await this.detectNfts();\n }, this.#interval);\n }\n\n /**\n * Checks whether network is mainnet or not.\n *\n * @returns Whether current network is mainnet.\n */\n isMainnet(): boolean {\n const { selectedNetworkClientId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n const {\n configuration: { chainId },\n } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n return chainId === ChainId.mainnet;\n }\n\n isMainnetByNetworkClientId(networkClient: NetworkClient): boolean {\n return networkClient.configuration.chainId === ChainId.mainnet;\n }\n\n /**\n * Handles the state change of the preference controller.\n * @param preferencesState - The new state of the preference controller.\n * @param preferencesState.useNftDetection - Boolean indicating user preference on NFT detection.\n */\n #onPreferencesControllerStateChange({ useNftDetection }: PreferencesState) {\n if (!useNftDetection !== this.#disabled) {\n this.#disabled = !useNftDetection;\n if (useNftDetection) {\n this.start();\n } else {\n this.stop();\n }\n }\n }\n\n #getOwnerNftApi({ address, next }: { address: string; next?: string }) {\n return `${NFT_API_BASE_URL}/users/${address}/tokens?chainIds=1&limit=50&includeTopBid=true&continuation=${\n next ?? ''\n }`;\n }\n\n async #getOwnerNfts(address: string) {\n let nftApiResponse: ReservoirResponse;\n let nfts: TokensResponse[] = [];\n let next;\n\n do {\n nftApiResponse = await fetchWithErrorHandling({\n url: this.#getOwnerNftApi({ address, next }),\n options: {\n headers: {\n Version: NFT_API_VERSION,\n },\n },\n timeout: NFT_API_TIMEOUT,\n });\n\n if (!nftApiResponse) {\n return nfts;\n }\n\n const newNfts =\n nftApiResponse.tokens?.filter(\n (elm) =>\n elm.token.isSpam === false &&\n (elm.blockaidResult?.result_type\n ? elm.blockaidResult?.result_type === BlockaidResultType.Benign\n : true),\n ) ?? [];\n\n nfts = [...nfts, ...newNfts];\n } while ((next = nftApiResponse.continuation));\n\n return nfts;\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(options?: {\n networkClientId?: NetworkClientId;\n userAddress?: string;\n }) {\n const userAddress =\n options?.userAddress ??\n this.messagingSystem.call('PreferencesController:getState')\n .selectedAddress;\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) => {\n const {\n tokenId: token_id,\n contract,\n kind,\n image: image_url,\n imageSmall: image_thumbnail_url,\n metadata: { imageOriginal: image_original_url } = {},\n name,\n description,\n attributes,\n topBid,\n lastSale,\n rarityRank,\n rarityScore,\n collection,\n } = nft.token;\n\n let ignored;\n /* istanbul ignore else */\n const { ignoredNfts } = this.#getNftState();\n if (ignoredNfts.length > 0) {\n ignored = ignoredNfts.find((c) => {\n /* istanbul ignore next */\n return (\n c.address === toChecksumHexAddress(contract) &&\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 description && { description },\n image_url && { image: image_url },\n image_thumbnail_url && { imageThumbnail: image_thumbnail_url },\n image_original_url && { imageOriginal: image_original_url },\n kind && { standard: kind.toUpperCase() },\n lastSale && { lastSale },\n attributes && { attributes },\n topBid && { topBid },\n rarityRank && { rarityRank },\n rarityScore && { rarityScore },\n collection && { collection },\n );\n\n await this.#addNft(contract, token_id, {\n nftMetadata,\n userAddress,\n source: Source.Detected,\n networkClientId: options?.networkClientId,\n });\n }\n });\n await Promise.all(addNftPromises);\n }\n}\n\nexport default NftDetectionController;\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/AssetsContractController.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,oBAAoB;AAE7B,SAAS,wBAAwB;AACjC,SAAS,gCAAgC;AAUzC,OAAO,mCAAmC;AAanC,IAAM,0CAA+D;AAAA,EAC1E,oBAAwC,GACtC;AAAA,EACF,iBAAoC,GAClC;AAAA,EACF,qBAAwC,GACtC;AAAA,EACF,oBAAqC,GACnC;AAAA,EACF,0BAAuC,GACrC;AAAA,EACF,4BAA6C,GAC3C;AAAA,EACF,6BAA8C,GAC5C;AAAA,EACF,wBAAyC,GACvC;AAAA,EACF,qBAAyC,GACvC;AAAA,EACF,oBAAqC,GACnC;AAAA,EACF,qBAAuC,GACrC;AAAA,EACF,oBAAuC,GACrC;AAAA,EACF,oBAAqC,GACnC;AAAA,EACF,oBAAuC,GACrC;AAAA,EACF,oBAAuC,GACrC;AAAA,EACF,4BAA8C,GAC5C;AAAA,EACF,uBAAyC,GACvC;AAAA,EACF,wBAA0C,GACxC;AACJ;AAEO,IAAM,yBACX;AAiCK,IAAM,2BAAN,cAAuC,iBAG5C;AAAA;AAAA;AAAA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I;AAAA,QAClC;AAAA,MACF,CAAC;AAAA,IACH;AACA,WAAO;AAAA,EACT;AACF;AAEA,IAAO,mCAAQ","sourcesContent":["import { Contract } from '@ethersproject/contracts';\nimport { Web3Provider } from '@ethersproject/providers';\nimport type { BaseConfig, BaseState } from '@metamask/base-controller';\nimport { BaseControllerV1 } from '@metamask/base-controller';\nimport { IPFS_DEFAULT_GATEWAY_URL } from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkState,\n NetworkController,\n Provider,\n} from '@metamask/network-controller';\nimport type { PreferencesState } from '@metamask/preferences-controller';\nimport type { Hex } from '@metamask/utils';\nimport type BN from 'bn.js';\nimport abiSingleCallBalancesContract from 'single-call-balance-checker-abi';\n\nimport { SupportedTokenDetectionNetworks } from './assetsUtil';\nimport { ERC20Standard } from './Standards/ERC20Standard';\nimport { ERC1155Standard } from './Standards/NftStandards/ERC1155/ERC1155Standard';\nimport { ERC721Standard } from './Standards/NftStandards/ERC721/ERC721Standard';\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 const SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID: Record<Hex, string> = {\n [SupportedTokenDetectionNetworks.mainnet]:\n '0xb1f8e55c7f64d203c1400b9d8555d050f94adf39',\n [SupportedTokenDetectionNetworks.bsc]:\n '0x2352c63A83f9Fd126af8676146721Fa00924d7e4',\n [SupportedTokenDetectionNetworks.polygon]:\n '0x2352c63A83f9Fd126af8676146721Fa00924d7e4',\n [SupportedTokenDetectionNetworks.avax]:\n '0xD023D153a0DFa485130ECFdE2FAA7e612EF94818',\n [SupportedTokenDetectionNetworks.aurora]:\n '0x1286415D333855237f89Df27D388127181448538',\n [SupportedTokenDetectionNetworks.linea_goerli]:\n '0x10dAd7Ca3921471f616db788D9300DC97Db01783',\n [SupportedTokenDetectionNetworks.linea_mainnet]:\n '0xF62e6a41561b3650a69Bb03199C735e3E3328c0D',\n [SupportedTokenDetectionNetworks.arbitrum]:\n '0x151E24A486D7258dd7C33Fb67E4bB01919B7B32c',\n [SupportedTokenDetectionNetworks.optimism]:\n '0xB1c568e9C3E6bdaf755A60c7418C269eb11524FC',\n [SupportedTokenDetectionNetworks.base]:\n '0x6AA75276052D96696134252587894ef5FFA520af',\n [SupportedTokenDetectionNetworks.zksync]:\n '0x458fEd3144680a5b8bcfaa0F9594aa19B4Ea2D34',\n [SupportedTokenDetectionNetworks.cronos]:\n '0x768ca200f0fc702ac9ea502498c18f5eff176378',\n [SupportedTokenDetectionNetworks.celo]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.gnosis]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.fantom]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.polygon_zkevm]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.moonbeam]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.moonriver]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n};\n\nexport const MISSING_PROVIDER_ERROR =\n 'AssetsContractController failed to set the provider correctly. A provider must be set for this method to be available';\n\n/**\n * @type AssetsContractConfig\n *\n * Assets Contract controller configuration\n * @property provider - Provider used to create a new web3 instance\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 AssetsContractConfig extends BaseConfig {\n provider: Provider | undefined;\n ipfsGateway: string;\n chainId: Hex;\n}\n\n/**\n * @type BalanceMap\n *\n * Key value object containing the balance for each tokenAddress\n * @property [tokenAddress] - Address of the token\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 BalanceMap {\n [tokenAddress: string]: BN;\n}\n\n/**\n * Controller that interacts with contracts on mainnet through web3\n */\nexport class AssetsContractController extends BaseControllerV1<\n AssetsContractConfig,\n BaseState\n> {\n private _provider?: Provider;\n\n /**\n * Name of this controller used during composition\n */\n override name = 'AssetsContractController' as const;\n\n private readonly getNetworkClientById: NetworkController['getNetworkClientById'];\n\n /**\n * Creates a AssetsContractController instance.\n *\n * @param options - The controller options.\n * @param options.chainId - The chain ID of the current network.\n * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.\n * @param options.onNetworkDidChange - Allows subscribing to network controller networkDidChange events.\n * @param options.getNetworkClientById - Gets the network client with the given 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 onPreferencesStateChange,\n onNetworkDidChange,\n getNetworkClientById,\n }: {\n chainId: Hex;\n onPreferencesStateChange: (\n listener: (preferencesState: PreferencesState) => void,\n ) => void;\n onNetworkDidChange: (\n listener: (networkState: NetworkState) => void,\n ) => void;\n getNetworkClientById: NetworkController['getNetworkClientById'];\n },\n config?: Partial<AssetsContractConfig>,\n state?: Partial<BaseState>,\n ) {\n super(config, state);\n this.defaultConfig = {\n provider: undefined,\n ipfsGateway: IPFS_DEFAULT_GATEWAY_URL,\n chainId: initialChainId,\n };\n this.initialize();\n this.getNetworkClientById = getNetworkClientById;\n\n onPreferencesStateChange(({ ipfsGateway }) => {\n this.configure({ ipfsGateway });\n });\n\n onNetworkDidChange((networkState) => {\n if (this.config.chainId !== networkState.providerConfig.chainId) {\n this.configure({\n chainId: networkState.providerConfig.chainId,\n });\n }\n });\n }\n\n /**\n * Sets a new provider.\n *\n * TODO: Replace this wth a method.\n *\n * @property provider - Provider used to create a new underlying Web3 instance\n */\n set provider(provider: Provider) {\n this._provider = provider;\n }\n\n get provider() {\n throw new Error('Property only used for setting');\n }\n\n /**\n * Get the relevant provider instance.\n *\n * @param networkClientId - Network Client ID.\n * @returns Web3Provider instance.\n */\n getProvider(networkClientId?: NetworkClientId): Web3Provider {\n const provider = networkClientId\n ? this.getNetworkClientById(networkClientId).provider\n : this._provider;\n\n if (provider === undefined) {\n throw new Error(MISSING_PROVIDER_ERROR);\n }\n\n // @ts-expect-error TODO: remove this annotation once the `Eip1193Provider` class is released\n return new Web3Provider(provider);\n }\n\n /**\n * Get the relevant chain ID.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns Hex chain ID.\n */\n getChainId(networkClientId?: NetworkClientId): Hex {\n return networkClientId\n ? this.getNetworkClientById(networkClientId).configuration.chainId\n : this.config.chainId;\n }\n\n /**\n * Get a ERC20Standard instance using the relevant provider instance.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns ERC20Standard instance.\n */\n getERC20Standard(networkClientId?: NetworkClientId): ERC20Standard {\n const provider = this.getProvider(networkClientId);\n return new ERC20Standard(provider);\n }\n\n /**\n * Get a ERC721Standard instance using the relevant provider instance.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns ERC721Standard instance.\n */\n getERC721Standard(networkClientId?: NetworkClientId): ERC721Standard {\n const provider = this.getProvider(networkClientId);\n return new ERC721Standard(provider);\n }\n\n /**\n * Get a ERC1155Standard instance using the relevant provider instance.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns ERC1155Standard instance.\n */\n getERC1155Standard(networkClientId?: NetworkClientId): ERC1155Standard {\n const provider = this.getProvider(networkClientId);\n return new ERC1155Standard(provider);\n }\n\n /**\n * Get balance or count for current account on specific asset contract.\n *\n * @param address - Asset ERC20 contract address.\n * @param selectedAddress - Current account public address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to BN object containing balance for current account on specific asset contract.\n */\n async getERC20BalanceOf(\n address: string,\n selectedAddress: string,\n networkClientId?: NetworkClientId,\n ): Promise<BN> {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return erc20Standard.getBalanceOf(address, selectedAddress);\n }\n\n /**\n * Query for the decimals for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'decimals'.\n */\n async getERC20TokenDecimals(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return erc20Standard.getTokenDecimals(address);\n }\n\n /**\n * Query for the name for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'decimals'.\n */\n async getERC20TokenName(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return erc20Standard.getTokenName(address);\n }\n\n /**\n * Enumerate assets assigned to an owner.\n *\n * @param address - ERC721 asset contract address.\n * @param selectedAddress - Current account public address.\n * @param index - An NFT counter less than `balanceOf(selectedAddress)`.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to token identifier for the 'index'th asset assigned to 'selectedAddress'.\n */\n getERC721NftTokenId(\n address: string,\n selectedAddress: string,\n index: number,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getNftTokenId(address, selectedAddress, index);\n }\n\n /**\n * Enumerate assets assigned to an owner.\n *\n * @param tokenAddress - ERC721 asset contract address.\n * @param userAddress - Current account public address.\n * @param tokenId - ERC721 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to an object containing the token standard and a set of details which depend on which standard the token supports.\n */\n async getTokenStandardAndDetails(\n tokenAddress: string,\n userAddress?: string,\n tokenId?: string,\n networkClientId?: NetworkClientId,\n ): Promise<{\n standard: string;\n tokenURI?: string | undefined;\n symbol?: string | undefined;\n name?: string | undefined;\n decimals?: string | undefined;\n balance?: BN | undefined;\n }> {\n // Asserts provider is available\n this.getProvider(networkClientId);\n\n const { ipfsGateway } = this.config;\n\n // ERC721\n try {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return {\n ...(await erc721Standard.getDetails(\n tokenAddress,\n ipfsGateway,\n tokenId,\n )),\n };\n } catch {\n // Ignore\n }\n\n // ERC1155\n try {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return {\n ...(await erc1155Standard.getDetails(\n tokenAddress,\n ipfsGateway,\n tokenId,\n )),\n };\n } catch {\n // Ignore\n }\n\n // ERC20\n try {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return {\n ...(await erc20Standard.getDetails(tokenAddress, userAddress)),\n };\n } catch {\n // Ignore\n }\n\n throw new Error('Unable to determine contract standard');\n }\n\n /**\n * Query for tokenURI for a given ERC721 asset.\n *\n * @param address - ERC721 asset contract address.\n * @param tokenId - ERC721 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'tokenURI'.\n */\n async getERC721TokenURI(\n address: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getTokenURI(address, tokenId);\n }\n\n /**\n * Query for name for a given asset.\n *\n * @param address - ERC721 or ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'name'.\n */\n async getERC721AssetName(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getAssetName(address);\n }\n\n /**\n * Query for symbol for a given asset.\n *\n * @param address - ERC721 or ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'symbol'.\n */\n async getERC721AssetSymbol(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getAssetSymbol(address);\n }\n\n /**\n * Query for owner for a given ERC721 asset.\n *\n * @param address - ERC721 asset contract address.\n * @param tokenId - ERC721 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the owner address.\n */\n async getERC721OwnerOf(\n address: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getOwnerOf(address, tokenId);\n }\n\n /**\n * Query for tokenURI for a given asset.\n *\n * @param address - ERC1155 asset contract address.\n * @param tokenId - ERC1155 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'tokenURI'.\n */\n async getERC1155TokenURI(\n address: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return erc1155Standard.getTokenURI(address, tokenId);\n }\n\n /**\n * Query for balance of a given ERC 1155 token.\n *\n * @param userAddress - Wallet public address.\n * @param nftAddress - ERC1155 asset contract address.\n * @param nftId - ERC1155 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'balanceOf'.\n */\n async getERC1155BalanceOf(\n userAddress: string,\n nftAddress: string,\n nftId: string,\n networkClientId?: NetworkClientId,\n ): Promise<BN> {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return erc1155Standard.getBalanceOf(nftAddress, userAddress, nftId);\n }\n\n /**\n * Transfer single ERC1155 token.\n *\n * @param nftAddress - ERC1155 token address.\n * @param senderAddress - ERC1155 token sender.\n * @param recipientAddress - ERC1155 token recipient.\n * @param nftId - ERC1155 token id.\n * @param qty - Quantity of tokens to be sent.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'transferSingle' ERC1155 token.\n */\n async transferSingleERC1155(\n nftAddress: string,\n senderAddress: string,\n recipientAddress: string,\n nftId: string,\n qty: string,\n networkClientId?: NetworkClientId,\n ): Promise<void> {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return erc1155Standard.transferSingle(\n nftAddress,\n senderAddress,\n recipientAddress,\n nftId,\n qty,\n );\n }\n\n /**\n * Get the token balance for a list of token addresses in a single call. Only non-zero balances\n * are returned.\n *\n * @param selectedAddress - The address to check token balances for.\n * @param tokensToDetect - The token addresses to detect balances for.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns The list of non-zero token balances.\n */\n async getBalancesInSingleCall(\n selectedAddress: string,\n tokensToDetect: string[],\n networkClientId?: NetworkClientId,\n ) {\n const chainId = this.getChainId(networkClientId);\n const provider = this.getProvider(networkClientId);\n if (!(chainId in SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID)) {\n // Only fetch balance if contract address exists\n return {};\n }\n const contractAddress = SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID[chainId];\n\n const contract = new Contract(\n contractAddress,\n abiSingleCallBalancesContract,\n provider,\n );\n const result = await contract.balances([selectedAddress], tokensToDetect);\n const nonZeroBalances: BalanceMap = {};\n /* istanbul ignore else */\n if (result.length > 0) {\n tokensToDetect.forEach((tokenAddress, index) => {\n const balance: BN = result[index];\n /* istanbul ignore else */\n if (String(balance) !== '0') {\n nonZeroBalances[tokenAddress] = balance;\n }\n });\n }\n return nonZeroBalances;\n }\n}\n\nexport default AssetsContractController;\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/TokenRatesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,yCAAyC;AAElD,SAAS,6BAAuC;AAChD,SAAS,eAAe;AAkHxB,eAAe,0BAA0B;AAAA,EACvC;AAAA,EACA;AACF,GAGG;AACD,QAAM,iBAAiB;AACvB,MAAI;AACF,UAAM,SAAS,MAAM;AAAA,MACnB;AAAA,MACA;AAAA,MACA;AAAA,IACF;AACA,WAAO,OAAO;AAAA,EAChB,SAAS,OAAO;AACd,QACE,iBAAiB,SACjB,MAAM,QAAQ,SAAS,0CAA0C,GACjE;AACA,aAAO;AAAA,IACT;AACA,UAAM;AAAA,EACR;AACF;AAzJA;AA+JO,IAAM,uBAAN,cAAmC,kCAGxC;AAAA;AAAA;AAAA;AAAA;A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AAC;AAAA,EACH,CAAC;AAED,MAAI,mDAAmD,MAAM;AAC3D,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,+BAA+B,OAAO;AAAA,IAC1C;AAAA,EACF,EAAE,OAAO,CAAC,KAAK,CAAC,cAAc,KAAK,MAAM;AACvC,UAAM;AAAA,MACJ,GAAG;AAAA,MACH,CAAC,YAAY,GAAG;AAAA,QACd,GAAG;AAAA,QACH,OAAO,MAAM,QACT,MAAM,QAAQ,iDACd;AAAA,MACN;AAAA,IACF;AACA,WAAO;AAAA,EACT,GAAG,CAAC,CAAC;AAEL,SAAO;AACT;AAGF,IAAO,+BAAQ","sourcesContent":["import type { BaseConfig, BaseState } from '@metamask/base-controller';\nimport {\n safelyExecute,\n toChecksumHexAddress,\n FALL_BACK_VS_CURRENCY,\n toHex,\n} from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkController,\n NetworkState,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingControllerV1 } from '@metamask/polling-controller';\nimport type { PreferencesState } from '@metamask/preferences-controller';\nimport { createDeferredPromise, type Hex } from '@metamask/utils';\nimport { isEqual } from 'lodash';\n\nimport { reduceInBatchesSerially, TOKEN_PRICES_BATCH_SIZE } from './assetsUtil';\nimport { fetchExchangeRate as fetchNativeCurrencyExchangeRate } from './crypto-compare-service';\nimport type { AbstractTokenPricesService } from './token-prices-service/abstract-token-prices-service';\nimport { ZERO_ADDRESS } from './token-prices-service/codefi-v2';\nimport type { TokensControllerState } from './TokensController';\n\n/**\n * @type Token\n *\n * Token representation\n * @property address - Hex address of the token contract\n * @property decimals - Number of decimals the token uses\n * @property symbol - Symbol of the token\n * @property image - Image of the token, url or bit32 image\n */\n\nexport type Token = {\n address: string;\n decimals: number;\n symbol: string;\n aggregators?: string[];\n image?: string;\n hasBalanceError?: boolean;\n isERC721?: boolean;\n name?: string;\n};\n\n/**\n * @type TokenRatesConfig\n *\n * Token rates controller configuration\n * @property interval - Polling interval used to fetch new token rates\n * @property nativeCurrency - Current native currency selected to use base of rates\n * @property chainId - Current network chainId\n * @property tokens - List of tokens to track exchange rates for\n * @property threshold - Threshold to invalidate the supportedChains\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 TokenRatesConfig extends BaseConfig {\n interval: number;\n nativeCurrency: string;\n chainId: Hex;\n selectedAddress: string;\n allTokens: { [chainId: Hex]: { [key: string]: Token[] } };\n allDetectedTokens: { [chainId: Hex]: { [key: string]: Token[] } };\n threshold: number;\n}\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 ContractExchangeRates {\n [address: string]: number | undefined;\n}\n\ntype MarketDataDetails = {\n tokenAddress: `0x${string}`;\n value: number;\n currency: string;\n allTimeHigh: number;\n allTimeLow: number;\n circulatingSupply: number;\n dilutedMarketCap: number;\n high1d: number;\n low1d: number;\n marketCap: number;\n marketCapPercentChange1d: number;\n price: number;\n priceChange1d: number;\n pricePercentChange1d: number;\n pricePercentChange1h: number;\n pricePercentChange1y: number;\n pricePercentChange7d: number;\n pricePercentChange14d: number;\n pricePercentChange30d: number;\n pricePercentChange200d: number;\n totalVolume: number;\n};\n\nexport type ContractMarketData = Record<Hex, MarketDataDetails>;\n\nenum PollState {\n Active = 'Active',\n Inactive = 'Inactive',\n}\n\n/**\n * @type TokenRatesState\n *\n * Token rates controller state\n * @property marketData - Market data for tokens, keyed by chain ID and then token contract 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 TokenRatesState extends BaseState {\n marketData: Record<Hex, Record<Hex, MarketDataDetails>>;\n}\n\n/**\n * Uses the CryptoCompare API to fetch the exchange rate between one currency\n * and another, i.e., the multiplier to apply the amount of one currency in\n * order to convert it to another.\n *\n * @param args - The arguments to this function.\n * @param args.from - The currency to convert from.\n * @param args.to - The currency to convert to.\n * @returns The exchange rate between `fromCurrency` to `toCurrency` if one\n * exists, or null if one does not.\n */\nasync function getCurrencyConversionRate({\n from,\n to,\n}: {\n from: string;\n to: string;\n}) {\n const includeUSDRate = false;\n try {\n const result = await fetchNativeCurrencyExchangeRate(\n to,\n from,\n includeUSDRate,\n );\n return result.conversionRate;\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes('market does not exist for this coin pair')\n ) {\n return null;\n }\n throw error;\n }\n}\n\n/**\n * Controller that passively polls on a set interval for token-to-fiat exchange rates\n * for tokens stored in the TokensController\n */\nexport class TokenRatesController extends StaticIntervalPollingControllerV1<\n TokenRatesConfig,\n TokenRatesState\n> {\n private handle?: ReturnType<typeof setTimeout>;\n\n #pollState = PollState.Inactive;\n\n #tokenPricesService: AbstractTokenPricesService;\n\n #inProcessExchangeRateUpdates: Record<`${Hex}:${string}`, Promise<void>> = {};\n\n /**\n * Name of this controller used during composition\n */\n override name = 'TokenRatesController' as const;\n\n private readonly getNetworkClientById: NetworkController['getNetworkClientById'];\n\n /**\n * Creates a TokenRatesController instance.\n *\n * @param options - The controller options.\n * @param options.interval - The polling interval in ms\n * @param options.threshold - The duration in ms before metadata fetched from CoinGecko is considered stale\n * @param options.getNetworkClientById - Gets the network client with the given id from the NetworkController.\n * @param options.chainId - The chain ID of the current network.\n * @param options.ticker - The ticker for the current network.\n * @param options.selectedAddress - The current selected address.\n * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.\n * @param options.onTokensStateChange - Allows subscribing to token controller state changes.\n * @param options.onNetworkStateChange - Allows subscribing to network state changes.\n * @param options.tokenPricesService - An object in charge of retrieving token prices.\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 interval = 3 * 60 * 1000,\n threshold = 6 * 60 * 60 * 1000,\n getNetworkClientById,\n chainId: initialChainId,\n ticker: initialTicker,\n selectedAddress: initialSelectedAddress,\n onPreferencesStateChange,\n onTokensStateChange,\n onNetworkStateChange,\n tokenPricesService,\n }: {\n interval?: number;\n threshold?: number;\n getNetworkClientById: NetworkController['getNetworkClientById'];\n chainId: Hex;\n ticker: string;\n selectedAddress: string;\n onPreferencesStateChange: (\n listener: (preferencesState: PreferencesState) => void,\n ) => void;\n onTokensStateChange: (\n listener: (tokensState: TokensControllerState) => void,\n ) => void;\n onNetworkStateChange: (\n listener: (networkState: NetworkState) => void,\n ) => void;\n tokenPricesService: AbstractTokenPricesService;\n },\n config?: Partial<TokenRatesConfig>,\n state?: Partial<TokenRatesState>,\n ) {\n super(config, state);\n this.defaultConfig = {\n interval,\n threshold,\n disabled: false,\n nativeCurrency: initialTicker,\n chainId: initialChainId,\n selectedAddress: initialSelectedAddress,\n allTokens: {}, // TODO: initialize these correctly, maybe as part of BaseControllerV2 migration\n allDetectedTokens: {},\n };\n\n this.defaultState = {\n marketData: {},\n };\n this.initialize();\n this.setIntervalLength(interval);\n this.getNetworkClientById = getNetworkClientById;\n this.#tokenPricesService = tokenPricesService;\n\n if (config?.disabled) {\n this.configure({ disabled: true }, false, false);\n }\n\n onPreferencesStateChange(async ({ selectedAddress }) => {\n if (this.config.selectedAddress !== selectedAddress) {\n this.configure({ selectedAddress });\n if (this.#pollState === PollState.Active) {\n await this.updateExchangeRates();\n }\n }\n });\n\n onTokensStateChange(async ({ allTokens, allDetectedTokens }) => {\n const previousTokenAddresses = this.#getTokenAddresses(\n this.config.chainId,\n );\n this.configure({ allTokens, allDetectedTokens });\n const newTokenAddresses = this.#getTokenAddresses(this.config.chainId);\n if (\n !isEqual(previousTokenAddresses, newTokenAddresses) &&\n this.#pollState === PollState.Active\n ) {\n await this.updateExchangeRates();\n }\n });\n\n onNetworkStateChange(async ({ selectedNetworkClientId }) => {\n const selectedNetworkClient = getNetworkClientById(\n selectedNetworkClientId,\n );\n const { chainId, ticker } = selectedNetworkClient.configuration;\n\n if (\n this.config.chainId !== chainId ||\n this.config.nativeCurrency !== ticker\n ) {\n this.update({ ...this.defaultState });\n this.configure({ chainId, nativeCurrency: ticker });\n if (this.#pollState === PollState.Active) {\n await this.updateExchangeRates();\n }\n }\n });\n }\n\n /**\n * Get the user's tokens for the given chain.\n *\n * @param chainId - The chain ID.\n * @returns The list of tokens addresses for the current chain\n */\n #getTokenAddresses(chainId: Hex): Hex[] {\n const { allTokens, allDetectedTokens } = this.config;\n const tokens = allTokens[chainId]?.[this.config.selectedAddress] || [];\n const detectedTokens =\n allDetectedTokens[chainId]?.[this.config.selectedAddress] || [];\n\n return [\n ...new Set(\n [...tokens, ...detectedTokens].map((token) =>\n toHex(toChecksumHexAddress(token.address)),\n ),\n ),\n ].sort();\n }\n\n /**\n * Start (or restart) polling.\n */\n async start() {\n this.#stopPoll();\n this.#pollState = PollState.Active;\n await this.#poll();\n }\n\n /**\n * Stop polling.\n */\n stop() {\n this.#stopPoll();\n this.#pollState = PollState.Inactive;\n }\n\n /**\n * Clear the active polling timer, if present.\n */\n #stopPoll() {\n if (this.handle) {\n clearTimeout(this.handle);\n }\n }\n\n /**\n * Poll for exchange rate updates.\n */\n async #poll() {\n await safelyExecute(() => this.updateExchangeRates());\n\n // Poll using recursive `setTimeout` instead of `setInterval` so that\n // requests don't stack if they take longer than the polling interval\n this.handle = setTimeout(() => {\n this.#poll();\n }, this.config.interval);\n }\n\n /**\n * Updates exchange rates for all tokens.\n */\n async updateExchangeRates() {\n const { chainId, nativeCurrency } = this.config;\n await this.updateExchangeRatesByChainId({\n chainId,\n nativeCurrency,\n });\n }\n\n /**\n * Updates exchange rates for all tokens.\n *\n * @param options - The options to fetch exchange rates.\n * @param options.chainId - The chain ID.\n * @param options.nativeCurrency - The ticker for the chain.\n */\n async updateExchangeRatesByChainId({\n chainId,\n nativeCurrency,\n }: {\n chainId: Hex;\n nativeCurrency: string;\n }) {\n if (this.disabled) {\n return;\n }\n\n const tokenAddresses = this.#getTokenAddresses(chainId);\n\n const updateKey: `${Hex}:${string}` = `${chainId}:${nativeCurrency}`;\n if (updateKey in this.#inProcessExchangeRateUpdates) {\n // This prevents redundant updates\n // This promise is resolved after the in-progress update has finished,\n // and state has been updated.\n await this.#inProcessExchangeRateUpdates[updateKey];\n return;\n }\n\n const {\n promise: inProgressUpdate,\n resolve: updateSucceeded,\n reject: updateFailed,\n } = createDeferredPromise({ suppressUnhandledRejection: true });\n this.#inProcessExchangeRateUpdates[updateKey] = inProgressUpdate;\n\n try {\n const contractInformations = await this.#fetchAndMapExchangeRates({\n tokenAddresses,\n chainId,\n nativeCurrency,\n });\n\n const marketData = {\n [chainId]: {\n ...(contractInformations ?? {}),\n },\n };\n\n this.update({\n marketData,\n });\n updateSucceeded();\n } catch (error: unknown) {\n updateFailed(error);\n throw error;\n } finally {\n delete this.#inProcessExchangeRateUpdates[updateKey];\n }\n }\n\n /**\n * Uses the token prices service to retrieve exchange rates for tokens in a\n * particular currency.\n *\n * If the price API does not support the given chain ID, returns an empty\n * object.\n *\n * If the price API does not support the given currency, retrieves exchange\n * rates in a known currency instead, then converts those rates using the\n * exchange rate between the known currency and desired currency.\n *\n * @param args - The arguments to this function.\n * @param args.tokenAddresses - Addresses for tokens.\n * @param args.chainId - The EIP-155 ID of the chain where the tokens live.\n * @param args.nativeCurrency - The native currency in which to request\n * exchange rates.\n * @returns A map from token address to its exchange rate in the native\n * currency, or an empty map if no exchange rates can be obtained for the\n * chain ID.\n */\n async #fetchAndMapExchangeRates({\n tokenAddresses,\n chainId,\n nativeCurrency,\n }: {\n tokenAddresses: Hex[];\n chainId: Hex;\n nativeCurrency: string;\n }): Promise<ContractMarketData> {\n if (!this.#tokenPricesService.validateChainIdSupported(chainId)) {\n return tokenAddresses.reduce((obj, tokenAddress) => {\n obj = {\n ...obj,\n [tokenAddress]: undefined,\n };\n\n return obj;\n }, {});\n }\n\n if (this.#tokenPricesService.validateCurrencySupported(nativeCurrency)) {\n return await this.#fetchAndMapExchangeRatesForSupportedNativeCurrency({\n tokenAddresses,\n chainId,\n nativeCurrency,\n });\n }\n return await this.#fetchAndMapExchangeRatesForUnsupportedNativeCurrency({\n tokenAddresses,\n nativeCurrency,\n });\n }\n\n /**\n * Updates token rates for the given networkClientId\n *\n * @param networkClientId - The network client ID used to get a ticker value.\n * @returns The controller state.\n */\n async _executePoll(networkClientId: NetworkClientId): Promise<void> {\n const networkClient = this.getNetworkClientById(networkClientId);\n await this.updateExchangeRatesByChainId({\n chainId: networkClient.configuration.chainId,\n nativeCurrency: networkClient.configuration.ticker,\n });\n }\n\n /**\n * Retrieves prices in the given currency for the given tokens on the given\n * chain. Ensures that token addresses are checksum addresses.\n *\n * @param args - The arguments to this function.\n * @param args.tokenAddresses - Addresses for tokens.\n * @param args.chainId - The EIP-155 ID of the chain where the tokens live.\n * @param args.nativeCurrency - The native currency in which to request\n * prices.\n * @returns A map of the token addresses (as checksums) to their prices in the\n * native currency.\n */\n async #fetchAndMapExchangeRatesForSupportedNativeCurrency({\n tokenAddresses,\n chainId,\n nativeCurrency,\n }: {\n tokenAddresses: Hex[];\n chainId: Hex;\n nativeCurrency: string;\n }): Promise<ContractMarketData> {\n let contractNativeInformations;\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 this.#tokenPricesService.fetchTokenPrices({\n tokenAddresses: batch,\n chainId,\n currency: nativeCurrency,\n });\n\n return {\n ...allTokenPricesByTokenAddress,\n ...tokenPricesByTokenAddressForBatch,\n };\n },\n initialResult: {},\n });\n contractNativeInformations = tokenPricesByTokenAddress;\n\n // fetch for native token\n if (tokenAddresses.length === 0) {\n const contractNativeInformationsNative =\n await this.#tokenPricesService.fetchTokenPrices({\n tokenAddresses: [],\n chainId,\n currency: nativeCurrency,\n });\n\n contractNativeInformations = {\n [ZERO_ADDRESS]: {\n currency: nativeCurrency,\n ...contractNativeInformationsNative[ZERO_ADDRESS],\n },\n };\n }\n return Object.entries(contractNativeInformations).reduce(\n (obj, [tokenAddress, token]) => {\n obj = {\n ...obj,\n [tokenAddress.toLowerCase()]: { ...token },\n };\n\n return obj;\n },\n {},\n );\n }\n\n /**\n * If the price API does not support a given native currency, then we need to\n * convert it to a fallback currency and feed that currency into the price\n * API, then convert the prices to our desired native currency.\n *\n * @param args - The arguments to this function.\n * @param args.tokenAddresses - Addresses for tokens.\n * @param args.nativeCurrency - The native currency in which to request\n * prices.\n * @returns A map of the token addresses (as checksums) to their prices in the\n * native currency.\n */\n async #fetchAndMapExchangeRatesForUnsupportedNativeCurrency({\n tokenAddresses,\n nativeCurrency,\n }: {\n tokenAddresses: Hex[];\n nativeCurrency: string;\n }): Promise<ContractMarketData> {\n const [\n contractExchangeInformations,\n fallbackCurrencyToNativeCurrencyConversionRate,\n ] = await Promise.all([\n this.#fetchAndMapExchangeRatesForSupportedNativeCurrency({\n tokenAddresses,\n chainId: this.config.chainId,\n nativeCurrency: FALL_BACK_VS_CURRENCY,\n }),\n getCurrencyConversionRate({\n from: FALL_BACK_VS_CURRENCY,\n to: nativeCurrency,\n }),\n ]);\n\n if (fallbackCurrencyToNativeCurrencyConversionRate === null) {\n return {};\n }\n\n const updatedContractExchangeRates = Object.entries(\n contractExchangeInformations,\n ).reduce((acc, [tokenAddress, token]) => {\n acc = {\n ...acc,\n [tokenAddress]: {\n ...token,\n value: token.value\n ? token.value * fallbackCurrencyToNativeCurrencyConversionRate\n : undefined,\n },\n };\n return acc;\n }, {});\n\n return updatedContractExchangeRates;\n }\n}\n\nexport default TokenRatesController;\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/crypto-compare-service/crypto-compare.ts"],"names":[],"mappings":";AAAA,SAAS,mBAAmB;AAM5B,IAAM,wBAAwB,oBAAI,IAAI,CAAC,CAAC,OAAO,QAAQ,CAAC,CAAC;AAEzD,IAAM,wBAAwB;AAa9B,SAAS,cACP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cACA,kBACA,gBACiD;AACjD,QAAM,MAAM;AAAA,IACV,OAAO,OAAO,gBAAgB,EAAE,KAAK,GAAG;AAAA,IACxC;AAAA,IACA;AAAA,EACF;AACA,QAAM,WAAW,MAAM,YAAY,GAAG;AACtC,sBAAoB,QAAQ;AAE5B,QAAM,QAAgD,CAAC;AACvD,aAAW,CAAC,gBAAgB,MAAM,KAAK,OAAO,QAAQ,QAAQ,GAGzD;AACH,UAAM,eAAe,YAAY,CAAC,IAAI;AAAA,MACpC,CAAC,aAAa,YAAY,CAAC,GAAG,OAAO,aAAa,YAAY,CAAC;AAAA,MAC/D,GAAI,kBAAkB,EAAE,KAAK,OAAO,IAAI;AAAA,IAC1C;AAAA,EACF;AAEA,SAAO;AACT","sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\n\n/**\n * A map from native currency symbol to CryptoCompare identifier.\n * This is only needed when the values don't match.\n */\nconst nativeSymbolOverrides = new Map([['MNT', 'MANTLE']]);\n\nconst CRYPTO_COMPARE_DOMAIN = 'https://min-api.cryptocompare.com';\n\n/**\n * Get the CryptoCompare API URL for getting the conversion rate from the given native currency to\n * the given currency. Optionally, the conversion rate from the native currency to USD can also be\n * included in the response.\n *\n * @param currentCurrency - The currency to get a conversion rate for.\n * @param nativeCurrency - The native currency to convert from.\n * @param includeUSDRate - Whether or not the native currency to USD conversion rate should be\n * included in the response as well.\n * @returns The API URL for getting the conversion rate.\n */\nfunction getPricingURL(\n currentCurrency: string,\n nativeCurrency: string,\n includeUSDRate?: boolean,\n) {\n nativeCurrency = nativeCurrency.toUpperCase();\n const fsym = nativeSymbolOverrides.get(nativeCurrency) ?? nativeCurrency;\n return (\n `${CRYPTO_COMPARE_DOMAIN}/data/price?fsym=` +\n `${fsym}&tsyms=${currentCurrency.toUpperCase()}` +\n `${includeUSDRate && currentCurrency.toUpperCase() !== 'USD' ? ',USD' : ''}`\n );\n}\n\n/**\n * Get the CryptoCompare API URL for getting the conversion rate from a given array of native currencies\n * to the given currency. Optionally, the conversion rate from the native currency to USD can also be\n * included in the response.\n *\n * @param fsyms - The native currencies to get conversion rates for.\n * @param tsyms - The currency to convert to.\n * @param includeUSDRate - Whether or not the native currency to USD conversion rate should be included.\n * @returns The API URL for getting the conversion rates.\n */\nfunction getMultiPricingURL(\n fsyms: string,\n tsyms: string,\n includeUSDRate = false,\n) {\n const updatedTsyms =\n includeUSDRate && !tsyms.includes('USD') ? `${tsyms},USD` : tsyms;\n\n const params = new URLSearchParams();\n params.append('fsyms', fsyms);\n params.append('tsyms', updatedTsyms);\n\n const url = new URL(`${CRYPTO_COMPARE_DOMAIN}/data/pricemulti`);\n url.search = params.toString();\n\n return url.toString();\n}\n\n/**\n * Handles an error response from the CryptoCompare API.\n * Expected error response format\n * { Response: \"Error\", Message: \"...\", HasWarning: false }\n *\n * @param json - The JSON response from the CryptoCompare API.\n * @param json.Response - The response status.\n * @param json.Message - The error message.\n */\nfunction handleErrorResponse(json: { Response?: string; Message?: string }) {\n if (json.Response === 'Error') {\n throw new Error(json.Message);\n }\n}\n\n/**\n * Fetches the exchange rate for a given currency.\n *\n * @param currency - ISO 4217 currency code.\n * @param nativeCurrency - Symbol for base asset.\n * @param includeUSDRate - Whether to add the USD rate to the fetch.\n * @returns Promise resolving to exchange rate for given currency.\n */\nexport async function fetchExchangeRate(\n currency: string,\n nativeCurrency: string,\n includeUSDRate?: boolean,\n): Promise<{\n conversionRate: number;\n usdConversionRate: number;\n}> {\n const json = await handleFetch(\n getPricingURL(currency, nativeCurrency, includeUSDRate),\n );\n\n handleErrorResponse(json);\n const conversionRate = Number(json[currency.toUpperCase()]);\n\n const usdConversionRate = Number(json.USD);\n if (!Number.isFinite(conversionRate)) {\n throw new Error(\n `Invalid response for ${currency.toUpperCase()}: ${\n json[currency.toUpperCase()]\n }`,\n );\n }\n\n if (includeUSDRate && !Number.isFinite(usdConversionRate)) {\n throw new Error(`Invalid response for usdConversionRate: ${json.USD}`);\n }\n\n return {\n conversionRate,\n usdConversionRate,\n };\n}\n\n/**\n * Fetches the exchange rates for multiple currencies.\n *\n * @param fiatCurrency - The currency of the rates (ISO 4217).\n * @param cryptocurrencies - The cryptocurrencies to get conversion rates for. Min length: 1. Max length: 300.\n * @param includeUSDRate - Whether to add the USD rate to the fetch.\n * @returns Promise resolving to exchange rates for given currencies.\n */\nexport async function fetchMultiExchangeRate(\n fiatCurrency: string,\n cryptocurrencies: string[],\n includeUSDRate: boolean,\n): Promise<Record<string, Record<string, string>>> {\n const url = getMultiPricingURL(\n Object.values(cryptocurrencies).join(','),\n fiatCurrency,\n includeUSDRate,\n );\n const response = await handleFetch(url);\n handleErrorResponse(response);\n\n const rates: Record<string, Record<string, string>> = {};\n for (const [cryptocurrency, values] of Object.entries(response) as [\n string,\n Record<string, string>,\n ][]) {\n rates[cryptocurrency.toLowerCase()] = {\n [fiatCurrency.toLowerCase()]: values[fiatCurrency.toUpperCase()],\n ...(includeUSDRate && { usd: values.USD }),\n };\n }\n\n return rates;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/token-prices-service/codefi-v2.ts"],"sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\nimport { hexToNumber } from '@metamask/utils';\nimport {\n circuitBreaker,\n ConsecutiveBreaker,\n ExponentialBackoff,\n handleAll,\n type IPolicy,\n retry,\n wrap,\n CircuitState,\n} from 'cockatiel';\n\nimport type {\n AbstractTokenPricesService,\n TokenPrice,\n TokenPricesByTokenAddress,\n} from './abstract-token-prices-service';\n\n/**\n * The list of currencies that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint, in lowercase form.\n */\nexport const SUPPORTED_CURRENCIES = [\n // Bitcoin\n 'btc',\n // Ether\n 'eth',\n // Litecoin\n 'ltc',\n // Bitcoin Cash\n 'bch',\n // Binance Coin\n 'bnb',\n // EOS\n 'eos',\n // XRP\n 'xrp',\n // Lumens\n 'xlm',\n // Chainlink\n 'link',\n // Polkadot\n 'dot',\n // Yearn.finance\n 'yfi',\n // US Dollar\n 'usd',\n // United Arab Emirates Dirham\n 'aed',\n // Argentine Peso\n 'ars',\n // Australian Dollar\n 'aud',\n // Bangladeshi Taka\n 'bdt',\n // Bahraini Dinar\n 'bhd',\n // Bermudian Dollar\n 'bmd',\n // Brazil Real\n 'brl',\n // Canadian Dollar\n 'cad',\n // Swiss Franc\n 'chf',\n // Chilean Peso\n 'clp',\n // Chinese Yuan\n 'cny',\n // Czech Koruna\n 'czk',\n // Danish Krone\n 'dkk',\n // Euro\n 'eur',\n // British Pound Sterling\n 'gbp',\n // Hong Kong Dollar\n 'hkd',\n // Hungarian Forint\n 'huf',\n // Indonesian Rupiah\n 'idr',\n // Israeli New Shekel\n 'ils',\n // Indian Rupee\n 'inr',\n // Japanese Yen\n 'jpy',\n // South Korean Won\n 'krw',\n // Kuwaiti Dinar\n 'kwd',\n // Sri Lankan Rupee\n 'lkr',\n // Burmese Kyat\n 'mmk',\n // Mexican Peso\n 'mxn',\n // Malaysian Ringgit\n 'myr',\n // Nigerian Naira\n 'ngn',\n // Norwegian Krone\n 'nok',\n // New Zealand Dollar\n 'nzd',\n // Philippine Peso\n 'php',\n // Pakistani Rupee\n 'pkr',\n // Polish Zloty\n 'pln',\n // Russian Ruble\n 'rub',\n // Saudi Riyal\n 'sar',\n // Swedish Krona\n 'sek',\n // Singapore Dollar\n 'sgd',\n // Thai Baht\n 'thb',\n // Turkish Lira\n 'try',\n // New Taiwan Dollar\n 'twd',\n // Ukrainian hryvnia\n 'uah',\n // Venezuelan bolívar fuerte\n 'vef',\n // Vietnamese đồng\n 'vnd',\n // South African Rand\n 'zar',\n // IMF Special Drawing Rights\n 'xdr',\n // Silver - Troy Ounce\n 'xag',\n // Gold - Troy Ounce\n 'xau',\n // Bits\n 'bits',\n // Satoshi\n 'sats',\n] as const;\n\n/**\n * Represents the zero address, commonly used as a placeholder in blockchain transactions.\n * In the context of fetching market data, the zero address is utilized to retrieve information\n * specifically for native currencies. This allows for a standardized approach to query market\n * data for blockchain-native assets without a specific contract address.\n */\nexport const ZERO_ADDRESS: Hex =\n '0x0000000000000000000000000000000000000000' as const;\n\n/**\n * A currency that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.\n */\ntype SupportedCurrency =\n | (typeof SUPPORTED_CURRENCIES)[number]\n | Uppercase<(typeof SUPPORTED_CURRENCIES)[number]>;\n\n/**\n * The list of chain IDs that can be supplied in the URL for the `/spot-prices`\n * endpoint, but in hexadecimal form (for consistency with how we represent\n * chain IDs in other places).\n * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.\n */\nexport const SUPPORTED_CHAIN_IDS = [\n // Ethereum Mainnet\n '0x1',\n // OP Mainnet\n '0xa',\n // Cronos Mainnet\n '0x19',\n // BNB Smart Chain Mainnet\n '0x38',\n // Syscoin Mainnet\n '0x39',\n // OKXChain Mainnet\n '0x42',\n // Hoo Smart Chain\n '0x46',\n // Meter Mainnet\n '0x52',\n // TomoChain\n '0x58',\n // Gnosis\n '0x64',\n // Velas EVM Mainnet\n '0x6a',\n // Fuse Mainnet\n '0x7a',\n // Huobi ECO Chain Mainnet\n '0x80',\n // Polygon Mainnet\n '0x89',\n // Fantom Opera\n '0xfa',\n // Boba Network\n '0x120',\n // KCC Mainnet\n '0x141',\n // zkSync Era Mainnet\n '0x144',\n // Theta Mainnet\n '0x169',\n // Metis Andromeda Mainnet\n '0x440',\n // Moonbeam\n '0x504',\n // Moonriver\n '0x505',\n // Base\n '0x2105',\n // Shiden\n '0x150',\n // Smart Bitcoin Cash\n '0x2710',\n // Arbitrum One\n '0xa4b1',\n // Celo Mainnet\n '0xa4ec',\n // Oasis Emerald\n '0xa516',\n // Avalanche C-Chain\n '0xa86a',\n // Polis Mainnet\n '0x518af',\n // Aurora Mainnet\n '0x4e454152',\n // Harmony Mainnet Shard 0\n '0x63564c40',\n // Linea Mainnet\n '0xe708',\n] as const;\n\n/**\n * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,\n * but in hexadecimal form (for consistency with how we represent chain IDs in\n * other places).\n */\ntype SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];\n\n/**\n * All requests to V2 of the Price API start with this.\n */\nconst BASE_URL = 'https://price.api.cx.metamask.io/v2';\n\nconst DEFAULT_TOKEN_PRICE_RETRIES = 3;\n// Each update attempt will result (1 + retries) calls if the server is down\nconst DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES =\n (1 + DEFAULT_TOKEN_PRICE_RETRIES) * 3;\n\nconst DEFAULT_DEGRADED_THRESHOLD = 5_000;\n\n/**\n * The shape of the data that the /spot-prices endpoint returns.\n */\ntype MarketData = {\n /**\n * The all-time highest price of the token.\n */\n allTimeHigh: number;\n /**\n * The all-time lowest price of the token.\n */\n allTimeLow: number;\n /**\n * The number of tokens currently in circulation.\n */\n circulatingSupply: number;\n /**\n * The market cap calculated using the diluted supply.\n */\n dilutedMarketCap: number;\n /**\n * The highest price of the token in the last 24 hours.\n */\n high1d: number;\n /**\n * The lowest price of the token in the last 24 hours.\n */\n low1d: number;\n /**\n * The current market capitalization of the token.\n */\n marketCap: number;\n /**\n * The percentage change in market capitalization over the last 24 hours.\n */\n marketCapPercentChange1d: number;\n /**\n * The current price of the token.\n */\n price: number;\n /**\n * The absolute change in price over the last 24 hours.\n */\n priceChange1d: number;\n /**\n * The percentage change in price over the last 24 hours.\n */\n pricePercentChange1d: number;\n /**\n * The percentage change in price over the last hour.\n */\n pricePercentChange1h: number;\n /**\n * The percentage change in price over the last year.\n */\n pricePercentChange1y: number;\n /**\n * The percentage change in price over the last 7 days.\n */\n pricePercentChange7d: number;\n /**\n * The percentage change in price over the last 14 days.\n */\n pricePercentChange14d: number;\n /**\n * The percentage change in price over the last 30 days.\n */\n pricePercentChange30d: number;\n /**\n * The percentage change in price over the last 200 days.\n */\n pricePercentChange200d: number;\n /**\n * The total trading volume of the token in the last 24 hours.\n */\n totalVolume: number;\n};\n\ntype MarketDataByTokenAddress = { [address: Hex]: MarketData };\n/**\n * This version of the token prices service uses V2 of the Codefi Price API to\n * fetch token prices.\n */\nexport class CodefiTokenPricesServiceV2\n implements\n AbstractTokenPricesService<SupportedChainId, Hex, SupportedCurrency>\n{\n #tokenPricePolicy: IPolicy;\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @param options - Constructor options\n * @param options.degradedThreshold - The threshold between \"normal\" and \"degrated\" service,\n * in milliseconds.\n * @param options.retries - Number of retry attempts for each token price update.\n * @param options.maximumConsecutiveFailures - The maximum number of consecutive failures\n * allowed before breaking the circuit and pausing further updates.\n * @param options.onBreak - An event handler for when the circuit breaks, useful for capturing\n * metrics about network failures.\n * @param options.onDegraded - An event handler for when the circuit remains closed, but requests\n * are failing or resolving too slowly (i.e. resolving more slowly than the `degradedThreshold).\n * @param options.circuitBreakDuration - The amount of time to wait when the circuit breaks\n * from too many consecutive failures.\n */\n constructor({\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n retries = DEFAULT_TOKEN_PRICE_RETRIES,\n maximumConsecutiveFailures = DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES,\n onBreak,\n onDegraded,\n circuitBreakDuration = 30 * 60 * 1000,\n }: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n } = {}) {\n // Construct a policy that will retry each update, and halt further updates\n // for a certain period after too many consecutive failures.\n const retryPolicy = retry(handleAll, {\n maxAttempts: retries,\n backoff: new ExponentialBackoff(),\n });\n const circuitBreakerPolicy = circuitBreaker(handleAll, {\n halfOpenAfter: circuitBreakDuration,\n breaker: new ConsecutiveBreaker(maximumConsecutiveFailures),\n });\n if (onBreak) {\n circuitBreakerPolicy.onBreak(onBreak);\n }\n if (onDegraded) {\n retryPolicy.onGiveUp(() => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n onDegraded();\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (\n circuitBreakerPolicy.state === CircuitState.Closed &&\n duration > degradedThreshold\n ) {\n onDegraded();\n }\n });\n }\n this.#tokenPricePolicy = wrap(retryPolicy, circuitBreakerPolicy);\n }\n\n /**\n * Retrieves prices in the given currency for the tokens identified by the\n * given addresses which are expected to live on the given chain.\n *\n * @param args - The arguments to function.\n * @param args.chainId - An EIP-155 chain ID.\n * @param args.tokenAddresses - Addresses for tokens that live on the chain.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n async fetchTokenPrices({\n chainId,\n tokenAddresses,\n currency,\n }: {\n chainId: SupportedChainId;\n tokenAddresses: Hex[];\n currency: SupportedCurrency;\n }): Promise<Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>> {\n const chainIdAsNumber = hexToNumber(chainId);\n\n const url = new URL(`${BASE_URL}/chains/${chainIdAsNumber}/spot-prices`);\n url.searchParams.append(\n 'tokenAddresses',\n [ZERO_ADDRESS, ...tokenAddresses].join(','),\n );\n url.searchParams.append('vsCurrency', currency);\n url.searchParams.append('includeMarketData', 'true');\n\n const addressCryptoDataMap: MarketDataByTokenAddress =\n await this.#tokenPricePolicy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n );\n\n return [ZERO_ADDRESS, ...tokenAddresses].reduce(\n (\n obj: Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>,\n tokenAddress,\n ) => {\n // The Price API lowercases both currency and token addresses, so we have\n // to keep track of them and make sure we return the original versions.\n const lowercasedTokenAddress =\n tokenAddress.toLowerCase() as Lowercase<Hex>;\n\n const marketData = addressCryptoDataMap[lowercasedTokenAddress];\n\n if (marketData === undefined) {\n return obj;\n }\n\n const { price } = marketData;\n\n const token: TokenPrice<Hex, SupportedCurrency> = {\n tokenAddress,\n value: price,\n currency,\n ...marketData,\n };\n\n return {\n ...obj,\n [tokenAddress]: token,\n };\n },\n {},\n ) as Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>;\n }\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is SupportedChainId {\n const supportedChainIds: readonly string[] = SUPPORTED_CHAIN_IDS;\n return typeof chainId === 'string' && supportedChainIds.includes(chainId);\n }\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check. If a string, can be either\n * lowercase or uppercase.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is SupportedCurrency {\n const supportedCurrencies: readonly string[] = SUPPORTED_CURRENCIES;\n return (\n typeof currency === 'string' &&\n supportedCurrencies.includes(currency.toLowerCase())\n );\n }\n}\n"],"mappings":";;;;;;;AAAA,SAAS,mBAAmB;AAE5B,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAYA,IAAM,uBAAuB;AAAA;AAAA,EAElC;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,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EAAE,KAAK,GAAG;AAAA,IAC5C;AACA,QAAI,aAAa,OAAO,cAAc,QAAQ;AAC9C,QAAI,aAAa,OAAO,qBAAqB,MAAM;AAEnD,UAAM,uBACJ,MAAM,mBAAK,mBAAkB;AAAA,MAAQ,MACnC,YAAY,KAAK,EAAE,SAAS,EAAE,iBAAiB,WAAW,EAAE,CAAC;AAAA,IAC/D;AAEF,WAAO,CAAC,cAAc,GAAG,cAAc,EAAE;AAAA,MACvC,CACE,KACA,iBACG;AAGH,cAAM,yBACJ,aAAa,YAAY;AAE3B,cAAM,aAAa,qBAAqB,sBAAsB;AAE9D,YAAI,eAAe,QAAW;AAC5B,iBAAO;AAAA,QACT;AAEA,cAAM,EAAE,MAAM,IAAI;AAElB,cAAM,QAA4C;AAAA,UAChD;AAAA,UACA,OAAO;AAAA,UACP;AAAA,UACA,GAAG;AAAA,QACL;AAEA,eAAO;AAAA,UACL,GAAG;AAAA,UACH,CAAC,YAAY,GAAG;AAAA,QAClB;AAAA,MACF;AAAA,MACA,CAAC;AAAA,IACH;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,yBAAyB,SAA+C;AACtE,UAAM,oBAAuC;AAC7C,WAAO,OAAO,YAAY,YAAY,kBAAkB,SAAS,OAAO;AAAA,EAC1E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,0BAA0B,UAAkD;AAC1E,UAAM,sBAAyC;AAC/C,WACE,OAAO,aAAa,YACpB,oBAAoB,SAAS,SAAS,YAAY,CAAC;AAAA,EAEvD;AACF;AA/JE;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/RatesController/RatesController.ts"],"names":["Cryptocurrency","fetchMultiExchangeRate"],"mappings":";;;;;;;;;;;AAAA,SAAS,sBAAsB;AAC/B,SAAS,aAAa;AAUf,IAAM,OAAO;AAEb,IAAK,iBAAL,kBAAKA,oBAAL;AACL,EAA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sBAAK,wBAAL,WAAe,YAAY;AAC/B,UAAM,EAAE,cAAc,iBAAiB,IAAI,KAAK;AAChD,UAAM,WAGF,MAAM,mBAAK,yBAAL,WACR,cACA,kBACA,mBAAK;AAGP,UAAM,eAAgC,CAAC;AACvC,eAAW,CAAC,gBAAgB,MAAM,KAAK,OAAO,QAAQ,QAAQ,GAAG;AAC/D,mBAAa,cAAc,IAAI;AAAA,QAC7B,gBAAgB,KAAK,IAAI;AAAA,QACzB,gBAAgB,OAAO,YAAY;AAAA,QACnC,GAAI,mBAAK,oBAAmB,EAAE,mBAAmB,OAAO,IAAI;AAAA,MAC9D;AAAA,IACF;AAEA,SAAK,OAAO,MAAM;AAChB,aAAO;AAAA,QACL,GAAG,KAAK;AAAA,QACR,OAAO;AAAA,MACT;AAAA,IACF,CAAC;AAAA,EACH;AACF","sourcesContent":["import { BaseController } from '@metamask/base-controller';\nimport { Mutex } from 'async-mutex';\n\nimport { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n ConversionRates,\n RatesControllerState,\n RatesControllerOptions,\n RatesControllerMessenger,\n} from './types';\n\nexport const name = 'RatesController';\n\nexport enum Cryptocurrency {\n Btc = 'btc',\n}\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst metadata = {\n fiatCurrency: { persist: true, anonymous: true },\n rates: { persist: true, anonymous: true },\n cryptocurrencies: { persist: true, anonymous: true },\n};\n\nconst defaultState = {\n fiatCurrency: 'usd',\n rates: {\n [Cryptocurrency.Btc]: {\n conversionDate: 0,\n conversionRate: '0',\n },\n },\n cryptocurrencies: [Cryptocurrency.Btc],\n};\n\nexport class RatesController extends BaseController<\n typeof name,\n RatesControllerState,\n RatesControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n readonly #fetchMultiExchangeRate;\n\n readonly #includeUsdRate;\n\n #intervalLength: number;\n\n #intervalId: NodeJS.Timeout | undefined;\n\n /**\n * Creates a RatesController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n messenger,\n state,\n includeUsdRate,\n fetchMultiExchangeRate = defaultFetchExchangeRate,\n }: RatesControllerOptions) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.#includeUsdRate = includeUsdRate;\n this.#fetchMultiExchangeRate = fetchMultiExchangeRate;\n this.#intervalLength = interval;\n }\n\n /**\n * Executes a function `callback` within a mutex lock to ensure that only one instance of `callback` runs at a time across all invocations of `#withLock`.\n * This method is useful for synchronizing access to a resource or section of code that should not be executed concurrently.\n *\n * @template R - The return type of the function `callback`.\n * @param callback - A callback to execute once the lock is acquired. This callback can be synchronous or asynchronous.\n * @returns A promise that resolves to the result of the function `callback`. The promise is fulfilled once `callback` has completed execution.\n * @example\n * async function criticalLogic() {\n * // Critical logic code goes here.\n * }\n *\n * // Execute criticalLogic within a lock.\n * const result = await this.#withLock(criticalLogic);\n */\n async #withLock<R>(callback: () => R) {\n const releaseLock = await this.#mutex.acquire();\n try {\n return callback();\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Executes the polling operation to update rates.\n */\n async #executePoll(): Promise<void> {\n await this.#updateRates();\n }\n\n /**\n * Updates the rates by fetching new data.\n */\n async #updateRates(): Promise<void> {\n await this.#withLock(async () => {\n const { fiatCurrency, cryptocurrencies } = this.state;\n const response: Record<\n Cryptocurrency,\n Record<string, string>\n > = await this.#fetchMultiExchangeRate(\n fiatCurrency,\n cryptocurrencies,\n this.#includeUsdRate,\n );\n\n const updatedRates: ConversionRates = {};\n for (const [cryptocurrency, values] of Object.entries(response)) {\n updatedRates[cryptocurrency] = {\n conversionDate: Date.now(),\n conversionRate: values[fiatCurrency],\n ...(this.#includeUsdRate && { usdConversionRate: values.usd }),\n };\n }\n\n this.update(() => {\n return {\n ...this.state,\n rates: updatedRates,\n };\n });\n });\n }\n\n /**\n * Starts the polling process.\n */\n async start(): Promise<void> {\n if (this.#intervalId) {\n return;\n }\n\n this.messagingSystem.publish(`${name}:pollingStarted`);\n\n this.#intervalId = setInterval(() => {\n this.#executePoll().catch(console.error);\n }, this.#intervalLength);\n }\n\n /**\n * Stops the polling process.\n */\n async stop(): Promise<void> {\n if (!this.#intervalId) {\n return;\n }\n\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n this.messagingSystem.publish(`${name}:pollingStopped`);\n }\n\n /**\n * Returns the current list of cryptocurrency.\n * @returns The cryptocurrency list.\n */\n getCryptocurrencyList(): Cryptocurrency[] {\n const { cryptocurrencies } = this.state;\n return cryptocurrencies;\n }\n\n /**\n * Sets the list of supported cryptocurrencies.\n * @param list - The list of supported cryptocurrencies.\n */\n async setCryptocurrencyList(list: Cryptocurrency[]): Promise<void> {\n await this.#withLock(() => {\n this.update(() => {\n return {\n ...this.state,\n fromCurrencies: list,\n };\n });\n });\n }\n\n /**\n * Sets the internal fiat currency and update rates accordingly.\n * @param fiatCurrency - The fiat currency.\n */\n async setFiatCurrency(fiatCurrency: string): Promise<void> {\n if (fiatCurrency === '') {\n throw new Error('The currency can not be an empty string');\n }\n\n await this.#withLock(() => {\n this.update(() => {\n return {\n ...defaultState,\n fiatCurrency,\n };\n });\n });\n await this.#updateRates();\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/token-prices-service/codefi-v2.ts"],"names":[],"mappings":";;;;;;;AAAA,SAAS,mBAAmB;AAE5B,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAYA,IAAM,uBAAuB;AAAA;AAAA,EAElC;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,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AAuC;AAC7C,WAAO,OAAO,YAAY,YAAY,kBAAkB,SAAS,OAAO;AAAA,EAC1E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,0BAA0B,UAAkD;AAC1E,UAAM,sBAAyC;AAC/C,WACE,OAAO,aAAa,YACpB,oBAAoB,SAAS,SAAS,YAAY,CAAC;AAAA,EAEvD;AACF;AA/JE","sourcesContent":["import { handleFetch } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\nimport { hexToNumber } from '@metamask/utils';\nimport {\n circuitBreaker,\n ConsecutiveBreaker,\n ExponentialBackoff,\n handleAll,\n type IPolicy,\n retry,\n wrap,\n CircuitState,\n} from 'cockatiel';\n\nimport type {\n AbstractTokenPricesService,\n TokenPrice,\n TokenPricesByTokenAddress,\n} from './abstract-token-prices-service';\n\n/**\n * The list of currencies that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint, in lowercase form.\n */\nexport const SUPPORTED_CURRENCIES = [\n // Bitcoin\n 'btc',\n // Ether\n 'eth',\n // Litecoin\n 'ltc',\n // Bitcoin Cash\n 'bch',\n // Binance Coin\n 'bnb',\n // EOS\n 'eos',\n // XRP\n 'xrp',\n // Lumens\n 'xlm',\n // Chainlink\n 'link',\n // Polkadot\n 'dot',\n // Yearn.finance\n 'yfi',\n // US Dollar\n 'usd',\n // United Arab Emirates Dirham\n 'aed',\n // Argentine Peso\n 'ars',\n // Australian Dollar\n 'aud',\n // Bangladeshi Taka\n 'bdt',\n // Bahraini Dinar\n 'bhd',\n // Bermudian Dollar\n 'bmd',\n // Brazil Real\n 'brl',\n // Canadian Dollar\n 'cad',\n // Swiss Franc\n 'chf',\n // Chilean Peso\n 'clp',\n // Chinese Yuan\n 'cny',\n // Czech Koruna\n 'czk',\n // Danish Krone\n 'dkk',\n // Euro\n 'eur',\n // British Pound Sterling\n 'gbp',\n // Hong Kong Dollar\n 'hkd',\n // Hungarian Forint\n 'huf',\n // Indonesian Rupiah\n 'idr',\n // Israeli New Shekel\n 'ils',\n // Indian Rupee\n 'inr',\n // Japanese Yen\n 'jpy',\n // South Korean Won\n 'krw',\n // Kuwaiti Dinar\n 'kwd',\n // Sri Lankan Rupee\n 'lkr',\n // Burmese Kyat\n 'mmk',\n // Mexican Peso\n 'mxn',\n // Malaysian Ringgit\n 'myr',\n // Nigerian Naira\n 'ngn',\n // Norwegian Krone\n 'nok',\n // New Zealand Dollar\n 'nzd',\n // Philippine Peso\n 'php',\n // Pakistani Rupee\n 'pkr',\n // Polish Zloty\n 'pln',\n // Russian Ruble\n 'rub',\n // Saudi Riyal\n 'sar',\n // Swedish Krona\n 'sek',\n // Singapore Dollar\n 'sgd',\n // Thai Baht\n 'thb',\n // Turkish Lira\n 'try',\n // New Taiwan Dollar\n 'twd',\n // Ukrainian hryvnia\n 'uah',\n // Venezuelan bolívar fuerte\n 'vef',\n // Vietnamese đồng\n 'vnd',\n // South African Rand\n 'zar',\n // IMF Special Drawing Rights\n 'xdr',\n // Silver - Troy Ounce\n 'xag',\n // Gold - Troy Ounce\n 'xau',\n // Bits\n 'bits',\n // Satoshi\n 'sats',\n] as const;\n\n/**\n * Represents the zero address, commonly used as a placeholder in blockchain transactions.\n * In the context of fetching market data, the zero address is utilized to retrieve information\n * specifically for native currencies. This allows for a standardized approach to query market\n * data for blockchain-native assets without a specific contract address.\n */\nexport const ZERO_ADDRESS: Hex =\n '0x0000000000000000000000000000000000000000' as const;\n\n/**\n * A currency that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.\n */\ntype SupportedCurrency =\n | (typeof SUPPORTED_CURRENCIES)[number]\n | Uppercase<(typeof SUPPORTED_CURRENCIES)[number]>;\n\n/**\n * The list of chain IDs that can be supplied in the URL for the `/spot-prices`\n * endpoint, but in hexadecimal form (for consistency with how we represent\n * chain IDs in other places).\n * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.\n */\nexport const SUPPORTED_CHAIN_IDS = [\n // Ethereum Mainnet\n '0x1',\n // OP Mainnet\n '0xa',\n // Cronos Mainnet\n '0x19',\n // BNB Smart Chain Mainnet\n '0x38',\n // Syscoin Mainnet\n '0x39',\n // OKXChain Mainnet\n '0x42',\n // Hoo Smart Chain\n '0x46',\n // Meter Mainnet\n '0x52',\n // TomoChain\n '0x58',\n // Gnosis\n '0x64',\n // Velas EVM Mainnet\n '0x6a',\n // Fuse Mainnet\n '0x7a',\n // Huobi ECO Chain Mainnet\n '0x80',\n // Polygon Mainnet\n '0x89',\n // Fantom Opera\n '0xfa',\n // Boba Network\n '0x120',\n // KCC Mainnet\n '0x141',\n // zkSync Era Mainnet\n '0x144',\n // Theta Mainnet\n '0x169',\n // Metis Andromeda Mainnet\n '0x440',\n // Moonbeam\n '0x504',\n // Moonriver\n '0x505',\n // Base\n '0x2105',\n // Shiden\n '0x150',\n // Smart Bitcoin Cash\n '0x2710',\n // Arbitrum One\n '0xa4b1',\n // Celo Mainnet\n '0xa4ec',\n // Oasis Emerald\n '0xa516',\n // Avalanche C-Chain\n '0xa86a',\n // Polis Mainnet\n '0x518af',\n // Aurora Mainnet\n '0x4e454152',\n // Harmony Mainnet Shard 0\n '0x63564c40',\n // Linea Mainnet\n '0xe708',\n] as const;\n\n/**\n * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,\n * but in hexadecimal form (for consistency with how we represent chain IDs in\n * other places).\n */\ntype SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];\n\n/**\n * All requests to V2 of the Price API start with this.\n */\nconst BASE_URL = 'https://price.api.cx.metamask.io/v2';\n\nconst DEFAULT_TOKEN_PRICE_RETRIES = 3;\n// Each update attempt will result (1 + retries) calls if the server is down\nconst DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES =\n (1 + DEFAULT_TOKEN_PRICE_RETRIES) * 3;\n\nconst DEFAULT_DEGRADED_THRESHOLD = 5_000;\n\n/**\n * The shape of the data that the /spot-prices endpoint returns.\n */\ntype MarketData = {\n /**\n * The all-time highest price of the token.\n */\n allTimeHigh: number;\n /**\n * The all-time lowest price of the token.\n */\n allTimeLow: number;\n /**\n * The number of tokens currently in circulation.\n */\n circulatingSupply: number;\n /**\n * The market cap calculated using the diluted supply.\n */\n dilutedMarketCap: number;\n /**\n * The highest price of the token in the last 24 hours.\n */\n high1d: number;\n /**\n * The lowest price of the token in the last 24 hours.\n */\n low1d: number;\n /**\n * The current market capitalization of the token.\n */\n marketCap: number;\n /**\n * The percentage change in market capitalization over the last 24 hours.\n */\n marketCapPercentChange1d: number;\n /**\n * The current price of the token.\n */\n price: number;\n /**\n * The absolute change in price over the last 24 hours.\n */\n priceChange1d: number;\n /**\n * The percentage change in price over the last 24 hours.\n */\n pricePercentChange1d: number;\n /**\n * The percentage change in price over the last hour.\n */\n pricePercentChange1h: number;\n /**\n * The percentage change in price over the last year.\n */\n pricePercentChange1y: number;\n /**\n * The percentage change in price over the last 7 days.\n */\n pricePercentChange7d: number;\n /**\n * The percentage change in price over the last 14 days.\n */\n pricePercentChange14d: number;\n /**\n * The percentage change in price over the last 30 days.\n */\n pricePercentChange30d: number;\n /**\n * The percentage change in price over the last 200 days.\n */\n pricePercentChange200d: number;\n /**\n * The total trading volume of the token in the last 24 hours.\n */\n totalVolume: number;\n};\n\ntype MarketDataByTokenAddress = { [address: Hex]: MarketData };\n/**\n * This version of the token prices service uses V2 of the Codefi Price API to\n * fetch token prices.\n */\nexport class CodefiTokenPricesServiceV2\n implements\n AbstractTokenPricesService<SupportedChainId, Hex, SupportedCurrency>\n{\n #tokenPricePolicy: IPolicy;\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @param options - Constructor options\n * @param options.degradedThreshold - The threshold between \"normal\" and \"degrated\" service,\n * in milliseconds.\n * @param options.retries - Number of retry attempts for each token price update.\n * @param options.maximumConsecutiveFailures - The maximum number of consecutive failures\n * allowed before breaking the circuit and pausing further updates.\n * @param options.onBreak - An event handler for when the circuit breaks, useful for capturing\n * metrics about network failures.\n * @param options.onDegraded - An event handler for when the circuit remains closed, but requests\n * are failing or resolving too slowly (i.e. resolving more slowly than the `degradedThreshold).\n * @param options.circuitBreakDuration - The amount of time to wait when the circuit breaks\n * from too many consecutive failures.\n */\n constructor({\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n retries = DEFAULT_TOKEN_PRICE_RETRIES,\n maximumConsecutiveFailures = DEFAULT_TOKEN_PRICE_MAX_CONSECUTIVE_FAILURES,\n onBreak,\n onDegraded,\n circuitBreakDuration = 30 * 60 * 1000,\n }: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n } = {}) {\n // Construct a policy that will retry each update, and halt further updates\n // for a certain period after too many consecutive failures.\n const retryPolicy = retry(handleAll, {\n maxAttempts: retries,\n backoff: new ExponentialBackoff(),\n });\n const circuitBreakerPolicy = circuitBreaker(handleAll, {\n halfOpenAfter: circuitBreakDuration,\n breaker: new ConsecutiveBreaker(maximumConsecutiveFailures),\n });\n if (onBreak) {\n circuitBreakerPolicy.onBreak(onBreak);\n }\n if (onDegraded) {\n retryPolicy.onGiveUp(() => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n onDegraded();\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (\n circuitBreakerPolicy.state === CircuitState.Closed &&\n duration > degradedThreshold\n ) {\n onDegraded();\n }\n });\n }\n this.#tokenPricePolicy = wrap(retryPolicy, circuitBreakerPolicy);\n }\n\n /**\n * Retrieves prices in the given currency for the tokens identified by the\n * given addresses which are expected to live on the given chain.\n *\n * @param args - The arguments to function.\n * @param args.chainId - An EIP-155 chain ID.\n * @param args.tokenAddresses - Addresses for tokens that live on the chain.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n async fetchTokenPrices({\n chainId,\n tokenAddresses,\n currency,\n }: {\n chainId: SupportedChainId;\n tokenAddresses: Hex[];\n currency: SupportedCurrency;\n }): Promise<Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>> {\n const chainIdAsNumber = hexToNumber(chainId);\n\n const url = new URL(`${BASE_URL}/chains/${chainIdAsNumber}/spot-prices`);\n url.searchParams.append(\n 'tokenAddresses',\n [ZERO_ADDRESS, ...tokenAddresses].join(','),\n );\n url.searchParams.append('vsCurrency', currency);\n url.searchParams.append('includeMarketData', 'true');\n\n const addressCryptoDataMap: MarketDataByTokenAddress =\n await this.#tokenPricePolicy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n );\n\n return [ZERO_ADDRESS, ...tokenAddresses].reduce(\n (\n obj: Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>,\n tokenAddress,\n ) => {\n // The Price API lowercases both currency and token addresses, so we have\n // to keep track of them and make sure we return the original versions.\n const lowercasedTokenAddress =\n tokenAddress.toLowerCase() as Lowercase<Hex>;\n\n const marketData = addressCryptoDataMap[lowercasedTokenAddress];\n\n if (marketData === undefined) {\n return obj;\n }\n\n const { price } = marketData;\n\n const token: TokenPrice<Hex, SupportedCurrency> = {\n tokenAddress,\n value: price,\n currency,\n ...marketData,\n };\n\n return {\n ...obj,\n [tokenAddress]: token,\n };\n },\n {},\n ) as Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>;\n }\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is SupportedChainId {\n const supportedChainIds: readonly string[] = SUPPORTED_CHAIN_IDS;\n return typeof chainId === 'string' && supportedChainIds.includes(chainId);\n }\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check. If a string, can be either\n * lowercase or uppercase.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is SupportedCurrency {\n const supportedCurrencies: readonly string[] = SUPPORTED_CURRENCIES;\n return (\n typeof currency === 'string' &&\n supportedCurrencies.includes(currency.toLowerCase())\n );\n }\n}\n"]}
|