@metamask/bridge-controller 45.0.0 → 47.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 +37 -1
- package/dist/bridge-controller.cjs +45 -30
- package/dist/bridge-controller.cjs.map +1 -1
- package/dist/bridge-controller.d.cts +3 -1
- package/dist/bridge-controller.d.cts.map +1 -1
- package/dist/bridge-controller.d.mts +3 -1
- package/dist/bridge-controller.d.mts.map +1 -1
- package/dist/bridge-controller.mjs +47 -32
- package/dist/bridge-controller.mjs.map +1 -1
- package/dist/index.cjs +3 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/selectors.cjs +23 -20
- package/dist/selectors.cjs.map +1 -1
- package/dist/selectors.d.cts +315 -81
- package/dist/selectors.d.cts.map +1 -1
- package/dist/selectors.d.mts +315 -81
- package/dist/selectors.d.mts.map +1 -1
- package/dist/selectors.mjs +25 -22
- package/dist/selectors.mjs.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +5 -5
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +5 -5
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/dist/utils/bridge.cjs +12 -1
- package/dist/utils/bridge.cjs.map +1 -1
- package/dist/utils/bridge.d.cts +8 -0
- package/dist/utils/bridge.d.cts.map +1 -1
- package/dist/utils/bridge.d.mts +8 -0
- package/dist/utils/bridge.d.mts.map +1 -1
- package/dist/utils/bridge.mjs +10 -0
- package/dist/utils/bridge.mjs.map +1 -1
- package/dist/utils/fetch.cjs +5 -0
- package/dist/utils/fetch.cjs.map +1 -1
- package/dist/utils/fetch.d.cts.map +1 -1
- package/dist/utils/fetch.d.mts.map +1 -1
- package/dist/utils/fetch.mjs +6 -1
- package/dist/utils/fetch.mjs.map +1 -1
- package/dist/utils/metrics/constants.cjs +0 -1
- package/dist/utils/metrics/constants.cjs.map +1 -1
- package/dist/utils/metrics/constants.d.cts +0 -1
- package/dist/utils/metrics/constants.d.cts.map +1 -1
- package/dist/utils/metrics/constants.d.mts +0 -1
- package/dist/utils/metrics/constants.d.mts.map +1 -1
- package/dist/utils/metrics/constants.mjs +0 -1
- package/dist/utils/metrics/constants.mjs.map +1 -1
- package/dist/utils/metrics/properties.cjs.map +1 -1
- package/dist/utils/metrics/properties.d.cts +1 -1
- package/dist/utils/metrics/properties.d.cts.map +1 -1
- package/dist/utils/metrics/properties.d.mts +1 -1
- package/dist/utils/metrics/properties.d.mts.map +1 -1
- package/dist/utils/metrics/properties.mjs.map +1 -1
- package/dist/utils/metrics/types.cjs.map +1 -1
- package/dist/utils/metrics/types.d.cts +1 -3
- package/dist/utils/metrics/types.d.cts.map +1 -1
- package/dist/utils/metrics/types.d.mts +1 -3
- package/dist/utils/metrics/types.d.mts.map +1 -1
- package/dist/utils/metrics/types.mjs.map +1 -1
- package/dist/utils/quote.cjs +19 -13
- package/dist/utils/quote.cjs.map +1 -1
- package/dist/utils/quote.d.cts +2 -2
- package/dist/utils/quote.d.cts.map +1 -1
- package/dist/utils/quote.d.mts +2 -2
- package/dist/utils/quote.d.mts.map +1 -1
- package/dist/utils/quote.mjs +18 -12
- package/dist/utils/quote.mjs.map +1 -1
- package/dist/utils/snaps.cjs +20 -6
- package/dist/utils/snaps.cjs.map +1 -1
- package/dist/utils/snaps.d.cts +16 -2
- package/dist/utils/snaps.d.cts.map +1 -1
- package/dist/utils/snaps.d.mts +16 -2
- package/dist/utils/snaps.d.mts.map +1 -1
- package/dist/utils/snaps.mjs +18 -4
- package/dist/utils/snaps.mjs.map +1 -1
- package/dist/utils/validators.cjs +17 -2
- package/dist/utils/validators.cjs.map +1 -1
- package/dist/utils/validators.d.cts +990 -2
- package/dist/utils/validators.d.cts.map +1 -1
- package/dist/utils/validators.d.mts +990 -2
- package/dist/utils/validators.d.mts.map +1 -1
- package/dist/utils/validators.mjs +15 -1
- package/dist/utils/validators.mjs.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge.cjs","sourceRoot":"","sources":["../../src/utils/bridge.ts"],"names":[],"mappings":";;;AAAA,wDAAuD;AACvD,wDAAoD;AACpD,uDAA2D;AAC3D,mEAAuD;AAEvD,2CAA6E;AAE7E,2DAI2B;AAC3B,oDAI6B;AAC7B,oDAAgD;AAChD,oDAI6B;AAM7B,wCAAmC;AAE5B,MAAM,+BAA+B,GAAG,GAA0B,EAAE;IACzE,OAAO,wCAA+B,CAAC;AACzC,CAAC,CAAC;AAFW,QAAA,+BAA+B,mCAE1C;AAEF;;;;;;;GAOG;AACH,MAAM,2BAA2B,GAAG,CAClC,OAAoB,EACpB,oBAAyD,EAC1C,EAAE;IACjB,OAAO,GAAG,IAAA,qCAAmB,EAAC,OAAO,CAAC,IAAI,6BAAoB,CAAC,oBAAoB,CAAC,EAAE,CAAC;AACzF,CAAC,CAAC;AAEF;;;;;;GAMG;AACI,MAAM,wBAAwB,GAAG,CACtC,OAA4C,EAC/B,EAAE;IACf,MAAM,aAAa,GAAG,IAAA,qCAAmB,EAAC,OAAO,CAAC,CAAC;IACnD,MAAM,WAAW,GACf,wCAA+B,CAC7B,IAAA,qCAAmB,EACjB,OAAO,CACwC,CAClD;QACD,wCAA+B,CAC7B,IAAA,oCAAkB,EAChB,OAAO,CACwC,CAClD,CAAC;IAEJ,IAAI,CAAC,WAAW,EAAE;QAChB,MAAM,IAAI,KAAK,CACb,mDAAmD,OAAO,EAAE,CAC7D,CAAC;KACH;IAED,OAAO;QACL,GAAG,WAAW;QACd,OAAO,EAAE,IAAA,oCAAkB,EAAC,OAAO,CAAC;QACpC,OAAO,EAAE,2BAA2B,CAAC,aAAa,EAAE,WAAW,CAAC,MAAM,CAAC;KACxE,CAAC;AACJ,CAAC,CA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KAChD;IACD,OAAO,OAAO,CAAC,QAAQ,EAAE,KAAK,eAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC;AACvD,CAAC,CAAC;AAPW,QAAA,gBAAgB,oBAO3B;AAEF;;;;;;GAMG;AACI,MAAM,YAAY,GAAG,CAC1B,UAA6C,EAC7C,WAAgD,EAChD,EAAE;IACF,IAAI;QACF,IAAI,CAAC,WAAW,EAAE;YAChB,OAAO,KAAK,CAAC;SACd;QACD,OAAO,IAAA,qCAAmB,EAAC,UAAU,CAAC,KAAK,IAAA,qCAAmB,EAAC,WAAW,CAAC,CAAC;KAC7E;IAAC,MAAM;QACN,OAAO,KAAK,CAAC;KACd;AACH,CAAC,CAAC;AAZW,QAAA,YAAY,gBAYvB","sourcesContent":["import { AddressZero } from '@ethersproject/constants';\nimport { Contract } from '@ethersproject/contracts';\nimport { BtcScope, SolScope } from '@metamask/keyring-api';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport type { CaipAssetType, CaipChainId } from '@metamask/utils';\nimport { isCaipChainId, isStrictHexString, type Hex } from '@metamask/utils';\n\nimport {\n formatChainIdToCaip,\n formatChainIdToDec,\n formatChainIdToHex,\n} from './caip-formatters';\nimport {\n DEFAULT_BRIDGE_CONTROLLER_STATE,\n ETH_USDT_ADDRESS,\n METABRIDGE_ETHEREUM_ADDRESS,\n} from '../constants/bridge';\nimport { CHAIN_IDS } from '../constants/chains';\nimport {\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP,\n SYMBOL_TO_SLIP44_MAP,\n type SupportedSwapsNativeCurrencySymbols,\n} from '../constants/tokens';\nimport type {\n BridgeAsset,\n BridgeControllerState,\n GenericQuoteRequest,\n} from '../types';\nimport { ChainId } from '../types';\n\nexport const getDefaultBridgeControllerState = (): BridgeControllerState => {\n return DEFAULT_BRIDGE_CONTROLLER_STATE;\n};\n\n/**\n * Returns the native assetType for a given chainId and native currency symbol\n * Note that the return value is used as the assetId although it is a CaipAssetType\n *\n * @param chainId - The chainId to get the native assetType for\n * @param nativeCurrencySymbol - The native currency symbol for the given chainId\n * @returns The native assetType for the given chainId\n */\nconst getNativeAssetCaipAssetType = (\n chainId: CaipChainId,\n nativeCurrencySymbol: SupportedSwapsNativeCurrencySymbols,\n): CaipAssetType => {\n return `${formatChainIdToCaip(chainId)}/${SYMBOL_TO_SLIP44_MAP[nativeCurrencySymbol]}`;\n};\n\n/**\n * Returns the native swaps or bridge asset for a given chainId\n *\n * @param chainId - The chainId to get the default token for\n * @returns The native asset for the given chainId\n * @throws If no native asset is defined for the given chainId\n */\nexport const getNativeAssetForChainId = (\n chainId: string | number | Hex | CaipChainId,\n): BridgeAsset => {\n const chainIdInCaip = formatChainIdToCaip(chainId);\n const nativeToken =\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n formatChainIdToCaip(\n chainId,\n ) as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ] ??\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n formatChainIdToHex(\n chainId,\n ) as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ];\n\n if (!nativeToken) {\n throw new Error(\n `No XChain Swaps native asset found for chainId: ${chainId}`,\n );\n }\n\n return {\n ...nativeToken,\n chainId: formatChainIdToDec(chainId),\n assetId: getNativeAssetCaipAssetType(chainIdInCaip, nativeToken.symbol),\n };\n};\n\n/**\n * A function to return the txParam data for setting allowance to 0 for USDT on Ethereum\n *\n * @returns The txParam data that will reset allowance to 0, combine it with the approval tx params received from Bridge API\n */\nexport const getEthUsdtResetData = () => {\n const UsdtContractInterface = new Contract(ETH_USDT_ADDRESS, abiERC20)\n .interface;\n const data = UsdtContractInterface.encodeFunctionData('approve', [\n METABRIDGE_ETHEREUM_ADDRESS,\n '0',\n ]);\n\n return data;\n};\n\nexport const isEthUsdt = (chainId: Hex, address: string) =>\n chainId === CHAIN_IDS.MAINNET &&\n address.toLowerCase() === ETH_USDT_ADDRESS.toLowerCase();\n\nexport const sumHexes = (...hexStrings: string[]): Hex => {\n if (hexStrings.length === 0) {\n return '0x0';\n }\n\n const sum = hexStrings.reduce((acc, hex) => acc + BigInt(hex), BigInt(0));\n return `0x${sum.toString(16)}`;\n};\n\n/**\n * Checks whether the provided address is strictly equal to the address for\n * the default swaps token of the provided chain.\n *\n * @param address - The string to compare to the default token address\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the address is the provided chain's default token address\n */\nexport const isSwapsDefaultTokenAddress = (\n address: string,\n chainId: Hex | CaipChainId,\n) => {\n if (!address || !chainId) {\n return false;\n }\n\n return address === getNativeAssetForChainId(chainId)?.address;\n};\n\n/**\n * Checks whether the provided symbol is strictly equal to the symbol for\n * the default swaps token of the provided chain.\n *\n * @param symbol - The string to compare to the default token symbol\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the symbol is the provided chain's default token symbol\n */\nexport const isSwapsDefaultTokenSymbol = (\n symbol: string,\n chainId: Hex | CaipChainId,\n) => {\n if (!symbol || !chainId) {\n return false;\n }\n\n return symbol === getNativeAssetForChainId(chainId)?.symbol;\n};\n\n/**\n * Checks whether the address is a native asset in any supported xchain swaps network\n *\n * @param address - The address to check\n * @returns Whether the address is a native asset\n */\nexport const isNativeAddress = (address?: string | null) =>\n address === AddressZero || // bridge and swap apis set the native asset address to zero\n address === '' || // assets controllers set the native asset address to an empty string\n !address ||\n (!isStrictHexString(address) &&\n Object.values(SYMBOL_TO_SLIP44_MAP).some(\n // check if it matches any supported SLIP44 references\n (reference) => address.includes(reference) || reference.endsWith(address),\n ));\n\n/**\n * Checks whether the chainId matches Solana in CaipChainId or number format\n *\n * @param chainId - The chainId to check\n * @returns Whether the chainId is Solana\n */\nexport const isSolanaChainId = (\n chainId: Hex | number | CaipChainId | string,\n) => {\n if (isCaipChainId(chainId)) {\n return chainId === SolScope.Mainnet.toString();\n }\n return chainId.toString() === ChainId.SOLANA.toString();\n};\n\nexport const isBitcoinChainId = (\n chainId: Hex | number | CaipChainId | string,\n) => {\n if (isCaipChainId(chainId)) {\n return chainId === BtcScope.Mainnet.toString();\n }\n return chainId.toString() === ChainId.BTC.toString();\n};\n\n/**\n * Checks whether the transaction is a cross-chain transaction by comparing the source and destination chainIds\n *\n * @param srcChainId - The source chainId\n * @param destChainId - The destination chainId\n * @returns Whether the transaction is a cross-chain transaction\n */\nexport const isCrossChain = (\n srcChainId: GenericQuoteRequest['srcChainId'],\n destChainId?: GenericQuoteRequest['destChainId'],\n) => {\n try {\n if (!destChainId) {\n return false;\n }\n return formatChainIdToCaip(srcChainId) !== formatChainIdToCaip(destChainId);\n } catch {\n return false;\n }\n};\n"]}
|
|
1
|
+
{"version":3,"file":"bridge.cjs","sourceRoot":"","sources":["../../src/utils/bridge.ts"],"names":[],"mappings":";;;AAAA,wDAAuD;AACvD,wDAAoD;AACpD,uDAA2D;AAC3D,mEAAuD;AAEvD,2CAA6E;AAE7E,2DAI2B;AAC3B,oDAI6B;AAC7B,oDAAgD;AAChD,oDAI6B;AAM7B,wCAAmC;AAE5B,MAAM,+BAA+B,GAAG,GAA0B,EAAE;IACzE,OAAO,wCAA+B,CAAC;AACzC,CAAC,CAAC;AAFW,QAAA,+BAA+B,mCAE1C;AAEF;;;;;;;GAOG;AACH,MAAM,2BAA2B,GAAG,CAClC,OAAoB,EACpB,oBAAyD,EAC1C,EAAE;IACjB,OAAO,GAAG,IAAA,qCAAmB,EAAC,OAAO,CAAC,IAAI,6BAAoB,CAAC,oBAAoB,CAAC,EAAE,CAAC;AACzF,CAAC,CAAC;AAEF;;;;;;GAMG;AACI,MAAM,wBAAwB,GAAG,CACtC,OAA4C,EAC/B,EAAE;IACf,MAAM,aAAa,GAAG,IAAA,qCAAmB,EAAC,OAAO,CAAC,CAAC;IACnD,MAAM,WAAW,GACf,wCAA+B,CAC7B,IAAA,qCAAmB,EACjB,OAAO,CACwC,CAClD;QACD,wCAA+B,CAC7B,IAAA,oCAAkB,EAChB,OAAO,CACwC,CAClD,CAAC;IAEJ,IAAI,CAA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AC,MAAM,CAAC,QAAQ,EAAE,CAAC;AAC1D,CAAC,CAAC;AAPW,QAAA,eAAe,mBAO1B;AAEK,MAAM,gBAAgB,GAAG,CAC9B,OAA4C,EAC5C,EAAE;IACF,IAAI,IAAA,qBAAa,EAAC,OAAO,CAAC,EAAE;QAC1B,OAAO,OAAO,KAAK,sBAAQ,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;KAChD;IACD,OAAO,OAAO,CAAC,QAAQ,EAAE,KAAK,eAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC;AACvD,CAAC,CAAC;AAPW,QAAA,gBAAgB,oBAO3B;AAEF;;;;;;GAMG;AACI,MAAM,eAAe,GAAG,CAC7B,OAA0C,EACjC,EAAE;IACX,OAAO,IAAA,uBAAe,EAAC,OAAO,CAAC,IAAI,IAAA,wBAAgB,EAAC,OAAO,CAAC,CAAC;AAC/D,CAAC,CAAC;AAJW,QAAA,eAAe,mBAI1B;AAEF;;;;;;GAMG;AACI,MAAM,YAAY,GAAG,CAC1B,UAA6C,EAC7C,WAAgD,EAChD,EAAE;IACF,IAAI;QACF,IAAI,CAAC,WAAW,EAAE;YAChB,OAAO,KAAK,CAAC;SACd;QACD,OAAO,IAAA,qCAAmB,EAAC,UAAU,CAAC,KAAK,IAAA,qCAAmB,EAAC,WAAW,CAAC,CAAC;KAC7E;IAAC,MAAM;QACN,OAAO,KAAK,CAAC;KACd;AACH,CAAC,CAAC;AAZW,QAAA,YAAY,gBAYvB","sourcesContent":["import { AddressZero } from '@ethersproject/constants';\nimport { Contract } from '@ethersproject/contracts';\nimport { BtcScope, SolScope } from '@metamask/keyring-api';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport type { CaipAssetType, CaipChainId } from '@metamask/utils';\nimport { isCaipChainId, isStrictHexString, type Hex } from '@metamask/utils';\n\nimport {\n formatChainIdToCaip,\n formatChainIdToDec,\n formatChainIdToHex,\n} from './caip-formatters';\nimport {\n DEFAULT_BRIDGE_CONTROLLER_STATE,\n ETH_USDT_ADDRESS,\n METABRIDGE_ETHEREUM_ADDRESS,\n} from '../constants/bridge';\nimport { CHAIN_IDS } from '../constants/chains';\nimport {\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP,\n SYMBOL_TO_SLIP44_MAP,\n type SupportedSwapsNativeCurrencySymbols,\n} from '../constants/tokens';\nimport type {\n BridgeAsset,\n BridgeControllerState,\n GenericQuoteRequest,\n} from '../types';\nimport { ChainId } from '../types';\n\nexport const getDefaultBridgeControllerState = (): BridgeControllerState => {\n return DEFAULT_BRIDGE_CONTROLLER_STATE;\n};\n\n/**\n * Returns the native assetType for a given chainId and native currency symbol\n * Note that the return value is used as the assetId although it is a CaipAssetType\n *\n * @param chainId - The chainId to get the native assetType for\n * @param nativeCurrencySymbol - The native currency symbol for the given chainId\n * @returns The native assetType for the given chainId\n */\nconst getNativeAssetCaipAssetType = (\n chainId: CaipChainId,\n nativeCurrencySymbol: SupportedSwapsNativeCurrencySymbols,\n): CaipAssetType => {\n return `${formatChainIdToCaip(chainId)}/${SYMBOL_TO_SLIP44_MAP[nativeCurrencySymbol]}`;\n};\n\n/**\n * Returns the native swaps or bridge asset for a given chainId\n *\n * @param chainId - The chainId to get the default token for\n * @returns The native asset for the given chainId\n * @throws If no native asset is defined for the given chainId\n */\nexport const getNativeAssetForChainId = (\n chainId: string | number | Hex | CaipChainId,\n): BridgeAsset => {\n const chainIdInCaip = formatChainIdToCaip(chainId);\n const nativeToken =\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n formatChainIdToCaip(\n chainId,\n ) as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ] ??\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n formatChainIdToHex(\n chainId,\n ) as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ];\n\n if (!nativeToken) {\n throw new Error(\n `No XChain Swaps native asset found for chainId: ${chainId}`,\n );\n }\n\n return {\n ...nativeToken,\n chainId: formatChainIdToDec(chainId),\n assetId: getNativeAssetCaipAssetType(chainIdInCaip, nativeToken.symbol),\n };\n};\n\n/**\n * A function to return the txParam data for setting allowance to 0 for USDT on Ethereum\n *\n * @returns The txParam data that will reset allowance to 0, combine it with the approval tx params received from Bridge API\n */\nexport const getEthUsdtResetData = () => {\n const UsdtContractInterface = new Contract(ETH_USDT_ADDRESS, abiERC20)\n .interface;\n const data = UsdtContractInterface.encodeFunctionData('approve', [\n METABRIDGE_ETHEREUM_ADDRESS,\n '0',\n ]);\n\n return data;\n};\n\nexport const isEthUsdt = (chainId: Hex, address: string) =>\n chainId === CHAIN_IDS.MAINNET &&\n address.toLowerCase() === ETH_USDT_ADDRESS.toLowerCase();\n\nexport const sumHexes = (...hexStrings: string[]): Hex => {\n if (hexStrings.length === 0) {\n return '0x0';\n }\n\n const sum = hexStrings.reduce((acc, hex) => acc + BigInt(hex), BigInt(0));\n return `0x${sum.toString(16)}`;\n};\n\n/**\n * Checks whether the provided address is strictly equal to the address for\n * the default swaps token of the provided chain.\n *\n * @param address - The string to compare to the default token address\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the address is the provided chain's default token address\n */\nexport const isSwapsDefaultTokenAddress = (\n address: string,\n chainId: Hex | CaipChainId,\n) => {\n if (!address || !chainId) {\n return false;\n }\n\n return address === getNativeAssetForChainId(chainId)?.address;\n};\n\n/**\n * Checks whether the provided symbol is strictly equal to the symbol for\n * the default swaps token of the provided chain.\n *\n * @param symbol - The string to compare to the default token symbol\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the symbol is the provided chain's default token symbol\n */\nexport const isSwapsDefaultTokenSymbol = (\n symbol: string,\n chainId: Hex | CaipChainId,\n) => {\n if (!symbol || !chainId) {\n return false;\n }\n\n return symbol === getNativeAssetForChainId(chainId)?.symbol;\n};\n\n/**\n * Checks whether the address is a native asset in any supported xchain swaps network\n *\n * @param address - The address to check\n * @returns Whether the address is a native asset\n */\nexport const isNativeAddress = (address?: string | null) =>\n address === AddressZero || // bridge and swap apis set the native asset address to zero\n address === '' || // assets controllers set the native asset address to an empty string\n !address ||\n (!isStrictHexString(address) &&\n Object.values(SYMBOL_TO_SLIP44_MAP).some(\n // check if it matches any supported SLIP44 references\n (reference) => address.includes(reference) || reference.endsWith(address),\n ));\n\n/**\n * Checks whether the chainId matches Solana in CaipChainId or number format\n *\n * @param chainId - The chainId to check\n * @returns Whether the chainId is Solana\n */\nexport const isSolanaChainId = (\n chainId: Hex | number | CaipChainId | string,\n) => {\n if (isCaipChainId(chainId)) {\n return chainId === SolScope.Mainnet.toString();\n }\n return chainId.toString() === ChainId.SOLANA.toString();\n};\n\nexport const isBitcoinChainId = (\n chainId: Hex | number | CaipChainId | string,\n) => {\n if (isCaipChainId(chainId)) {\n return chainId === BtcScope.Mainnet.toString();\n }\n return chainId.toString() === ChainId.BTC.toString();\n};\n\n/**\n * Checks if a chain ID represents a non-EVM blockchain supported by swaps\n * Currently supports Solana and Bitcoin\n *\n * @param chainId - The chain ID to check\n * @returns True if the chain is a supported non-EVM chain, false otherwise\n */\nexport const isNonEvmChainId = (\n chainId: GenericQuoteRequest['srcChainId'],\n): boolean => {\n return isSolanaChainId(chainId) || isBitcoinChainId(chainId);\n};\n\n/**\n * Checks whether the transaction is a cross-chain transaction by comparing the source and destination chainIds\n *\n * @param srcChainId - The source chainId\n * @param destChainId - The destination chainId\n * @returns Whether the transaction is a cross-chain transaction\n */\nexport const isCrossChain = (\n srcChainId: GenericQuoteRequest['srcChainId'],\n destChainId?: GenericQuoteRequest['destChainId'],\n) => {\n try {\n if (!destChainId) {\n return false;\n }\n return formatChainIdToCaip(srcChainId) !== formatChainIdToCaip(destChainId);\n } catch {\n return false;\n }\n};\n"]}
|
package/dist/utils/bridge.d.cts
CHANGED
|
@@ -51,6 +51,14 @@ export declare const isNativeAddress: (address?: string | null) => boolean;
|
|
|
51
51
|
*/
|
|
52
52
|
export declare const isSolanaChainId: (chainId: Hex | number | CaipChainId | string) => boolean;
|
|
53
53
|
export declare const isBitcoinChainId: (chainId: Hex | number | CaipChainId | string) => boolean;
|
|
54
|
+
/**
|
|
55
|
+
* Checks if a chain ID represents a non-EVM blockchain supported by swaps
|
|
56
|
+
* Currently supports Solana and Bitcoin
|
|
57
|
+
*
|
|
58
|
+
* @param chainId - The chain ID to check
|
|
59
|
+
* @returns True if the chain is a supported non-EVM chain, false otherwise
|
|
60
|
+
*/
|
|
61
|
+
export declare const isNonEvmChainId: (chainId: GenericQuoteRequest['srcChainId']) => boolean;
|
|
54
62
|
/**
|
|
55
63
|
* Checks whether the transaction is a cross-chain transaction by comparing the source and destination chainIds
|
|
56
64
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge.d.cts","sourceRoot":"","sources":["../../src/utils/bridge.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAiB,WAAW,EAAE,wBAAwB;AAClE,OAAO,EAAoC,KAAK,GAAG,EAAE,wBAAwB;AAkB7E,OAAO,KAAK,EACV,WAAW,EACX,qBAAqB,EACrB,mBAAmB,EACpB,qBAAiB;AAGlB,eAAO,MAAM,+BAA+B,QAAO,qBAElD,CAAC;AAiBF;;;;;;GAMG;AACH,eAAO,MAAM,wBAAwB,YAC1B,MAAM,GAAG,MAAM,GAAG,GAAG,GAAG,WAAW,KAC3C,WAyBF,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,cAS/B,CAAC;AAEF,eAAO,MAAM,SAAS,YAAa,GAAG,WAAW,MAAM,YAEG,CAAC;AAE3D,eAAO,MAAM,QAAQ,kBAAmB,MAAM,EAAE,KAAG,GAOlD,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,0BAA0B,YAC5B,MAAM,WACN,GAAG,GAAG,WAAW,YAO3B,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,yBAAyB,WAC5B,MAAM,WACL,GAAG,GAAG,WAAW,YAO3B,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MA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,eAAO,MAAM,eAAe,YACjB,GAAG,GAAG,MAAM,GAAG,WAAW,GAAG,MAAM,YAM7C,CAAC;AAEF,eAAO,MAAM,gBAAgB,YAClB,GAAG,GAAG,MAAM,GAAG,WAAW,GAAG,MAAM,YAM7C,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,eAAe,YACjB,mBAAmB,CAAC,YAAY,CAAC,KACzC,OAEF,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,YAAY,eACX,mBAAmB,CAAC,YAAY,CAAC,gBAC/B,mBAAmB,CAAC,aAAa,CAAC,YAUjD,CAAC"}
|
package/dist/utils/bridge.d.mts
CHANGED
|
@@ -51,6 +51,14 @@ export declare const isNativeAddress: (address?: string | null) => boolean;
|
|
|
51
51
|
*/
|
|
52
52
|
export declare const isSolanaChainId: (chainId: Hex | number | CaipChainId | string) => boolean;
|
|
53
53
|
export declare const isBitcoinChainId: (chainId: Hex | number | CaipChainId | string) => boolean;
|
|
54
|
+
/**
|
|
55
|
+
* Checks if a chain ID represents a non-EVM blockchain supported by swaps
|
|
56
|
+
* Currently supports Solana and Bitcoin
|
|
57
|
+
*
|
|
58
|
+
* @param chainId - The chain ID to check
|
|
59
|
+
* @returns True if the chain is a supported non-EVM chain, false otherwise
|
|
60
|
+
*/
|
|
61
|
+
export declare const isNonEvmChainId: (chainId: GenericQuoteRequest['srcChainId']) => boolean;
|
|
54
62
|
/**
|
|
55
63
|
* Checks whether the transaction is a cross-chain transaction by comparing the source and destination chainIds
|
|
56
64
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge.d.mts","sourceRoot":"","sources":["../../src/utils/bridge.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAiB,WAAW,EAAE,wBAAwB;AAClE,OAAO,EAAoC,KAAK,GAAG,EAAE,wBAAwB;AAkB7E,OAAO,KAAK,EACV,WAAW,EACX,qBAAqB,EACrB,mBAAmB,EACpB,qBAAiB;AAGlB,eAAO,M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,wBAAwB,YAC1B,MAAM,GAAG,MAAM,GAAG,GAAG,GAAG,WAAW,KAC3C,WAyBF,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,cAS/B,CAAC;AAEF,eAAO,MAAM,SAAS,YAAa,GAAG,WAAW,MAAM,YAEG,CAAC;AAE3D,eAAO,MAAM,QAAQ,kBAAmB,MAAM,EAAE,KAAG,GAOlD,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,0BAA0B,YAC5B,MAAM,WACN,GAAG,GAAG,WAAW,YAO3B,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,yBAAyB,WAC5B,MAAM,WACL,GAAG,GAAG,WAAW,YAO3B,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,eAAe,aAAc,MAAM,GAAG,IAAI,YAQjD,CAAC;AAEP;;;;;GAKG;AACH,eAAO,MAAM,eAAe,YACjB,GAAG,GAAG,MAAM,GAAG,WAAW,GAAG,MAAM,YAM7C,CAAC;AAEF,eAAO,MAAM,gBAAgB,YAClB,GAAG,GAAG,MAAM,GAAG,WAAW,GAAG,MAAM,YAM7C,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,eAAe,YACjB,mBAAmB,CAAC,YAAY,CAAC,KACzC,OAEF,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,YAAY,eACX,mBAAmB,CAAC,YAAY,CAAC,gBAC/B,mBAAmB,CAAC,aAAa,CAAC,YAUjD,CAAC"}
|
package/dist/utils/bridge.mjs
CHANGED
|
@@ -124,6 +124,16 @@ export const isBitcoinChainId = (chainId) => {
|
|
|
124
124
|
}
|
|
125
125
|
return chainId.toString() === ChainId.BTC.toString();
|
|
126
126
|
};
|
|
127
|
+
/**
|
|
128
|
+
* Checks if a chain ID represents a non-EVM blockchain supported by swaps
|
|
129
|
+
* Currently supports Solana and Bitcoin
|
|
130
|
+
*
|
|
131
|
+
* @param chainId - The chain ID to check
|
|
132
|
+
* @returns True if the chain is a supported non-EVM chain, false otherwise
|
|
133
|
+
*/
|
|
134
|
+
export const isNonEvmChainId = (chainId) => {
|
|
135
|
+
return isSolanaChainId(chainId) || isBitcoinChainId(chainId);
|
|
136
|
+
};
|
|
127
137
|
/**
|
|
128
138
|
* Checks whether the transaction is a cross-chain transaction by comparing the source and destination chainIds
|
|
129
139
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge.mjs","sourceRoot":"","sources":["../../src/utils/bridge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,iCAAiC;AACvD,OAAO,EAAE,QAAQ,EAAE,iCAAiC;AACpD,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,8BAA8B;AAC3D,OAAO,EAAE,QAAQ,EAAE,oCAAoC;AAEvD,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAY,wBAAwB;AAE7E,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,kBAAkB,EACnB,8BAA0B;AAC3B,OAAO,EACL,+BAA+B,EAC/B,gBAAgB,EAChB,2BAA2B,EAC5B,gCAA4B;AAC7B,OAAO,EAAE,SAAS,EAAE,gCAA4B;AAChD,OAAO,EACL,+BAA+B,EAC/B,oBAAoB,EAErB,gCAA4B;AAM7B,OAAO,EAAE,OAAO,EAAE,qBAAiB;AAEnC,MAAM,CAAC,MAAM,+BAA+B,GAAG,GAA0B,EAAE;IACzE,OAAO,+BAA+B,CAAC;AACzC,CAAC,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,2BAA2B,GAAG,CAClC,OAAoB,EACpB,oBAAyD,EAC1C,EAAE;IACjB,OAAO,GAAG,mBAAmB,CAAC,OAAO,CAAC,IAAI,oBAAoB,CAAC,oBAAoB,CAAC,EAAE,CAAC;AACzF,CAAC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,CACtC,OAA4C,EAC/B,EAAE;IACf,MAAM,aAAa,GAAG,mBAAmB,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QAAQ,EAAE,KAAK,OAAO,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;AAC1D,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAC9B,OAA4C,EAC5C,EAAE;IACF,IAAI,aAAa,CAAC,OAAO,CAAC,EAAE;QAC1B,OAAO,OAAO,KAAK,QAAQ,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;KAChD;IACD,OAAO,OAAO,CAAC,QAAQ,EAAE,KAAK,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC;AACvD,CAAC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,CAC1B,UAA6C,EAC7C,WAAgD,EAChD,EAAE;IACF,IAAI;QACF,IAAI,CAAC,WAAW,EAAE;YAChB,OAAO,KAAK,CAAC;SACd;QACD,OAAO,mBAAmB,CAAC,UAAU,CAAC,KAAK,mBAAmB,CAAC,WAAW,CAAC,CAAC;KAC7E;IAAC,MAAM;QACN,OAAO,KAAK,CAAC;KACd;AACH,CAAC,CAAC","sourcesContent":["import { AddressZero } from '@ethersproject/constants';\nimport { Contract } from '@ethersproject/contracts';\nimport { BtcScope, SolScope } from '@metamask/keyring-api';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport type { CaipAssetType, CaipChainId } from '@metamask/utils';\nimport { isCaipChainId, isStrictHexString, type Hex } from '@metamask/utils';\n\nimport {\n formatChainIdToCaip,\n formatChainIdToDec,\n formatChainIdToHex,\n} from './caip-formatters';\nimport {\n DEFAULT_BRIDGE_CONTROLLER_STATE,\n ETH_USDT_ADDRESS,\n METABRIDGE_ETHEREUM_ADDRESS,\n} from '../constants/bridge';\nimport { CHAIN_IDS } from '../constants/chains';\nimport {\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP,\n SYMBOL_TO_SLIP44_MAP,\n type SupportedSwapsNativeCurrencySymbols,\n} from '../constants/tokens';\nimport type {\n BridgeAsset,\n BridgeControllerState,\n GenericQuoteRequest,\n} from '../types';\nimport { ChainId } from '../types';\n\nexport const getDefaultBridgeControllerState = (): BridgeControllerState => {\n return DEFAULT_BRIDGE_CONTROLLER_STATE;\n};\n\n/**\n * Returns the native assetType for a given chainId and native currency symbol\n * Note that the return value is used as the assetId although it is a CaipAssetType\n *\n * @param chainId - The chainId to get the native assetType for\n * @param nativeCurrencySymbol - The native currency symbol for the given chainId\n * @returns The native assetType for the given chainId\n */\nconst getNativeAssetCaipAssetType = (\n chainId: CaipChainId,\n nativeCurrencySymbol: SupportedSwapsNativeCurrencySymbols,\n): CaipAssetType => {\n return `${formatChainIdToCaip(chainId)}/${SYMBOL_TO_SLIP44_MAP[nativeCurrencySymbol]}`;\n};\n\n/**\n * Returns the native swaps or bridge asset for a given chainId\n *\n * @param chainId - The chainId to get the default token for\n * @returns The native asset for the given chainId\n * @throws If no native asset is defined for the given chainId\n */\nexport const getNativeAssetForChainId = (\n chainId: string | number | Hex | CaipChainId,\n): BridgeAsset => {\n const chainIdInCaip = formatChainIdToCaip(chainId);\n const nativeToken =\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n formatChainIdToCaip(\n chainId,\n ) as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ] ??\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n formatChainIdToHex(\n chainId,\n ) as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ];\n\n if (!nativeToken) {\n throw new Error(\n `No XChain Swaps native asset found for chainId: ${chainId}`,\n );\n }\n\n return {\n ...nativeToken,\n chainId: formatChainIdToDec(chainId),\n assetId: getNativeAssetCaipAssetType(chainIdInCaip, nativeToken.symbol),\n };\n};\n\n/**\n * A function to return the txParam data for setting allowance to 0 for USDT on Ethereum\n *\n * @returns The txParam data that will reset allowance to 0, combine it with the approval tx params received from Bridge API\n */\nexport const getEthUsdtResetData = () => {\n const UsdtContractInterface = new Contract(ETH_USDT_ADDRESS, abiERC20)\n .interface;\n const data = UsdtContractInterface.encodeFunctionData('approve', [\n METABRIDGE_ETHEREUM_ADDRESS,\n '0',\n ]);\n\n return data;\n};\n\nexport const isEthUsdt = (chainId: Hex, address: string) =>\n chainId === CHAIN_IDS.MAINNET &&\n address.toLowerCase() === ETH_USDT_ADDRESS.toLowerCase();\n\nexport const sumHexes = (...hexStrings: string[]): Hex => {\n if (hexStrings.length === 0) {\n return '0x0';\n }\n\n const sum = hexStrings.reduce((acc, hex) => acc + BigInt(hex), BigInt(0));\n return `0x${sum.toString(16)}`;\n};\n\n/**\n * Checks whether the provided address is strictly equal to the address for\n * the default swaps token of the provided chain.\n *\n * @param address - The string to compare to the default token address\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the address is the provided chain's default token address\n */\nexport const isSwapsDefaultTokenAddress = (\n address: string,\n chainId: Hex | CaipChainId,\n) => {\n if (!address || !chainId) {\n return false;\n }\n\n return address === getNativeAssetForChainId(chainId)?.address;\n};\n\n/**\n * Checks whether the provided symbol is strictly equal to the symbol for\n * the default swaps token of the provided chain.\n *\n * @param symbol - The string to compare to the default token symbol\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the symbol is the provided chain's default token symbol\n */\nexport const isSwapsDefaultTokenSymbol = (\n symbol: string,\n chainId: Hex | CaipChainId,\n) => {\n if (!symbol || !chainId) {\n return false;\n }\n\n return symbol === getNativeAssetForChainId(chainId)?.symbol;\n};\n\n/**\n * Checks whether the address is a native asset in any supported xchain swaps network\n *\n * @param address - The address to check\n * @returns Whether the address is a native asset\n */\nexport const isNativeAddress = (address?: string | null) =>\n address === AddressZero || // bridge and swap apis set the native asset address to zero\n address === '' || // assets controllers set the native asset address to an empty string\n !address ||\n (!isStrictHexString(address) &&\n Object.values(SYMBOL_TO_SLIP44_MAP).some(\n // check if it matches any supported SLIP44 references\n (reference) => address.includes(reference) || reference.endsWith(address),\n ));\n\n/**\n * Checks whether the chainId matches Solana in CaipChainId or number format\n *\n * @param chainId - The chainId to check\n * @returns Whether the chainId is Solana\n */\nexport const isSolanaChainId = (\n chainId: Hex | number | CaipChainId | string,\n) => {\n if (isCaipChainId(chainId)) {\n return chainId === SolScope.Mainnet.toString();\n }\n return chainId.toString() === ChainId.SOLANA.toString();\n};\n\nexport const isBitcoinChainId = (\n chainId: Hex | number | CaipChainId | string,\n) => {\n if (isCaipChainId(chainId)) {\n return chainId === BtcScope.Mainnet.toString();\n }\n return chainId.toString() === ChainId.BTC.toString();\n};\n\n/**\n * Checks whether the transaction is a cross-chain transaction by comparing the source and destination chainIds\n *\n * @param srcChainId - The source chainId\n * @param destChainId - The destination chainId\n * @returns Whether the transaction is a cross-chain transaction\n */\nexport const isCrossChain = (\n srcChainId: GenericQuoteRequest['srcChainId'],\n destChainId?: GenericQuoteRequest['destChainId'],\n) => {\n try {\n if (!destChainId) {\n return false;\n }\n return formatChainIdToCaip(srcChainId) !== formatChainIdToCaip(destChainId);\n } catch {\n return false;\n }\n};\n"]}
|
|
1
|
+
{"version":3,"file":"bridge.mjs","sourceRoot":"","sources":["../../src/utils/bridge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,iCAAiC;AACvD,OAAO,EAAE,QAAQ,EAAE,iCAAiC;AACpD,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,8BAA8B;AAC3D,OAAO,EAAE,QAAQ,EAAE,oCAAoC;AAEvD,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAY,wBAAwB;AAE7E,OAAO,EACL,mBAAmB,EACnB,kBAAkB,EAClB,kBAAkB,EACnB,8BAA0B;AAC3B,OAAO,EACL,+BAA+B,EAC/B,gBAAgB,EAChB,2BAA2B,EAC5B,gCAA4B;AAC7B,OAAO,EAAE,SAAS,EAAE,gCAA4B;AAChD,OAAO,EACL,+BAA+B,EAC/B,oBAAoB,EAErB,gCAA4B;AAM7B,OAAO,EAAE,OAAO,EAAE,qBAAiB;AAEnC,MAAM,CAAC,MAAM,+BAA+B,GAAG,GAA0B,EAAE;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port { Contract } from '@ethersproject/contracts';\nimport { BtcScope, SolScope } from '@metamask/keyring-api';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport type { CaipAssetType, CaipChainId } from '@metamask/utils';\nimport { isCaipChainId, isStrictHexString, type Hex } from '@metamask/utils';\n\nimport {\n formatChainIdToCaip,\n formatChainIdToDec,\n formatChainIdToHex,\n} from './caip-formatters';\nimport {\n DEFAULT_BRIDGE_CONTROLLER_STATE,\n ETH_USDT_ADDRESS,\n METABRIDGE_ETHEREUM_ADDRESS,\n} from '../constants/bridge';\nimport { CHAIN_IDS } from '../constants/chains';\nimport {\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP,\n SYMBOL_TO_SLIP44_MAP,\n type SupportedSwapsNativeCurrencySymbols,\n} from '../constants/tokens';\nimport type {\n BridgeAsset,\n BridgeControllerState,\n GenericQuoteRequest,\n} from '../types';\nimport { ChainId } from '../types';\n\nexport const getDefaultBridgeControllerState = (): BridgeControllerState => {\n return DEFAULT_BRIDGE_CONTROLLER_STATE;\n};\n\n/**\n * Returns the native assetType for a given chainId and native currency symbol\n * Note that the return value is used as the assetId although it is a CaipAssetType\n *\n * @param chainId - The chainId to get the native assetType for\n * @param nativeCurrencySymbol - The native currency symbol for the given chainId\n * @returns The native assetType for the given chainId\n */\nconst getNativeAssetCaipAssetType = (\n chainId: CaipChainId,\n nativeCurrencySymbol: SupportedSwapsNativeCurrencySymbols,\n): CaipAssetType => {\n return `${formatChainIdToCaip(chainId)}/${SYMBOL_TO_SLIP44_MAP[nativeCurrencySymbol]}`;\n};\n\n/**\n * Returns the native swaps or bridge asset for a given chainId\n *\n * @param chainId - The chainId to get the default token for\n * @returns The native asset for the given chainId\n * @throws If no native asset is defined for the given chainId\n */\nexport const getNativeAssetForChainId = (\n chainId: string | number | Hex | CaipChainId,\n): BridgeAsset => {\n const chainIdInCaip = formatChainIdToCaip(chainId);\n const nativeToken =\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n formatChainIdToCaip(\n chainId,\n ) as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ] ??\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n formatChainIdToHex(\n chainId,\n ) as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ];\n\n if (!nativeToken) {\n throw new Error(\n `No XChain Swaps native asset found for chainId: ${chainId}`,\n );\n }\n\n return {\n ...nativeToken,\n chainId: formatChainIdToDec(chainId),\n assetId: getNativeAssetCaipAssetType(chainIdInCaip, nativeToken.symbol),\n };\n};\n\n/**\n * A function to return the txParam data for setting allowance to 0 for USDT on Ethereum\n *\n * @returns The txParam data that will reset allowance to 0, combine it with the approval tx params received from Bridge API\n */\nexport const getEthUsdtResetData = () => {\n const UsdtContractInterface = new Contract(ETH_USDT_ADDRESS, abiERC20)\n .interface;\n const data = UsdtContractInterface.encodeFunctionData('approve', [\n METABRIDGE_ETHEREUM_ADDRESS,\n '0',\n ]);\n\n return data;\n};\n\nexport const isEthUsdt = (chainId: Hex, address: string) =>\n chainId === CHAIN_IDS.MAINNET &&\n address.toLowerCase() === ETH_USDT_ADDRESS.toLowerCase();\n\nexport const sumHexes = (...hexStrings: string[]): Hex => {\n if (hexStrings.length === 0) {\n return '0x0';\n }\n\n const sum = hexStrings.reduce((acc, hex) => acc + BigInt(hex), BigInt(0));\n return `0x${sum.toString(16)}`;\n};\n\n/**\n * Checks whether the provided address is strictly equal to the address for\n * the default swaps token of the provided chain.\n *\n * @param address - The string to compare to the default token address\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the address is the provided chain's default token address\n */\nexport const isSwapsDefaultTokenAddress = (\n address: string,\n chainId: Hex | CaipChainId,\n) => {\n if (!address || !chainId) {\n return false;\n }\n\n return address === getNativeAssetForChainId(chainId)?.address;\n};\n\n/**\n * Checks whether the provided symbol is strictly equal to the symbol for\n * the default swaps token of the provided chain.\n *\n * @param symbol - The string to compare to the default token symbol\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the symbol is the provided chain's default token symbol\n */\nexport const isSwapsDefaultTokenSymbol = (\n symbol: string,\n chainId: Hex | CaipChainId,\n) => {\n if (!symbol || !chainId) {\n return false;\n }\n\n return symbol === getNativeAssetForChainId(chainId)?.symbol;\n};\n\n/**\n * Checks whether the address is a native asset in any supported xchain swaps network\n *\n * @param address - The address to check\n * @returns Whether the address is a native asset\n */\nexport const isNativeAddress = (address?: string | null) =>\n address === AddressZero || // bridge and swap apis set the native asset address to zero\n address === '' || // assets controllers set the native asset address to an empty string\n !address ||\n (!isStrictHexString(address) &&\n Object.values(SYMBOL_TO_SLIP44_MAP).some(\n // check if it matches any supported SLIP44 references\n (reference) => address.includes(reference) || reference.endsWith(address),\n ));\n\n/**\n * Checks whether the chainId matches Solana in CaipChainId or number format\n *\n * @param chainId - The chainId to check\n * @returns Whether the chainId is Solana\n */\nexport const isSolanaChainId = (\n chainId: Hex | number | CaipChainId | string,\n) => {\n if (isCaipChainId(chainId)) {\n return chainId === SolScope.Mainnet.toString();\n }\n return chainId.toString() === ChainId.SOLANA.toString();\n};\n\nexport const isBitcoinChainId = (\n chainId: Hex | number | CaipChainId | string,\n) => {\n if (isCaipChainId(chainId)) {\n return chainId === BtcScope.Mainnet.toString();\n }\n return chainId.toString() === ChainId.BTC.toString();\n};\n\n/**\n * Checks if a chain ID represents a non-EVM blockchain supported by swaps\n * Currently supports Solana and Bitcoin\n *\n * @param chainId - The chain ID to check\n * @returns True if the chain is a supported non-EVM chain, false otherwise\n */\nexport const isNonEvmChainId = (\n chainId: GenericQuoteRequest['srcChainId'],\n): boolean => {\n return isSolanaChainId(chainId) || isBitcoinChainId(chainId);\n};\n\n/**\n * Checks whether the transaction is a cross-chain transaction by comparing the source and destination chainIds\n *\n * @param srcChainId - The source chainId\n * @param destChainId - The destination chainId\n * @returns Whether the transaction is a cross-chain transaction\n */\nexport const isCrossChain = (\n srcChainId: GenericQuoteRequest['srcChainId'],\n destChainId?: GenericQuoteRequest['destChainId'],\n) => {\n try {\n if (!destChainId) {\n return false;\n }\n return formatChainIdToCaip(srcChainId) !== formatChainIdToCaip(destChainId);\n } catch {\n return false;\n }\n};\n"]}
|
package/dist/utils/fetch.cjs
CHANGED
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.fetchAssetPrices = exports.fetchBridgeQuotes = exports.fetchBridgeTokens = exports.getClientIdHeader = void 0;
|
|
4
4
|
const superstruct_1 = require("@metamask/superstruct");
|
|
5
5
|
const utils_1 = require("@metamask/utils");
|
|
6
|
+
const bridge_1 = require("./bridge.cjs");
|
|
6
7
|
const caip_formatters_1 = require("./caip-formatters.cjs");
|
|
7
8
|
const validators_1 = require("./validators.cjs");
|
|
8
9
|
const CACHE_REFRESH_TEN_MINUTES = 10 * utils_1.Duration.Minute;
|
|
@@ -92,6 +93,10 @@ async function fetchBridgeQuotes(request, signal, clientId, fetchFn, bridgeApiBa
|
|
|
92
93
|
const uniqueValidationFailures = new Set([]);
|
|
93
94
|
const filteredQuotes = quotes.filter((quoteResponse) => {
|
|
94
95
|
try {
|
|
96
|
+
const isBitcoinQuote = (0, bridge_1.isBitcoinChainId)(request.srcChainId);
|
|
97
|
+
if (isBitcoinQuote) {
|
|
98
|
+
return (0, validators_1.validateBitcoinQuoteResponse)(quoteResponse);
|
|
99
|
+
}
|
|
95
100
|
return (0, validators_1.validateQuoteResponse)(quoteResponse);
|
|
96
101
|
}
|
|
97
102
|
catch (error) {
|
package/dist/utils/fetch.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.cjs","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":";;;AAAA,uDAAoD;AAEpD,2CAA2C;AAE3C,2DAG2B;AAC3B,iDAA+E;AAS/E,MAAM,yBAAyB,GAAG,EAAE,GAAG,gBAAQ,CAAC,MAAM,CAAC;AAEhD,MAAM,iBAAiB,GAAG,CAAC,QAAgB,EAAE,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AG,CAAC,OAAwB,CAAC,GAAG,EAAE,CAAC;qBACpC;oBACD,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,EAAE;wBAC5D,GAAG,CAAC,OAAwB,CAAC,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;oBAClD,CAAC,CAAC,CAAC;gBACL,CAAC,CAAC,CAAC;aACJ;YACD,OAAO,GAAG,CAAC;QACb,CAAC,EACD,EAA2D,CAC5D,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC;AAnCW,QAAA,gBAAgB,oBAmC3B","sourcesContent":["import { StructError } from '@metamask/superstruct';\nimport type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';\nimport { Duration } from '@metamask/utils';\n\nimport {\n formatAddressToCaipReference,\n formatChainIdToDec,\n} from './caip-formatters';\nimport { validateQuoteResponse, validateSwapsTokenObject } from './validators';\nimport type {\n QuoteResponse,\n FetchFunction,\n GenericQuoteRequest,\n QuoteRequest,\n BridgeAsset,\n} from '../types';\n\nconst CACHE_REFRESH_TEN_MINUTES = 10 * Duration.Minute;\n\nexport const getClientIdHeader = (clientId: string) => ({\n 'X-Client-Id': clientId,\n});\n\n/**\n * Returns a list of enabled (unblocked) tokens\n *\n * @param chainId - The chain ID to fetch tokens for\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of enabled (unblocked) tokens\n */\nexport async function fetchBridgeTokens(\n chainId: Hex | CaipChainId,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<Record<string, BridgeAsset>> {\n // TODO make token api v2 call\n const url = `${bridgeApiBaseUrl}/getTokens?chainId=${formatChainIdToDec(chainId)}`;\n\n // TODO we will need to cache these. In Extension fetchWithCache is used. This is due to the following:\n // If we allow selecting dest networks which the user has not imported,\n // note that the Assets controller won't be able to provide tokens. In extension we fetch+cache the token list from bridge-api to handle this\n const tokens = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: CACHE_REFRESH_TEN_MINUTES },\n functionName: 'fetchBridgeTokens',\n });\n\n const transformedTokens: Record<string, BridgeAsset> = {};\n tokens.forEach((token: unknown) => {\n if (validateSwapsTokenObject(token)) {\n transformedTokens[token.address] = token;\n }\n });\n return transformedTokens;\n}\n\n/**\n * Converts the generic quote request to the type that the bridge-api expects\n * then fetches quotes from the bridge-api\n *\n * @param request - The quote request\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of bridge tx quotes\n */\nexport async function fetchBridgeQuotes(\n request: GenericQuoteRequest,\n signal: AbortSignal | null,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<{\n quotes: QuoteResponse[];\n validationFailures: string[];\n}> {\n const destWalletAddress = request.destWalletAddress ?? request.walletAddress;\n // Transform the generic quote request into QuoteRequest\n const normalizedRequest: QuoteRequest = {\n walletAddress: formatAddressToCaipReference(request.walletAddress),\n destWalletAddress: formatAddressToCaipReference(destWalletAddress),\n srcChainId: formatChainIdToDec(request.srcChainId),\n destChainId: formatChainIdToDec(request.destChainId),\n srcTokenAddress: formatAddressToCaipReference(request.srcTokenAddress),\n destTokenAddress: formatAddressToCaipReference(request.destTokenAddress),\n srcTokenAmount: request.srcTokenAmount,\n insufficientBal: Boolean(request.insufficientBal),\n resetApproval: Boolean(request.resetApproval),\n gasIncluded: Boolean(request.gasIncluded),\n gasIncluded7702: Boolean(request.gasIncluded7702),\n };\n if (request.slippage !== undefined) {\n normalizedRequest.slippage = request.slippage;\n }\n if (request.noFee !== undefined) {\n normalizedRequest.noFee = request.noFee;\n }\n if (request.aggIds && request.aggIds.length > 0) {\n normalizedRequest.aggIds = request.aggIds;\n }\n if (request.bridgeIds && request.bridgeIds.length > 0) {\n normalizedRequest.bridgeIds = request.bridgeIds;\n }\n\n const queryParams = new URLSearchParams();\n Object.entries(normalizedRequest).forEach(([key, value]) => {\n queryParams.append(key, value.toString());\n });\n const url = `${bridgeApiBaseUrl}/getQuote?${queryParams}`;\n const quotes: unknown[] = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n signal,\n cacheOptions: { cacheRefreshTime: 0 },\n functionName: 'fetchBridgeQuotes',\n });\n\n const uniqueValidationFailures: Set<string> = new Set<string>([]);\n const filteredQuotes = quotes.filter(\n (quoteResponse: unknown): quoteResponse is QuoteResponse => {\n try {\n return validateQuoteResponse(quoteResponse);\n } catch (error) {\n if (error instanceof StructError) {\n error.failures().forEach(({ branch, path }) => {\n const aggregatorId =\n branch?.[0]?.quote?.bridgeId ||\n branch?.[0]?.quote?.bridges?.[0] ||\n (quoteResponse as QuoteResponse)?.quote?.bridgeId ||\n (quoteResponse as QuoteResponse)?.quote?.bridges?.[0] ||\n 'unknown';\n const pathString = path?.join('.') || 'unknown';\n uniqueValidationFailures.add([aggregatorId, pathString].join('|'));\n });\n }\n return false;\n }\n },\n );\n\n const validationFailures = Array.from(uniqueValidationFailures);\n if (uniqueValidationFailures.size > 0) {\n console.warn('Quote validation failed', validationFailures);\n }\n\n return {\n quotes: filteredQuotes,\n validationFailures,\n };\n}\n\nconst fetchAssetPricesForCurrency = async (request: {\n currency: string;\n assetIds: Set<CaipAssetType>;\n clientId: string;\n fetchFn: FetchFunction;\n}): Promise<Record<CaipAssetType, { [currency: string]: string }>> => {\n const { currency, assetIds, clientId, fetchFn } = request;\n const validAssetIds = Array.from(assetIds).filter(Boolean);\n if (validAssetIds.length === 0) {\n return {};\n }\n\n const queryParams = new URLSearchParams({\n assetIds: validAssetIds.filter(Boolean).join(','),\n vsCurrency: currency,\n });\n const url = `https://price.api.cx.metamask.io/v3/spot-prices?${queryParams}`;\n const priceApiResponse = (await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: Number(Duration.Second * 30) },\n functionName: 'fetchAssetExchangeRates',\n })) as Record<CaipAssetType, { [currency: string]: number }>;\n\n if (!priceApiResponse || typeof priceApiResponse !== 'object') {\n return {};\n }\n\n return Object.entries(priceApiResponse).reduce(\n (acc, [assetId, currencyToPrice]) => {\n if (!currencyToPrice) {\n return acc;\n }\n if (!acc[assetId as CaipAssetType]) {\n acc[assetId as CaipAssetType] = {};\n }\n if (currencyToPrice[currency]) {\n acc[assetId as CaipAssetType][currency] =\n currencyToPrice[currency].toString();\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n};\n\n/**\n * Fetches the asset prices from the price API for multiple currencies\n *\n * @param request - The request object\n * @returns The asset prices by assetId\n */\nexport const fetchAssetPrices = async (\n request: {\n currencies: Set<string>;\n } & Omit<Parameters<typeof fetchAssetPricesForCurrency>[0], 'currency'>,\n): Promise<\n Record<CaipAssetType, { [currency: string]: string } | undefined>\n> => {\n const { currencies, ...args } = request;\n\n const combinedPrices = await Promise.allSettled(\n Array.from(currencies).map(\n async (currency) =>\n await fetchAssetPricesForCurrency({ ...args, currency }),\n ),\n ).then((priceApiResponse) => {\n return priceApiResponse.reduce(\n (acc, result) => {\n if (result.status === 'fulfilled') {\n Object.entries(result.value).forEach(([assetId, currencyToPrice]) => {\n const existingPrices = acc[assetId as CaipAssetType];\n if (!existingPrices) {\n acc[assetId as CaipAssetType] = {};\n }\n Object.entries(currencyToPrice).forEach(([currency, price]) => {\n acc[assetId as CaipAssetType][currency] = price;\n });\n });\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n });\n\n return combinedPrices;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"fetch.cjs","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":";;;AAAA,uDAAoD;AAEpD,2CAA2C;AAE3C,yCAA4C;AAC5C,2DAG2B;AAC3B,iDAIsB;AAStB,MAAM,yBA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AM,CAAC,MAAM,KAAK,WAAW,EAAE;gBACjC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,EAAE,eAAe,CAAC,EAAE,EAAE;oBAClE,MAAM,cAAc,GAAG,GAAG,CAAC,OAAwB,CAAC,CAAC;oBACrD,IAAI,CAAC,cAAc,EAAE;wBACnB,GAAG,CAAC,OAAwB,CAAC,GAAG,EAAE,CAAC;qBACpC;oBACD,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,EAAE;wBAC5D,GAAG,CAAC,OAAwB,CAAC,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;oBAClD,CAAC,CAAC,CAAC;gBACL,CAAC,CAAC,CAAC;aACJ;YACD,OAAO,GAAG,CAAC;QACb,CAAC,EACD,EAA2D,CAC5D,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC;AAnCW,QAAA,gBAAgB,oBAmC3B","sourcesContent":["import { StructError } from '@metamask/superstruct';\nimport type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';\nimport { Duration } from '@metamask/utils';\n\nimport { isBitcoinChainId } from './bridge';\nimport {\n formatAddressToCaipReference,\n formatChainIdToDec,\n} from './caip-formatters';\nimport {\n validateQuoteResponse,\n validateBitcoinQuoteResponse,\n validateSwapsTokenObject,\n} from './validators';\nimport type {\n QuoteResponse,\n FetchFunction,\n GenericQuoteRequest,\n QuoteRequest,\n BridgeAsset,\n} from '../types';\n\nconst CACHE_REFRESH_TEN_MINUTES = 10 * Duration.Minute;\n\nexport const getClientIdHeader = (clientId: string) => ({\n 'X-Client-Id': clientId,\n});\n\n/**\n * Returns a list of enabled (unblocked) tokens\n *\n * @param chainId - The chain ID to fetch tokens for\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of enabled (unblocked) tokens\n */\nexport async function fetchBridgeTokens(\n chainId: Hex | CaipChainId,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<Record<string, BridgeAsset>> {\n // TODO make token api v2 call\n const url = `${bridgeApiBaseUrl}/getTokens?chainId=${formatChainIdToDec(chainId)}`;\n\n // TODO we will need to cache these. In Extension fetchWithCache is used. This is due to the following:\n // If we allow selecting dest networks which the user has not imported,\n // note that the Assets controller won't be able to provide tokens. In extension we fetch+cache the token list from bridge-api to handle this\n const tokens = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: CACHE_REFRESH_TEN_MINUTES },\n functionName: 'fetchBridgeTokens',\n });\n\n const transformedTokens: Record<string, BridgeAsset> = {};\n tokens.forEach((token: unknown) => {\n if (validateSwapsTokenObject(token)) {\n transformedTokens[token.address] = token;\n }\n });\n return transformedTokens;\n}\n\n/**\n * Converts the generic quote request to the type that the bridge-api expects\n * then fetches quotes from the bridge-api\n *\n * @param request - The quote request\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of bridge tx quotes\n */\nexport async function fetchBridgeQuotes(\n request: GenericQuoteRequest,\n signal: AbortSignal | null,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<{\n quotes: QuoteResponse[];\n validationFailures: string[];\n}> {\n const destWalletAddress = request.destWalletAddress ?? request.walletAddress;\n // Transform the generic quote request into QuoteRequest\n const normalizedRequest: QuoteRequest = {\n walletAddress: formatAddressToCaipReference(request.walletAddress),\n destWalletAddress: formatAddressToCaipReference(destWalletAddress),\n srcChainId: formatChainIdToDec(request.srcChainId),\n destChainId: formatChainIdToDec(request.destChainId),\n srcTokenAddress: formatAddressToCaipReference(request.srcTokenAddress),\n destTokenAddress: formatAddressToCaipReference(request.destTokenAddress),\n srcTokenAmount: request.srcTokenAmount,\n insufficientBal: Boolean(request.insufficientBal),\n resetApproval: Boolean(request.resetApproval),\n gasIncluded: Boolean(request.gasIncluded),\n gasIncluded7702: Boolean(request.gasIncluded7702),\n };\n if (request.slippage !== undefined) {\n normalizedRequest.slippage = request.slippage;\n }\n if (request.noFee !== undefined) {\n normalizedRequest.noFee = request.noFee;\n }\n if (request.aggIds && request.aggIds.length > 0) {\n normalizedRequest.aggIds = request.aggIds;\n }\n if (request.bridgeIds && request.bridgeIds.length > 0) {\n normalizedRequest.bridgeIds = request.bridgeIds;\n }\n\n const queryParams = new URLSearchParams();\n Object.entries(normalizedRequest).forEach(([key, value]) => {\n queryParams.append(key, value.toString());\n });\n const url = `${bridgeApiBaseUrl}/getQuote?${queryParams}`;\n const quotes: unknown[] = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n signal,\n cacheOptions: { cacheRefreshTime: 0 },\n functionName: 'fetchBridgeQuotes',\n });\n\n const uniqueValidationFailures: Set<string> = new Set<string>([]);\n const filteredQuotes = quotes.filter(\n (quoteResponse: unknown): quoteResponse is QuoteResponse => {\n try {\n const isBitcoinQuote = isBitcoinChainId(request.srcChainId);\n\n if (isBitcoinQuote) {\n return validateBitcoinQuoteResponse(quoteResponse);\n }\n return validateQuoteResponse(quoteResponse);\n } catch (error) {\n if (error instanceof StructError) {\n error.failures().forEach(({ branch, path }) => {\n const aggregatorId =\n branch?.[0]?.quote?.bridgeId ||\n branch?.[0]?.quote?.bridges?.[0] ||\n (quoteResponse as QuoteResponse)?.quote?.bridgeId ||\n (quoteResponse as QuoteResponse)?.quote?.bridges?.[0] ||\n 'unknown';\n const pathString = path?.join('.') || 'unknown';\n uniqueValidationFailures.add([aggregatorId, pathString].join('|'));\n });\n }\n return false;\n }\n },\n );\n\n const validationFailures = Array.from(uniqueValidationFailures);\n if (uniqueValidationFailures.size > 0) {\n console.warn('Quote validation failed', validationFailures);\n }\n\n return {\n quotes: filteredQuotes,\n validationFailures,\n };\n}\n\nconst fetchAssetPricesForCurrency = async (request: {\n currency: string;\n assetIds: Set<CaipAssetType>;\n clientId: string;\n fetchFn: FetchFunction;\n}): Promise<Record<CaipAssetType, { [currency: string]: string }>> => {\n const { currency, assetIds, clientId, fetchFn } = request;\n const validAssetIds = Array.from(assetIds).filter(Boolean);\n if (validAssetIds.length === 0) {\n return {};\n }\n\n const queryParams = new URLSearchParams({\n assetIds: validAssetIds.filter(Boolean).join(','),\n vsCurrency: currency,\n });\n const url = `https://price.api.cx.metamask.io/v3/spot-prices?${queryParams}`;\n const priceApiResponse = (await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: Number(Duration.Second * 30) },\n functionName: 'fetchAssetExchangeRates',\n })) as Record<CaipAssetType, { [currency: string]: number }>;\n\n if (!priceApiResponse || typeof priceApiResponse !== 'object') {\n return {};\n }\n\n return Object.entries(priceApiResponse).reduce(\n (acc, [assetId, currencyToPrice]) => {\n if (!currencyToPrice) {\n return acc;\n }\n if (!acc[assetId as CaipAssetType]) {\n acc[assetId as CaipAssetType] = {};\n }\n if (currencyToPrice[currency]) {\n acc[assetId as CaipAssetType][currency] =\n currencyToPrice[currency].toString();\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n};\n\n/**\n * Fetches the asset prices from the price API for multiple currencies\n *\n * @param request - The request object\n * @returns The asset prices by assetId\n */\nexport const fetchAssetPrices = async (\n request: {\n currencies: Set<string>;\n } & Omit<Parameters<typeof fetchAssetPricesForCurrency>[0], 'currency'>,\n): Promise<\n Record<CaipAssetType, { [currency: string]: string } | undefined>\n> => {\n const { currencies, ...args } = request;\n\n const combinedPrices = await Promise.allSettled(\n Array.from(currencies).map(\n async (currency) =>\n await fetchAssetPricesForCurrency({ ...args, currency }),\n ),\n ).then((priceApiResponse) => {\n return priceApiResponse.reduce(\n (acc, result) => {\n if (result.status === 'fulfilled') {\n Object.entries(result.value).forEach(([assetId, currencyToPrice]) => {\n const existingPrices = acc[assetId as CaipAssetType];\n if (!existingPrices) {\n acc[assetId as CaipAssetType] = {};\n }\n Object.entries(currencyToPrice).forEach(([currency, price]) => {\n acc[assetId as CaipAssetType][currency] = price;\n });\n });\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n });\n\n return combinedPrices;\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.d.cts","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,EAAE,wBAAwB;
|
|
1
|
+
{"version":3,"file":"fetch.d.cts","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,EAAE,wBAAwB;AAavE,OAAO,KAAK,EACV,aAAa,EACb,aAAa,EACb,mBAAmB,EAEnB,WAAW,EACZ,qBAAiB;AAIlB,eAAO,MAAM,iBAAiB,aAAc,MAAM;;CAEhD,CAAC;AAEH;;;;;;;;GAQG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,GAAG,GAAG,WAAW,EAC1B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,aAAa,EACtB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAoBtC;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,mBAAmB,EAC5B,MAAM,EAAE,WAAW,GAAG,IAAI,EAC1B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,aAAa,EACtB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC;IACT,MAAM,EAAE,aAAa,EAAE,CAAC;IACxB,kBAAkB,EAAE,MAAM,EAAE,CAAC;CAC9B,CAAC,CA8ED;AAED,QAAA,MAAM,2BAA2B,YAAmB;IAClD,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,IAAI,aAAa,CAAC,CAAC;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,aAAa,CAAC;CACxB;;GAsCA,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,YAClB;IACP,UAAU,EAAE,IAAI,MAAM,CAAC,CAAC;CACzB,GAAG,KAAK,WAAW,kCAAkC,CAAC,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC;;eAgCxE,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.d.mts","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,EAAE,wBAAwB;
|
|
1
|
+
{"version":3,"file":"fetch.d.mts","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,EAAE,wBAAwB;AAavE,OAAO,KAAK,EACV,aAAa,EACb,aAAa,EACb,mBAAmB,EAEnB,WAAW,EACZ,qBAAiB;AAIlB,eAAO,MAAM,iBAAiB,aAAc,MAAM;;CAEhD,CAAC;AAEH;;;;;;;;GAQG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,GAAG,GAAG,WAAW,EAC1B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,aAAa,EACtB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAoBtC;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,mBAAmB,EAC5B,MAAM,EAAE,WAAW,GAAG,IAAI,EAC1B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,aAAa,EACtB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC;IACT,MAAM,EAAE,aAAa,EAAE,CAAC;IACxB,kBAAkB,EAAE,MAAM,EAAE,CAAC;CAC9B,CAAC,CA8ED;AAED,QAAA,MAAM,2BAA2B,YAAmB;IAClD,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,IAAI,aAAa,CAAC,CAAC;IAC7B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,aAAa,CAAC;CACxB;;GAsCA,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,YAClB;IACP,UAAU,EAAE,IAAI,MAAM,CAAC,CAAC;CACzB,GAAG,KAAK,WAAW,kCAAkC,CAAC,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC;;eAgCxE,CAAC"}
|
package/dist/utils/fetch.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { StructError } from "@metamask/superstruct";
|
|
2
2
|
import { Duration } from "@metamask/utils";
|
|
3
|
+
import { isBitcoinChainId } from "./bridge.mjs";
|
|
3
4
|
import { formatAddressToCaipReference, formatChainIdToDec } from "./caip-formatters.mjs";
|
|
4
|
-
import { validateQuoteResponse, validateSwapsTokenObject } from "./validators.mjs";
|
|
5
|
+
import { validateQuoteResponse, validateBitcoinQuoteResponse, validateSwapsTokenObject } from "./validators.mjs";
|
|
5
6
|
const CACHE_REFRESH_TEN_MINUTES = 10 * Duration.Minute;
|
|
6
7
|
export const getClientIdHeader = (clientId) => ({
|
|
7
8
|
'X-Client-Id': clientId,
|
|
@@ -87,6 +88,10 @@ export async function fetchBridgeQuotes(request, signal, clientId, fetchFn, brid
|
|
|
87
88
|
const uniqueValidationFailures = new Set([]);
|
|
88
89
|
const filteredQuotes = quotes.filter((quoteResponse) => {
|
|
89
90
|
try {
|
|
91
|
+
const isBitcoinQuote = isBitcoinChainId(request.srcChainId);
|
|
92
|
+
if (isBitcoinQuote) {
|
|
93
|
+
return validateBitcoinQuoteResponse(quoteResponse);
|
|
94
|
+
}
|
|
90
95
|
return validateQuoteResponse(quoteResponse);
|
|
91
96
|
}
|
|
92
97
|
catch (error) {
|
package/dist/utils/fetch.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.mjs","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,8BAA8B;AAEpD,OAAO,EAAE,QAAQ,EAAE,wBAAwB;AAE3C,OAAO,EACL,4BAA4B,EAC5B,kBAAkB,EACnB,8BAA0B;AAC3B,OAAO,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,yBAAqB;AAS/E,MAAM,yBAAyB,GAAG,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC;AAEvD,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,QAAgB,EAAE,EAAE,CAAC,CAAC;IACtD,aAAa,EAAE,QAAQ;CACxB,CAAC,CAAC;AAEH;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,OAA0B,EAC1B,QAAgB,EAChB,OAAsB,EACtB,gBAAwB;IAExB,8BAA8B;IAC9B,MAAM,GAAG,GAAG,GAAG,gBAAgB,sBAAsB,kBAAkB,CAAC,OAAO,CAAC,EAAE,CAAC;IAEnF,uGAAuG;IACvG,uEAAuE;IACvE,6IAA6I;IAC7I,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,GAAG,EAAE;QAChC,OAAO,EAAE,iBAAiB,CAAC,QAAQ,CAAC;QACpC,YAAY,EAAE,EAAE,gBAAgB,EAAE,yBAAyB,EAAE;QAC7D,YAAY,EAAE,mBAAmB;KAClC,CAAC,CAAC;IAEH,MAAM,iBAAiB,GAAgC,EAAE,CAAC;IAC1D,MAAM,CAAC,OAAO,CAAC,CAAC,KAAc,EAAE,EAAE;QAChC,IAAI,wBAAwB,CAAC,KAAK,CAAC,EAAE;YACnC,iBAAiB,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,KAAK,CAAC;SAC1C;IACH,C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AC3D,CACF,CAAC,IAAI,CAAC,CAAC,gBAAgB,EAAE,EAAE;QAC1B,OAAO,gBAAgB,CAAC,MAAM,CAC5B,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE;YACd,IAAI,MAAM,CAAC,MAAM,KAAK,WAAW,EAAE;gBACjC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,EAAE,eAAe,CAAC,EAAE,EAAE;oBAClE,MAAM,cAAc,GAAG,GAAG,CAAC,OAAwB,CAAC,CAAC;oBACrD,IAAI,CAAC,cAAc,EAAE;wBACnB,GAAG,CAAC,OAAwB,CAAC,GAAG,EAAE,CAAC;qBACpC;oBACD,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,EAAE;wBAC5D,GAAG,CAAC,OAAwB,CAAC,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;oBAClD,CAAC,CAAC,CAAC;gBACL,CAAC,CAAC,CAAC;aACJ;YACD,OAAO,GAAG,CAAC;QACb,CAAC,EACD,EAA2D,CAC5D,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC","sourcesContent":["import { StructError } from '@metamask/superstruct';\nimport type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';\nimport { Duration } from '@metamask/utils';\n\nimport {\n formatAddressToCaipReference,\n formatChainIdToDec,\n} from './caip-formatters';\nimport { validateQuoteResponse, validateSwapsTokenObject } from './validators';\nimport type {\n QuoteResponse,\n FetchFunction,\n GenericQuoteRequest,\n QuoteRequest,\n BridgeAsset,\n} from '../types';\n\nconst CACHE_REFRESH_TEN_MINUTES = 10 * Duration.Minute;\n\nexport const getClientIdHeader = (clientId: string) => ({\n 'X-Client-Id': clientId,\n});\n\n/**\n * Returns a list of enabled (unblocked) tokens\n *\n * @param chainId - The chain ID to fetch tokens for\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of enabled (unblocked) tokens\n */\nexport async function fetchBridgeTokens(\n chainId: Hex | CaipChainId,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<Record<string, BridgeAsset>> {\n // TODO make token api v2 call\n const url = `${bridgeApiBaseUrl}/getTokens?chainId=${formatChainIdToDec(chainId)}`;\n\n // TODO we will need to cache these. In Extension fetchWithCache is used. This is due to the following:\n // If we allow selecting dest networks which the user has not imported,\n // note that the Assets controller won't be able to provide tokens. In extension we fetch+cache the token list from bridge-api to handle this\n const tokens = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: CACHE_REFRESH_TEN_MINUTES },\n functionName: 'fetchBridgeTokens',\n });\n\n const transformedTokens: Record<string, BridgeAsset> = {};\n tokens.forEach((token: unknown) => {\n if (validateSwapsTokenObject(token)) {\n transformedTokens[token.address] = token;\n }\n });\n return transformedTokens;\n}\n\n/**\n * Converts the generic quote request to the type that the bridge-api expects\n * then fetches quotes from the bridge-api\n *\n * @param request - The quote request\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of bridge tx quotes\n */\nexport async function fetchBridgeQuotes(\n request: GenericQuoteRequest,\n signal: AbortSignal | null,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<{\n quotes: QuoteResponse[];\n validationFailures: string[];\n}> {\n const destWalletAddress = request.destWalletAddress ?? request.walletAddress;\n // Transform the generic quote request into QuoteRequest\n const normalizedRequest: QuoteRequest = {\n walletAddress: formatAddressToCaipReference(request.walletAddress),\n destWalletAddress: formatAddressToCaipReference(destWalletAddress),\n srcChainId: formatChainIdToDec(request.srcChainId),\n destChainId: formatChainIdToDec(request.destChainId),\n srcTokenAddress: formatAddressToCaipReference(request.srcTokenAddress),\n destTokenAddress: formatAddressToCaipReference(request.destTokenAddress),\n srcTokenAmount: request.srcTokenAmount,\n insufficientBal: Boolean(request.insufficientBal),\n resetApproval: Boolean(request.resetApproval),\n gasIncluded: Boolean(request.gasIncluded),\n gasIncluded7702: Boolean(request.gasIncluded7702),\n };\n if (request.slippage !== undefined) {\n normalizedRequest.slippage = request.slippage;\n }\n if (request.noFee !== undefined) {\n normalizedRequest.noFee = request.noFee;\n }\n if (request.aggIds && request.aggIds.length > 0) {\n normalizedRequest.aggIds = request.aggIds;\n }\n if (request.bridgeIds && request.bridgeIds.length > 0) {\n normalizedRequest.bridgeIds = request.bridgeIds;\n }\n\n const queryParams = new URLSearchParams();\n Object.entries(normalizedRequest).forEach(([key, value]) => {\n queryParams.append(key, value.toString());\n });\n const url = `${bridgeApiBaseUrl}/getQuote?${queryParams}`;\n const quotes: unknown[] = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n signal,\n cacheOptions: { cacheRefreshTime: 0 },\n functionName: 'fetchBridgeQuotes',\n });\n\n const uniqueValidationFailures: Set<string> = new Set<string>([]);\n const filteredQuotes = quotes.filter(\n (quoteResponse: unknown): quoteResponse is QuoteResponse => {\n try {\n return validateQuoteResponse(quoteResponse);\n } catch (error) {\n if (error instanceof StructError) {\n error.failures().forEach(({ branch, path }) => {\n const aggregatorId =\n branch?.[0]?.quote?.bridgeId ||\n branch?.[0]?.quote?.bridges?.[0] ||\n (quoteResponse as QuoteResponse)?.quote?.bridgeId ||\n (quoteResponse as QuoteResponse)?.quote?.bridges?.[0] ||\n 'unknown';\n const pathString = path?.join('.') || 'unknown';\n uniqueValidationFailures.add([aggregatorId, pathString].join('|'));\n });\n }\n return false;\n }\n },\n );\n\n const validationFailures = Array.from(uniqueValidationFailures);\n if (uniqueValidationFailures.size > 0) {\n console.warn('Quote validation failed', validationFailures);\n }\n\n return {\n quotes: filteredQuotes,\n validationFailures,\n };\n}\n\nconst fetchAssetPricesForCurrency = async (request: {\n currency: string;\n assetIds: Set<CaipAssetType>;\n clientId: string;\n fetchFn: FetchFunction;\n}): Promise<Record<CaipAssetType, { [currency: string]: string }>> => {\n const { currency, assetIds, clientId, fetchFn } = request;\n const validAssetIds = Array.from(assetIds).filter(Boolean);\n if (validAssetIds.length === 0) {\n return {};\n }\n\n const queryParams = new URLSearchParams({\n assetIds: validAssetIds.filter(Boolean).join(','),\n vsCurrency: currency,\n });\n const url = `https://price.api.cx.metamask.io/v3/spot-prices?${queryParams}`;\n const priceApiResponse = (await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: Number(Duration.Second * 30) },\n functionName: 'fetchAssetExchangeRates',\n })) as Record<CaipAssetType, { [currency: string]: number }>;\n\n if (!priceApiResponse || typeof priceApiResponse !== 'object') {\n return {};\n }\n\n return Object.entries(priceApiResponse).reduce(\n (acc, [assetId, currencyToPrice]) => {\n if (!currencyToPrice) {\n return acc;\n }\n if (!acc[assetId as CaipAssetType]) {\n acc[assetId as CaipAssetType] = {};\n }\n if (currencyToPrice[currency]) {\n acc[assetId as CaipAssetType][currency] =\n currencyToPrice[currency].toString();\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n};\n\n/**\n * Fetches the asset prices from the price API for multiple currencies\n *\n * @param request - The request object\n * @returns The asset prices by assetId\n */\nexport const fetchAssetPrices = async (\n request: {\n currencies: Set<string>;\n } & Omit<Parameters<typeof fetchAssetPricesForCurrency>[0], 'currency'>,\n): Promise<\n Record<CaipAssetType, { [currency: string]: string } | undefined>\n> => {\n const { currencies, ...args } = request;\n\n const combinedPrices = await Promise.allSettled(\n Array.from(currencies).map(\n async (currency) =>\n await fetchAssetPricesForCurrency({ ...args, currency }),\n ),\n ).then((priceApiResponse) => {\n return priceApiResponse.reduce(\n (acc, result) => {\n if (result.status === 'fulfilled') {\n Object.entries(result.value).forEach(([assetId, currencyToPrice]) => {\n const existingPrices = acc[assetId as CaipAssetType];\n if (!existingPrices) {\n acc[assetId as CaipAssetType] = {};\n }\n Object.entries(currencyToPrice).forEach(([currency, price]) => {\n acc[assetId as CaipAssetType][currency] = price;\n });\n });\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n });\n\n return combinedPrices;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"fetch.mjs","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,8BAA8B;AAEpD,OAAO,EAAE,QAAQ,EAAE,wBAAwB;AAE3C,OAAO,EAAE,gBAAgB,EAAE,qBAAiB;AAC5C,OAAO,EACL,4BAA4B,EAC5B,kBAAkB,EACnB,8BAA0B;AAC3B,OAAO,EACL,qBAAqB,EACrB,4BAA4B,EAC5B,wBAAwB,EACzB,yBAAqB;AAStB,MAAM,yBAAyB,GAAG,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC;AAEvD,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,QAAgB,EAAE,EAAE,CAAC,CAAC;IACtD,aAAa,EAAE,QAAQ;CACxB,CAAC,CAAC;AAEH;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,OAA0B,EAC1B,QAAgB,EAChB,OAAsB,EACtB,gBAAwB;IAExB,8BAA8B;IAC9B,MAAM,GAAG,GAAG,GAAG,gBAAgB,sBAAsB,kBAAkB,CAAC,OAAO,CAAC,EAAE,CAAC;IAEnF,uGAAuG;IACvG,uEAAuE;IACvE,6IAA6I;IAC7I,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,GAAG,EAAE;QAChC,OAAO,EAAE,iBAAiB,CAAC,QAAQ,CAAC;QACpC,YAAY,EAAE,EAAE,gBAAgB,EAAE,yBAAyB,EAAE;QAC7D,YAAY,EAAE,mBAAmB;KAClC,CAAC,CAAC;IAEH,MAAM,iBAAiB,GAAgC,EAAE,CAAC;IAC1D,MAAM,CAAC,OAAO,CAA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,EAGvE,EAAE;IACF,MAAM,EAAE,UAAU,EAAE,GAAG,IAAI,EAAE,GAAG,OAAO,CAAC;IAExC,MAAM,cAAc,GAAG,MAAM,OAAO,CAAC,UAAU,CAC7C,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,GAAG,CACxB,KAAK,EAAE,QAAQ,EAAE,EAAE,CACjB,MAAM,2BAA2B,CAAC,EAAE,GAAG,IAAI,EAAE,QAAQ,EAAE,CAAC,CAC3D,CACF,CAAC,IAAI,CAAC,CAAC,gBAAgB,EAAE,EAAE;QAC1B,OAAO,gBAAgB,CAAC,MAAM,CAC5B,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE;YACd,IAAI,MAAM,CAAC,MAAM,KAAK,WAAW,EAAE;gBACjC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,EAAE,eAAe,CAAC,EAAE,EAAE;oBAClE,MAAM,cAAc,GAAG,GAAG,CAAC,OAAwB,CAAC,CAAC;oBACrD,IAAI,CAAC,cAAc,EAAE;wBACnB,GAAG,CAAC,OAAwB,CAAC,GAAG,EAAE,CAAC;qBACpC;oBACD,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,EAAE;wBAC5D,GAAG,CAAC,OAAwB,CAAC,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;oBAClD,CAAC,CAAC,CAAC;gBACL,CAAC,CAAC,CAAC;aACJ;YACD,OAAO,GAAG,CAAC;QACb,CAAC,EACD,EAA2D,CAC5D,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC","sourcesContent":["import { StructError } from '@metamask/superstruct';\nimport type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';\nimport { Duration } from '@metamask/utils';\n\nimport { isBitcoinChainId } from './bridge';\nimport {\n formatAddressToCaipReference,\n formatChainIdToDec,\n} from './caip-formatters';\nimport {\n validateQuoteResponse,\n validateBitcoinQuoteResponse,\n validateSwapsTokenObject,\n} from './validators';\nimport type {\n QuoteResponse,\n FetchFunction,\n GenericQuoteRequest,\n QuoteRequest,\n BridgeAsset,\n} from '../types';\n\nconst CACHE_REFRESH_TEN_MINUTES = 10 * Duration.Minute;\n\nexport const getClientIdHeader = (clientId: string) => ({\n 'X-Client-Id': clientId,\n});\n\n/**\n * Returns a list of enabled (unblocked) tokens\n *\n * @param chainId - The chain ID to fetch tokens for\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of enabled (unblocked) tokens\n */\nexport async function fetchBridgeTokens(\n chainId: Hex | CaipChainId,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<Record<string, BridgeAsset>> {\n // TODO make token api v2 call\n const url = `${bridgeApiBaseUrl}/getTokens?chainId=${formatChainIdToDec(chainId)}`;\n\n // TODO we will need to cache these. In Extension fetchWithCache is used. This is due to the following:\n // If we allow selecting dest networks which the user has not imported,\n // note that the Assets controller won't be able to provide tokens. In extension we fetch+cache the token list from bridge-api to handle this\n const tokens = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: CACHE_REFRESH_TEN_MINUTES },\n functionName: 'fetchBridgeTokens',\n });\n\n const transformedTokens: Record<string, BridgeAsset> = {};\n tokens.forEach((token: unknown) => {\n if (validateSwapsTokenObject(token)) {\n transformedTokens[token.address] = token;\n }\n });\n return transformedTokens;\n}\n\n/**\n * Converts the generic quote request to the type that the bridge-api expects\n * then fetches quotes from the bridge-api\n *\n * @param request - The quote request\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of bridge tx quotes\n */\nexport async function fetchBridgeQuotes(\n request: GenericQuoteRequest,\n signal: AbortSignal | null,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<{\n quotes: QuoteResponse[];\n validationFailures: string[];\n}> {\n const destWalletAddress = request.destWalletAddress ?? request.walletAddress;\n // Transform the generic quote request into QuoteRequest\n const normalizedRequest: QuoteRequest = {\n walletAddress: formatAddressToCaipReference(request.walletAddress),\n destWalletAddress: formatAddressToCaipReference(destWalletAddress),\n srcChainId: formatChainIdToDec(request.srcChainId),\n destChainId: formatChainIdToDec(request.destChainId),\n srcTokenAddress: formatAddressToCaipReference(request.srcTokenAddress),\n destTokenAddress: formatAddressToCaipReference(request.destTokenAddress),\n srcTokenAmount: request.srcTokenAmount,\n insufficientBal: Boolean(request.insufficientBal),\n resetApproval: Boolean(request.resetApproval),\n gasIncluded: Boolean(request.gasIncluded),\n gasIncluded7702: Boolean(request.gasIncluded7702),\n };\n if (request.slippage !== undefined) {\n normalizedRequest.slippage = request.slippage;\n }\n if (request.noFee !== undefined) {\n normalizedRequest.noFee = request.noFee;\n }\n if (request.aggIds && request.aggIds.length > 0) {\n normalizedRequest.aggIds = request.aggIds;\n }\n if (request.bridgeIds && request.bridgeIds.length > 0) {\n normalizedRequest.bridgeIds = request.bridgeIds;\n }\n\n const queryParams = new URLSearchParams();\n Object.entries(normalizedRequest).forEach(([key, value]) => {\n queryParams.append(key, value.toString());\n });\n const url = `${bridgeApiBaseUrl}/getQuote?${queryParams}`;\n const quotes: unknown[] = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n signal,\n cacheOptions: { cacheRefreshTime: 0 },\n functionName: 'fetchBridgeQuotes',\n });\n\n const uniqueValidationFailures: Set<string> = new Set<string>([]);\n const filteredQuotes = quotes.filter(\n (quoteResponse: unknown): quoteResponse is QuoteResponse => {\n try {\n const isBitcoinQuote = isBitcoinChainId(request.srcChainId);\n\n if (isBitcoinQuote) {\n return validateBitcoinQuoteResponse(quoteResponse);\n }\n return validateQuoteResponse(quoteResponse);\n } catch (error) {\n if (error instanceof StructError) {\n error.failures().forEach(({ branch, path }) => {\n const aggregatorId =\n branch?.[0]?.quote?.bridgeId ||\n branch?.[0]?.quote?.bridges?.[0] ||\n (quoteResponse as QuoteResponse)?.quote?.bridgeId ||\n (quoteResponse as QuoteResponse)?.quote?.bridges?.[0] ||\n 'unknown';\n const pathString = path?.join('.') || 'unknown';\n uniqueValidationFailures.add([aggregatorId, pathString].join('|'));\n });\n }\n return false;\n }\n },\n );\n\n const validationFailures = Array.from(uniqueValidationFailures);\n if (uniqueValidationFailures.size > 0) {\n console.warn('Quote validation failed', validationFailures);\n }\n\n return {\n quotes: filteredQuotes,\n validationFailures,\n };\n}\n\nconst fetchAssetPricesForCurrency = async (request: {\n currency: string;\n assetIds: Set<CaipAssetType>;\n clientId: string;\n fetchFn: FetchFunction;\n}): Promise<Record<CaipAssetType, { [currency: string]: string }>> => {\n const { currency, assetIds, clientId, fetchFn } = request;\n const validAssetIds = Array.from(assetIds).filter(Boolean);\n if (validAssetIds.length === 0) {\n return {};\n }\n\n const queryParams = new URLSearchParams({\n assetIds: validAssetIds.filter(Boolean).join(','),\n vsCurrency: currency,\n });\n const url = `https://price.api.cx.metamask.io/v3/spot-prices?${queryParams}`;\n const priceApiResponse = (await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: Number(Duration.Second * 30) },\n functionName: 'fetchAssetExchangeRates',\n })) as Record<CaipAssetType, { [currency: string]: number }>;\n\n if (!priceApiResponse || typeof priceApiResponse !== 'object') {\n return {};\n }\n\n return Object.entries(priceApiResponse).reduce(\n (acc, [assetId, currencyToPrice]) => {\n if (!currencyToPrice) {\n return acc;\n }\n if (!acc[assetId as CaipAssetType]) {\n acc[assetId as CaipAssetType] = {};\n }\n if (currencyToPrice[currency]) {\n acc[assetId as CaipAssetType][currency] =\n currencyToPrice[currency].toString();\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n};\n\n/**\n * Fetches the asset prices from the price API for multiple currencies\n *\n * @param request - The request object\n * @returns The asset prices by assetId\n */\nexport const fetchAssetPrices = async (\n request: {\n currencies: Set<string>;\n } & Omit<Parameters<typeof fetchAssetPricesForCurrency>[0], 'currency'>,\n): Promise<\n Record<CaipAssetType, { [currency: string]: string } | undefined>\n> => {\n const { currencies, ...args } = request;\n\n const combinedPrices = await Promise.allSettled(\n Array.from(currencies).map(\n async (currency) =>\n await fetchAssetPricesForCurrency({ ...args, currency }),\n ),\n ).then((priceApiResponse) => {\n return priceApiResponse.reduce(\n (acc, result) => {\n if (result.status === 'fulfilled') {\n Object.entries(result.value).forEach(([assetId, currencyToPrice]) => {\n const existingPrices = acc[assetId as CaipAssetType];\n if (!existingPrices) {\n acc[assetId as CaipAssetType] = {};\n }\n Object.entries(currencyToPrice).forEach(([currency, price]) => {\n acc[assetId as CaipAssetType][currency] = price;\n });\n });\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n });\n\n return combinedPrices;\n};\n"]}
|
|
@@ -14,7 +14,6 @@ var UnifiedSwapBridgeEventName;
|
|
|
14
14
|
UnifiedSwapBridgeEventName["QuotesRequested"] = "Unified SwapBridge Quotes Requested";
|
|
15
15
|
UnifiedSwapBridgeEventName["QuotesReceived"] = "Unified SwapBridge Quotes Received";
|
|
16
16
|
UnifiedSwapBridgeEventName["QuotesError"] = "Unified SwapBridge Quotes Error";
|
|
17
|
-
UnifiedSwapBridgeEventName["SnapConfirmationViewed"] = "Unified SwapBridge Snap Confirmation Page Viewed";
|
|
18
17
|
UnifiedSwapBridgeEventName["Submitted"] = "Unified SwapBridge Submitted";
|
|
19
18
|
UnifiedSwapBridgeEventName["Completed"] = "Unified SwapBridge Completed";
|
|
20
19
|
UnifiedSwapBridgeEventName["Failed"] = "Unified SwapBridge Failed";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.cjs","sourceRoot":"","sources":["../../../src/utils/metrics/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,kCAAkC,GAAG,oBAAoB,CAAC;AAEvE;;GAEG;AACH,IAAY,
|
|
1
|
+
{"version":3,"file":"constants.cjs","sourceRoot":"","sources":["../../../src/utils/metrics/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,kCAAkC,GAAG,oBAAoB,CAAC;AAEvE;;GAEG;AACH,IAAY,0BAiBX;AAjBD,WAAY,0BAA0B;IACpC,iFAAsE,CAAA;IACtE,2EAAgE,CAAA;IAChE,+EAAoE,CAAA;IACpE,+GAAoG,CAAA;IACpG,qFAA0E,CAAA;IAC1E,mFAAwE,CAAA;IACxE,6EAAkE,CAAA;IAClE,wEAA6D,CAAA;IAC7D,wEAA6D,CAAA;IAC7D,kEAAuD,CAAA;IACvD,sFAA2E,CAAA;IAC3E,sFAA2E,CAAA;IAC3E,iFAAsE,CAAA;IACtE,2GAAgG,CAAA;IAChG,oGAAyF,CAAA;IACzF,oGAAyF,CAAA;AAC3F,CAAC,EAjBW,0BAA0B,0CAA1B,0BAA0B,QAiBrC;AAED,IAAY,WAIX;AAJD,WAAY,WAAW;IACrB,oDAAqC,CAAA;IACrC,4DAA6C,CAAA;IAC7C,oDAAqC,CAAA;AACvC,CAAC,EAJW,WAAW,2BAAX,WAAW,QAItB;AAED;;GAEG;AACH,IAAY,2BAGX;AAHD,WAAY,2BAA2B;IACrC,qDAAsB,CAAA;IACtB,uDAAwB,CAAA;AAC1B,CAAC,EAHW,2BAA2B,2CAA3B,2BAA2B,QAGtC;AAED,IAAY,iBAMX;AAND,WAAY,iBAAiB;IAC3B;;OAEG;IACH,oDAA+B,CAAA;IAC/B,oDAA+B,CAAA;AACjC,CAAC,EANW,iBAAiB,iCAAjB,iBAAiB,QAM5B;AAED,IAAY,eAGX;AAHD,WAAY,eAAe;IACzB,0CAAuB,CAAA;IACvB,4CAAyB,CAAA;AAC3B,CAAC,EAHW,eAAe,+BAAf,eAAe,QAG1B","sourcesContent":["export const UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY = 'Unified SwapBridge';\n\n/**\n * These event names map to events defined in the segment-schema: https://github.com/Consensys/segment-schema/tree/main/libraries/events/metamask-cross-chain-swaps\n */\nexport enum UnifiedSwapBridgeEventName {\n ButtonClicked = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Button Clicked`,\n PageViewed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Page Viewed`,\n InputChanged = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Input Changed`,\n InputSourceDestinationSwitched = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Source Destination Switched`,\n QuotesRequested = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quotes Requested`,\n QuotesReceived = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quotes Received`,\n QuotesError = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quotes Error`,\n Submitted = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Submitted`,\n Completed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Completed`,\n Failed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Failed`,\n AllQuotesOpened = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} All Quotes Opened`,\n AllQuotesSorted = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} All Quotes Sorted`,\n QuoteSelected = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quote Selected`,\n AssetDetailTooltipClicked = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Asset Detail Tooltip Clicked`,\n QuotesValidationFailed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quotes Failed Validation`,\n StatusValidationFailed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Status Failed Validation`,\n}\n\nexport enum AbortReason {\n NewQuoteRequest = 'New Quote Request',\n QuoteRequestUpdated = 'Quote Request Updated',\n ResetState = 'Reset controller state',\n}\n\n/**\n * @deprecated remove this event property\n */\nexport enum MetaMetricsSwapsEventSource {\n MainView = 'Main View',\n TokenView = 'Token View',\n}\n\nexport enum MetricsActionType {\n /**\n * @deprecated new events should use SWAPBRIDGE_V1 instead\n */\n CROSSCHAIN_V1 = 'crosschain-v1',\n SWAPBRIDGE_V1 = 'swapbridge-v1',\n}\n\nexport enum MetricsSwapType {\n SINGLE = 'single_chain',\n CROSSCHAIN = 'crosschain',\n}\n"]}
|
|
@@ -10,7 +10,6 @@ export declare enum UnifiedSwapBridgeEventName {
|
|
|
10
10
|
QuotesRequested = "Unified SwapBridge Quotes Requested",
|
|
11
11
|
QuotesReceived = "Unified SwapBridge Quotes Received",
|
|
12
12
|
QuotesError = "Unified SwapBridge Quotes Error",
|
|
13
|
-
SnapConfirmationViewed = "Unified SwapBridge Snap Confirmation Page Viewed",
|
|
14
13
|
Submitted = "Unified SwapBridge Submitted",
|
|
15
14
|
Completed = "Unified SwapBridge Completed",
|
|
16
15
|
Failed = "Unified SwapBridge Failed",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../../../src/utils/metrics/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,kCAAkC,uBAAuB,CAAC;AAEvE;;GAEG;AACH,oBAAY,0BAA0B;IACpC,aAAa,sCAAyD;IACtE,UAAU,mCAAsD;IAChE,YAAY,qCAAwD;IACpE,8BAA8B,mDAAsE;IACpG,eAAe,wCAA2D;IAC1E,cAAc,uCAA0D;IACxE,WAAW,oCAAuD;IAClE,
|
|
1
|
+
{"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../../../src/utils/metrics/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,kCAAkC,uBAAuB,CAAC;AAEvE;;GAEG;AACH,oBAAY,0BAA0B;IACpC,aAAa,sCAAyD;IACtE,UAAU,mCAAsD;IAChE,YAAY,qCAAwD;IACpE,8BAA8B,mDAAsE;IACpG,eAAe,wCAA2D;IAC1E,cAAc,uCAA0D;IACxE,WAAW,oCAAuD;IAClE,SAAS,iCAAoD;IAC7D,SAAS,iCAAoD;IAC7D,MAAM,8BAAiD;IACvD,eAAe,yCAA4D;IAC3E,eAAe,yCAA4D;IAC3E,aAAa,sCAAyD;IACtE,yBAAyB,oDAAuE;IAChG,sBAAsB,gDAAmE;IACzF,sBAAsB,gDAAmE;CAC1F;AAED,oBAAY,WAAW;IACrB,eAAe,sBAAsB;IACrC,mBAAmB,0BAA0B;IAC7C,UAAU,2BAA2B;CACtC;AAED;;GAEG;AACH,oBAAY,2BAA2B;IACrC,QAAQ,cAAc;IACtB,SAAS,eAAe;CACzB;AAED,oBAAY,iBAAiB;IAC3B;;OAEG;IACH,aAAa,kBAAkB;IAC/B,aAAa,kBAAkB;CAChC;AAED,oBAAY,eAAe;IACzB,MAAM,iBAAiB;IACvB,UAAU,eAAe;CAC1B"}
|
|
@@ -10,7 +10,6 @@ export declare enum UnifiedSwapBridgeEventName {
|
|
|
10
10
|
QuotesRequested = "Unified SwapBridge Quotes Requested",
|
|
11
11
|
QuotesReceived = "Unified SwapBridge Quotes Received",
|
|
12
12
|
QuotesError = "Unified SwapBridge Quotes Error",
|
|
13
|
-
SnapConfirmationViewed = "Unified SwapBridge Snap Confirmation Page Viewed",
|
|
14
13
|
Submitted = "Unified SwapBridge Submitted",
|
|
15
14
|
Completed = "Unified SwapBridge Completed",
|
|
16
15
|
Failed = "Unified SwapBridge Failed",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.d.mts","sourceRoot":"","sources":["../../../src/utils/metrics/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,kCAAkC,uBAAuB,CAAC;AAEvE;;GAEG;AACH,oBAAY,0BAA0B;IACpC,aAAa,sCAAyD;IACtE,UAAU,mCAAsD;IAChE,YAAY,qCAAwD;IACpE,8BAA8B,mDAAsE;IACpG,eAAe,wCAA2D;IAC1E,cAAc,uCAA0D;IACxE,WAAW,oCAAuD;IAClE,
|
|
1
|
+
{"version":3,"file":"constants.d.mts","sourceRoot":"","sources":["../../../src/utils/metrics/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,kCAAkC,uBAAuB,CAAC;AAEvE;;GAEG;AACH,oBAAY,0BAA0B;IACpC,aAAa,sCAAyD;IACtE,UAAU,mCAAsD;IAChE,YAAY,qCAAwD;IACpE,8BAA8B,mDAAsE;IACpG,eAAe,wCAA2D;IAC1E,cAAc,uCAA0D;IACxE,WAAW,oCAAuD;IAClE,SAAS,iCAAoD;IAC7D,SAAS,iCAAoD;IAC7D,MAAM,8BAAiD;IACvD,eAAe,yCAA4D;IAC3E,eAAe,yCAA4D;IAC3E,aAAa,sCAAyD;IACtE,yBAAyB,oDAAuE;IAChG,sBAAsB,gDAAmE;IACzF,sBAAsB,gDAAmE;CAC1F;AAED,oBAAY,WAAW;IACrB,eAAe,sBAAsB;IACrC,mBAAmB,0BAA0B;IAC7C,UAAU,2BAA2B;CACtC;AAED;;GAEG;AACH,oBAAY,2BAA2B;IACrC,QAAQ,cAAc;IACtB,SAAS,eAAe;CACzB;AAED,oBAAY,iBAAiB;IAC3B;;OAEG;IACH,aAAa,kBAAkB;IAC/B,aAAa,kBAAkB;CAChC;AAED,oBAAY,eAAe;IACzB,MAAM,iBAAiB;IACvB,UAAU,eAAe;CAC1B"}
|
|
@@ -11,7 +11,6 @@ export var UnifiedSwapBridgeEventName;
|
|
|
11
11
|
UnifiedSwapBridgeEventName["QuotesRequested"] = "Unified SwapBridge Quotes Requested";
|
|
12
12
|
UnifiedSwapBridgeEventName["QuotesReceived"] = "Unified SwapBridge Quotes Received";
|
|
13
13
|
UnifiedSwapBridgeEventName["QuotesError"] = "Unified SwapBridge Quotes Error";
|
|
14
|
-
UnifiedSwapBridgeEventName["SnapConfirmationViewed"] = "Unified SwapBridge Snap Confirmation Page Viewed";
|
|
15
14
|
UnifiedSwapBridgeEventName["Submitted"] = "Unified SwapBridge Submitted";
|
|
16
15
|
UnifiedSwapBridgeEventName["Completed"] = "Unified SwapBridge Completed";
|
|
17
16
|
UnifiedSwapBridgeEventName["Failed"] = "Unified SwapBridge Failed";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.mjs","sourceRoot":"","sources":["../../../src/utils/metrics/constants.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,kCAAkC,GAAG,oBAAoB,CAAC;AAEvE;;GAEG;AACH,MAAM,CAAN,IAAY,
|
|
1
|
+
{"version":3,"file":"constants.mjs","sourceRoot":"","sources":["../../../src/utils/metrics/constants.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,kCAAkC,GAAG,oBAAoB,CAAC;AAEvE;;GAEG;AACH,MAAM,CAAN,IAAY,0BAiBX;AAjBD,WAAY,0BAA0B;IACpC,iFAAsE,CAAA;IACtE,2EAAgE,CAAA;IAChE,+EAAoE,CAAA;IACpE,+GAAoG,CAAA;IACpG,qFAA0E,CAAA;IAC1E,mFAAwE,CAAA;IACxE,6EAAkE,CAAA;IAClE,wEAA6D,CAAA;IAC7D,wEAA6D,CAAA;IAC7D,kEAAuD,CAAA;IACvD,sFAA2E,CAAA;IAC3E,sFAA2E,CAAA;IAC3E,iFAAsE,CAAA;IACtE,2GAAgG,CAAA;IAChG,oGAAyF,CAAA;IACzF,oGAAyF,CAAA;AAC3F,CAAC,EAjBW,0BAA0B,KAA1B,0BAA0B,QAiBrC;AAED,MAAM,CAAN,IAAY,WAIX;AAJD,WAAY,WAAW;IACrB,oDAAqC,CAAA;IACrC,4DAA6C,CAAA;IAC7C,oDAAqC,CAAA;AACvC,CAAC,EAJW,WAAW,KAAX,WAAW,QAItB;AAED;;GAEG;AACH,MAAM,CAAN,IAAY,2BAGX;AAHD,WAAY,2BAA2B;IACrC,qDAAsB,CAAA;IACtB,uDAAwB,CAAA;AAC1B,CAAC,EAHW,2BAA2B,KAA3B,2BAA2B,QAGtC;AAED,MAAM,CAAN,IAAY,iBAMX;AAND,WAAY,iBAAiB;IAC3B;;OAEG;IACH,oDAA+B,CAAA;IAC/B,oDAA+B,CAAA;AACjC,CAAC,EANW,iBAAiB,KAAjB,iBAAiB,QAM5B;AAED,MAAM,CAAN,IAAY,eAGX;AAHD,WAAY,eAAe;IACzB,0CAAuB,CAAA;IACvB,4CAAyB,CAAA;AAC3B,CAAC,EAHW,eAAe,KAAf,eAAe,QAG1B","sourcesContent":["export const UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY = 'Unified SwapBridge';\n\n/**\n * These event names map to events defined in the segment-schema: https://github.com/Consensys/segment-schema/tree/main/libraries/events/metamask-cross-chain-swaps\n */\nexport enum UnifiedSwapBridgeEventName {\n ButtonClicked = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Button Clicked`,\n PageViewed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Page Viewed`,\n InputChanged = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Input Changed`,\n InputSourceDestinationSwitched = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Source Destination Switched`,\n QuotesRequested = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quotes Requested`,\n QuotesReceived = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quotes Received`,\n QuotesError = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quotes Error`,\n Submitted = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Submitted`,\n Completed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Completed`,\n Failed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Failed`,\n AllQuotesOpened = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} All Quotes Opened`,\n AllQuotesSorted = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} All Quotes Sorted`,\n QuoteSelected = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quote Selected`,\n AssetDetailTooltipClicked = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Asset Detail Tooltip Clicked`,\n QuotesValidationFailed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Quotes Failed Validation`,\n StatusValidationFailed = `${UNIFIED_SWAP_BRIDGE_EVENT_CATEGORY} Status Failed Validation`,\n}\n\nexport enum AbortReason {\n NewQuoteRequest = 'New Quote Request',\n QuoteRequestUpdated = 'Quote Request Updated',\n ResetState = 'Reset controller state',\n}\n\n/**\n * @deprecated remove this event property\n */\nexport enum MetaMetricsSwapsEventSource {\n MainView = 'Main View',\n TokenView = 'Token View',\n}\n\nexport enum MetricsActionType {\n /**\n * @deprecated new events should use SWAPBRIDGE_V1 instead\n */\n CROSSCHAIN_V1 = 'crosschain-v1',\n SWAPBRIDGE_V1 = 'swapbridge-v1',\n}\n\nexport enum MetricsSwapType {\n SINGLE = 'single_chain',\n CROSSCHAIN = 'crosschain',\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"properties.cjs","sourceRoot":"","sources":["../../../src/utils/metrics/properties.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"properties.cjs","sourceRoot":"","sources":["../../../src/utils/metrics/properties.ts"],"names":[],"mappings":";;;AAGA,+CAA8C;AAE9C,uDAAyE;AAGzE,0CAAmE;AACnE,4DAG4B;AAEf,QAAA,yBAAyB,GAElC;IACF,eAAe,EAAE,cAAc;IAC/B,gBAAgB,EAAE,mBAAmB;IACrC,UAAU,EAAE,cAAc;IAC1B,WAAW,EAAE,mBAAmB;IAChC,QAAQ,EAAE,UAAU;CACrB,CAAC;AAEW,QAAA,2BAA2B,GAOpC;IACF,eAAe,EAAE,CAAC,EAAE,eAAe,EAAE,UAAU,EAAE,EAAE,EAAE,CACnD,UAAU;QACR,CAAC,CAAC,IAAA,wCAAsB,EAAC,eAAe,IAAI,EAAE,EAAE,UAAU,CAAC;QAC3D,CAAC,CAAC,SAAS;IACf,gBAAgB,EAAE,CAAC,EAA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vB,MAAM,gBAAgB,GAAG,CAC9B,EACE,WAAW,EACX,eAAe,EACf,gBAAgB,GACsB,EACxC,cAA2B,EAC3B,EAAE;IACF,OAAO;QACL,eAAe,EAAE,cAAc;QAC/B,oBAAoB,EAAE,WAAW,CAAC,CAAC,CAAC,IAAA,qCAAmB,EAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI;QAC3E,oBAAoB,EAAE,eAAe;YACnC,CAAC,CAAC,CAAC,IAAA,wCAAsB,EAAC,eAAe,EAAE,cAAc,CAAC;gBACxD,IAAA,iCAAwB,EAAC,cAAc,CAAC,EAAE,OAAO;gBACjD,IAAI,CAAC;YACP,CAAC,CAAC,CAAC,IAAA,iCAAwB,EAAC,cAAc,CAAC,EAAE,OAAO,IAAI,IAAI,CAAC;QAC/D,yBAAyB,EAAE,gBAAgB;YACzC,CAAC,CAAC,CAAC,IAAA,wCAAsB,EACrB,gBAAgB,EAChB,WAAW,IAAI,cAAc,CAC9B,IAAI,IAAI,CAAC;YACZ,CAAC,CAAC,IAAI;KACT,CAAC;AACJ,CAAC,CAAC;AAvBW,QAAA,gBAAgB,oBAuB3B;AAEK,MAAM,gBAAgB,GAAG,CAC9B,eAAiF,EACjF,EAAE;IACF,OAAO,eAAe,EAAE,QAAQ,EAAE,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,UAAU,CAAC,IAAI,KAAK,CAAC;AAChF,CAAC,CAAC;AAJW,QAAA,gBAAgB,oBAI3B;AAEF;;;;;GAKG;AACI,MAAM,gBAAgB,GAAG,CAAC,QAAyC,EAAE,EAAE;IAC5E,OAAO,QAAQ,KAAK,wCAA+B,CAAC,YAAY,CAAC,QAAQ,CAAC;AAC5E,CAAC,CAAC;AAFW,QAAA,gBAAgB,oBAE3B","sourcesContent":["import type { AccountsControllerState } from '@metamask/accounts-controller';\nimport type { CaipChainId } from '@metamask/utils';\n\nimport { MetricsSwapType } from './constants';\nimport type { InputKeys, InputValues } from './types';\nimport { DEFAULT_BRIDGE_CONTROLLER_STATE } from '../../constants/bridge';\nimport type { BridgeControllerState, QuoteResponse, TxData } from '../../types';\nimport { type GenericQuoteRequest, type QuoteRequest } from '../../types';\nimport { getNativeAssetForChainId, isCrossChain } from '../bridge';\nimport {\n formatAddressToAssetId,\n formatChainIdToCaip,\n} from '../caip-formatters';\n\nexport const toInputChangedPropertyKey: Partial<\n Record<keyof QuoteRequest, InputKeys>\n> = {\n srcTokenAddress: 'token_source',\n destTokenAddress: 'token_destination',\n srcChainId: 'chain_source',\n destChainId: 'chain_destination',\n slippage: 'slippage',\n};\n\nexport const toInputChangedPropertyValue: Partial<\n Record<\n keyof typeof toInputChangedPropertyKey,\n (\n input_value: Partial<GenericQuoteRequest>,\n ) => InputValues[keyof InputValues] | undefined\n >\n> = {\n srcTokenAddress: ({ srcTokenAddress, srcChainId }) =>\n srcChainId\n ? formatAddressToAssetId(srcTokenAddress ?? '', srcChainId)\n : undefined,\n destTokenAddress: ({ destTokenAddress, destChainId }) =>\n destChainId\n ? formatAddressToAssetId(destTokenAddress ?? '', destChainId)\n : undefined,\n srcChainId: ({ srcChainId }) =>\n srcChainId ? formatChainIdToCaip(srcChainId) : undefined,\n destChainId: ({ destChainId }) =>\n destChainId ? formatChainIdToCaip(destChainId) : undefined,\n slippage: ({ slippage }) => (slippage ? Number(slippage) : slippage),\n};\n\nexport const getSwapType = (\n srcChainId?: GenericQuoteRequest['srcChainId'],\n destChainId?: GenericQuoteRequest['destChainId'],\n) => {\n if (srcChainId && !isCrossChain(srcChainId, destChainId ?? srcChainId)) {\n return MetricsSwapType.SINGLE;\n }\n return MetricsSwapType.CROSSCHAIN;\n};\n\nexport const getSwapTypeFromQuote = (\n quoteRequest: Partial<GenericQuoteRequest>,\n) => {\n return getSwapType(quoteRequest.srcChainId, quoteRequest.destChainId);\n};\n\nexport const formatProviderLabel = ({\n bridgeId,\n bridges,\n}: QuoteResponse<TxData | string>['quote']): `${string}_${string}` =>\n `${bridgeId}_${bridges[0]}`;\n\nexport const getRequestParams = (\n {\n destChainId,\n srcTokenAddress,\n destTokenAddress,\n }: BridgeControllerState['quoteRequest'],\n srcChainIdCaip: CaipChainId,\n) => {\n return {\n chain_id_source: srcChainIdCaip,\n chain_id_destination: destChainId ? formatChainIdToCaip(destChainId) : null,\n token_address_source: srcTokenAddress\n ? (formatAddressToAssetId(srcTokenAddress, srcChainIdCaip) ??\n getNativeAssetForChainId(srcChainIdCaip)?.assetId ??\n null)\n : (getNativeAssetForChainId(srcChainIdCaip)?.assetId ?? null),\n token_address_destination: destTokenAddress\n ? (formatAddressToAssetId(\n destTokenAddress,\n destChainId ?? srcChainIdCaip,\n ) ?? null)\n : null,\n };\n};\n\nexport const isHardwareWallet = (\n selectedAccount?: AccountsControllerState['internalAccounts']['accounts'][string],\n) => {\n return selectedAccount?.metadata?.keyring.type?.includes('Hardware') ?? false;\n};\n\n/**\n * @param slippage - The slippage percentage\n * @returns Whether the default slippage was overridden by the user\n *\n * @deprecated This function should not be used. Use {@link selectDefaultSlippagePercentage} instead.\n */\nexport const isCustomSlippage = (slippage: GenericQuoteRequest['slippage']) => {\n return slippage !== DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest.slippage;\n};\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import type { AccountsControllerState } from "@metamask/accounts-controller";
|
|
1
2
|
import type { CaipChainId } from "@metamask/utils";
|
|
2
3
|
import { MetricsSwapType } from "./constants.cjs";
|
|
3
4
|
import type { InputKeys, InputValues } from "./types.cjs";
|
|
4
|
-
import type { AccountsControllerState } from "../../../../accounts-controller/src/AccountsController.cjs";
|
|
5
5
|
import type { BridgeControllerState, QuoteResponse, TxData } from "../../types.cjs";
|
|
6
6
|
import { type GenericQuoteRequest, type QuoteRequest } from "../../types.cjs";
|
|
7
7
|
export declare const toInputChangedPropertyKey: Partial<Record<keyof QuoteRequest, InputKeys>>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"properties.d.cts","sourceRoot":"","sources":["../../../src/utils/metrics/properties.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,wBAAwB;AAEnD,OAAO,EAAE,eAAe,EAAE,wBAAoB;AAC9C,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,oBAAgB;
|
|
1
|
+
{"version":3,"file":"properties.d.cts","sourceRoot":"","sources":["../../../src/utils/metrics/properties.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,sCAAsC;AAC7E,OAAO,KAAK,EAAE,WAAW,EAAE,wBAAwB;AAEnD,OAAO,EAAE,eAAe,EAAE,wBAAoB;AAC9C,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,oBAAgB;AAEtD,OAAO,KAAK,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,EAAE,wBAAoB;AAChF,OAAO,EAAE,KAAK,mBAAmB,EAAE,KAAK,YAAY,EAAE,wBAAoB;AAO1E,eAAO,MAAM,yBAAyB,EAAE,OAAO,CAC7C,MAAM,CAAC,MAAM,YAAY,EAAE,SAAS,CAAC,CAOtC,CAAC;AAEF,eAAO,MAAM,2BAA2B,EAAE,OAAO,CAC/C,MAAM,CACJ,MAAM,OAAO,yBAAyB,EACtC,CACE,WAAW,EAAE,OAAO,CAAC,mBAAmB,CAAC,KACtC,WAAW,CAAC,MAAM,WAAW,CAAC,GAAG,SAAS,CAChD,CAeF,CAAC;AAEF,eAAO,MAAM,WAAW,gBACT,mBAAmB,CAAC,YAAY,CAAC,gBAChC,mBAAmB,CAAC,aAAa,CAAC,oBAMjD,CAAC;AAEF,eAAO,MAAM,oBAAoB,iBACjB,QAAQ,mBAAmB,CAAC,oBAG3C,CAAC;AAEF,eAAO,MAAM,mBAAmB,2BAG7B,cAAc,MAAM,GAAG,MAAM,CAAC,CAAC,OAAO,CAAC,KAAG,GAAG,MAAM,IAAI,MAAM,EACnC,CAAC;AAE9B,eAAO,MAAM,gBAAgB,wDAKxB,qBAAqB,CAAC,cAAc,CAAC,kBACxB,WAAW;;;;;CAiB5B,CAAC;AAEF,eAAO,MAAM,gBAAgB,qBACT,uBAAuB,CAAC,kBAAkB,CAAC,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,YAGlF,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,aAAc,mBAAmB,CAAC,UAAU,CAAC,YAEzE,CAAC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import type { AccountsControllerState } from "@metamask/accounts-controller";
|
|
1
2
|
import type { CaipChainId } from "@metamask/utils";
|
|
2
3
|
import { MetricsSwapType } from "./constants.mjs";
|
|
3
4
|
import type { InputKeys, InputValues } from "./types.mjs";
|
|
4
|
-
import type { AccountsControllerState } from "../../../../accounts-controller/src/AccountsController.mjs";
|
|
5
5
|
import type { BridgeControllerState, QuoteResponse, TxData } from "../../types.mjs";
|
|
6
6
|
import { type GenericQuoteRequest, type QuoteRequest } from "../../types.mjs";
|
|
7
7
|
export declare const toInputChangedPropertyKey: Partial<Record<keyof QuoteRequest, InputKeys>>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"properties.d.mts","sourceRoot":"","sources":["../../../src/utils/metrics/properties.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,wBAAwB;AAEnD,OAAO,EAAE,eAAe,EAAE,wBAAoB;AAC9C,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,oBAAgB;
|
|
1
|
+
{"version":3,"file":"properties.d.mts","sourceRoot":"","sources":["../../../src/utils/metrics/properties.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,sCAAsC;AAC7E,OAAO,KAAK,EAAE,WAAW,EAAE,wBAAwB;AAEnD,OAAO,EAAE,eAAe,EAAE,wBAAoB;AAC9C,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,oBAAgB;AAEtD,OAAO,KAAK,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,EAAE,wBAAoB;AAChF,OAAO,EAAE,KAAK,mBAAmB,EAAE,KAAK,YAAY,EAAE,wBAAoB;AAO1E,eAAO,MAAM,yBAAyB,EAAE,OAAO,CAC7C,MAAM,CAAC,MAAM,YAAY,EAAE,SAAS,CAAC,CAOtC,CAAC;AAEF,eAAO,MAAM,2BAA2B,EAAE,OAAO,CAC/C,MAAM,CACJ,MAAM,OAAO,yBAAyB,EACtC,CACE,WAAW,EAAE,OAAO,CAAC,mBAAmB,CAAC,KACtC,WAAW,CAAC,MAAM,WAAW,CAAC,GAAG,SAAS,CAChD,CAeF,CAAC;AAEF,eAAO,MAAM,WAAW,gBACT,mBAAmB,CAAC,YAAY,CAAC,gBAChC,mBAAmB,CAAC,aAAa,CAAC,oBAMjD,CAAC;AAEF,eAAO,MAAM,oBAAoB,iBACjB,QAAQ,mBAAmB,CAAC,oBAG3C,CAAC;AAEF,eAAO,MAAM,mBAAmB,2BAG7B,cAAc,MAAM,GAAG,MAAM,CAAC,CAAC,OAAO,CAAC,KAAG,GAAG,MAAM,IAAI,MAAM,EACnC,CAAC;AAE9B,eAAO,MAAM,gBAAgB,wDAKxB,qBAAqB,CAAC,cAAc,CAAC,kBACxB,WAAW;;;;;CAiB5B,CAAC;AAEF,eAAO,MAAM,gBAAgB,qBACT,uBAAuB,CAAC,kBAAkB,CAAC,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,YAGlF,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,aAAc,mBAAmB,CAAC,UAAU,CAAC,YAEzE,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"properties.mjs","sourceRoot":"","sources":["../../../src/utils/metrics/properties.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"properties.mjs","sourceRoot":"","sources":["../../../src/utils/metrics/properties.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,eAAe,EAAE,wBAAoB;AAE9C,OA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AE,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,UAAU,CAAC,IAAI,KAAK,CAAC;AAChF,CAAC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,QAAyC,EAAE,EAAE;IAC5E,OAAO,QAAQ,KAAK,+BAA+B,CAAC,YAAY,CAAC,QAAQ,CAAC;AAC5E,CAAC,CAAC","sourcesContent":["import type { AccountsControllerState } from '@metamask/accounts-controller';\nimport type { CaipChainId } from '@metamask/utils';\n\nimport { MetricsSwapType } from './constants';\nimport type { InputKeys, InputValues } from './types';\nimport { DEFAULT_BRIDGE_CONTROLLER_STATE } from '../../constants/bridge';\nimport type { BridgeControllerState, QuoteResponse, TxData } from '../../types';\nimport { type GenericQuoteRequest, type QuoteRequest } from '../../types';\nimport { getNativeAssetForChainId, isCrossChain } from '../bridge';\nimport {\n formatAddressToAssetId,\n formatChainIdToCaip,\n} from '../caip-formatters';\n\nexport const toInputChangedPropertyKey: Partial<\n Record<keyof QuoteRequest, InputKeys>\n> = {\n srcTokenAddress: 'token_source',\n destTokenAddress: 'token_destination',\n srcChainId: 'chain_source',\n destChainId: 'chain_destination',\n slippage: 'slippage',\n};\n\nexport const toInputChangedPropertyValue: Partial<\n Record<\n keyof typeof toInputChangedPropertyKey,\n (\n input_value: Partial<GenericQuoteRequest>,\n ) => InputValues[keyof InputValues] | undefined\n >\n> = {\n srcTokenAddress: ({ srcTokenAddress, srcChainId }) =>\n srcChainId\n ? formatAddressToAssetId(srcTokenAddress ?? '', srcChainId)\n : undefined,\n destTokenAddress: ({ destTokenAddress, destChainId }) =>\n destChainId\n ? formatAddressToAssetId(destTokenAddress ?? '', destChainId)\n : undefined,\n srcChainId: ({ srcChainId }) =>\n srcChainId ? formatChainIdToCaip(srcChainId) : undefined,\n destChainId: ({ destChainId }) =>\n destChainId ? formatChainIdToCaip(destChainId) : undefined,\n slippage: ({ slippage }) => (slippage ? Number(slippage) : slippage),\n};\n\nexport const getSwapType = (\n srcChainId?: GenericQuoteRequest['srcChainId'],\n destChainId?: GenericQuoteRequest['destChainId'],\n) => {\n if (srcChainId && !isCrossChain(srcChainId, destChainId ?? srcChainId)) {\n return MetricsSwapType.SINGLE;\n }\n return MetricsSwapType.CROSSCHAIN;\n};\n\nexport const getSwapTypeFromQuote = (\n quoteRequest: Partial<GenericQuoteRequest>,\n) => {\n return getSwapType(quoteRequest.srcChainId, quoteRequest.destChainId);\n};\n\nexport const formatProviderLabel = ({\n bridgeId,\n bridges,\n}: QuoteResponse<TxData | string>['quote']): `${string}_${string}` =>\n `${bridgeId}_${bridges[0]}`;\n\nexport const getRequestParams = (\n {\n destChainId,\n srcTokenAddress,\n destTokenAddress,\n }: BridgeControllerState['quoteRequest'],\n srcChainIdCaip: CaipChainId,\n) => {\n return {\n chain_id_source: srcChainIdCaip,\n chain_id_destination: destChainId ? formatChainIdToCaip(destChainId) : null,\n token_address_source: srcTokenAddress\n ? (formatAddressToAssetId(srcTokenAddress, srcChainIdCaip) ??\n getNativeAssetForChainId(srcChainIdCaip)?.assetId ??\n null)\n : (getNativeAssetForChainId(srcChainIdCaip)?.assetId ?? null),\n token_address_destination: destTokenAddress\n ? (formatAddressToAssetId(\n destTokenAddress,\n destChainId ?? srcChainIdCaip,\n ) ?? null)\n : null,\n };\n};\n\nexport const isHardwareWallet = (\n selectedAccount?: AccountsControllerState['internalAccounts']['accounts'][string],\n) => {\n return selectedAccount?.metadata?.keyring.type?.includes('Hardware') ?? false;\n};\n\n/**\n * @param slippage - The slippage percentage\n * @returns Whether the default slippage was overridden by the user\n *\n * @deprecated This function should not be used. Use {@link selectDefaultSlippagePercentage} instead.\n */\nexport const isCustomSlippage = (slippage: GenericQuoteRequest['slippage']) => {\n return slippage !== DEFAULT_BRIDGE_CONTROLLER_STATE.quoteRequest.slippage;\n};\n"]}
|