@metamask/bridge-controller 53.0.0 → 53.1.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 +19 -1
- package/dist/bridge-controller.cjs +2 -2
- package/dist/bridge-controller.cjs.map +1 -1
- package/dist/bridge-controller.mjs +2 -2
- package/dist/bridge-controller.mjs.map +1 -1
- package/dist/constants/bridge.cjs +1 -0
- package/dist/constants/bridge.cjs.map +1 -1
- package/dist/constants/bridge.d.cts +1 -1
- package/dist/constants/bridge.d.cts.map +1 -1
- package/dist/constants/bridge.d.mts +1 -1
- package/dist/constants/bridge.d.mts.map +1 -1
- package/dist/constants/bridge.mjs +1 -0
- package/dist/constants/bridge.mjs.map +1 -1
- package/dist/constants/chains.cjs +4 -1
- package/dist/constants/chains.cjs.map +1 -1
- package/dist/constants/chains.d.cts +3 -0
- package/dist/constants/chains.d.cts.map +1 -1
- package/dist/constants/chains.d.mts +3 -0
- package/dist/constants/chains.d.mts.map +1 -1
- package/dist/constants/chains.mjs +3 -0
- package/dist/constants/chains.mjs.map +1 -1
- package/dist/constants/tokens.cjs +10 -0
- package/dist/constants/tokens.cjs.map +1 -1
- package/dist/constants/tokens.d.cts +7 -0
- package/dist/constants/tokens.d.cts.map +1 -1
- package/dist/constants/tokens.d.mts +7 -0
- package/dist/constants/tokens.d.mts.map +1 -1
- package/dist/constants/tokens.mjs +10 -0
- package/dist/constants/tokens.mjs.map +1 -1
- package/dist/selectors.cjs +1 -1
- package/dist/selectors.cjs.map +1 -1
- package/dist/selectors.d.cts +258 -222
- package/dist/selectors.d.cts.map +1 -1
- package/dist/selectors.d.mts +258 -222
- package/dist/selectors.d.mts.map +1 -1
- package/dist/selectors.mjs +2 -2
- package/dist/selectors.mjs.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +3 -2
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +3 -2
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/dist/utils/bridge.cjs +5 -1
- package/dist/utils/bridge.cjs.map +1 -1
- package/dist/utils/bridge.d.cts +10 -1
- package/dist/utils/bridge.d.cts.map +1 -1
- package/dist/utils/bridge.d.mts +10 -1
- package/dist/utils/bridge.d.mts.map +1 -1
- package/dist/utils/bridge.mjs +3 -0
- package/dist/utils/bridge.mjs.map +1 -1
- package/dist/utils/fetch-server-events.cjs +61 -0
- package/dist/utils/fetch-server-events.cjs.map +1 -0
- package/dist/utils/fetch-server-events.d.cts +17 -0
- package/dist/utils/fetch-server-events.d.cts.map +1 -0
- package/dist/utils/fetch-server-events.d.mts +17 -0
- package/dist/utils/fetch-server-events.d.mts.map +1 -0
- package/dist/utils/fetch-server-events.mjs +57 -0
- package/dist/utils/fetch-server-events.mjs.map +1 -0
- package/dist/utils/fetch.cjs +14 -24
- 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 +15 -25
- package/dist/utils/fetch.mjs.map +1 -1
- package/dist/utils/quote-fees.cjs.map +1 -1
- package/dist/utils/quote-fees.mjs.map +1 -1
- package/dist/utils/quote.cjs +2 -1
- package/dist/utils/quote.cjs.map +1 -1
- package/dist/utils/quote.d.cts +3 -3
- package/dist/utils/quote.d.cts.map +1 -1
- package/dist/utils/quote.d.mts +3 -3
- package/dist/utils/quote.d.mts.map +1 -1
- package/dist/utils/quote.mjs +2 -1
- package/dist/utils/quote.mjs.map +1 -1
- package/dist/utils/validators.cjs +1 -12
- package/dist/utils/validators.cjs.map +1 -1
- package/dist/utils/validators.d.cts +0 -972
- package/dist/utils/validators.d.cts.map +1 -1
- package/dist/utils/validators.d.mts +0 -972
- package/dist/utils/validators.d.mts.map +1 -1
- package/dist/utils/validators.mjs +0 -10
- package/dist/utils/validators.mjs.map +1 -1
- package/package.json +1 -2
package/dist/utils/bridge.d.mts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { CaipChainId } from "@metamask/utils";
|
|
2
2
|
import { type Hex } from "@metamask/utils";
|
|
3
|
-
import type { BridgeAsset, BridgeControllerState, GenericQuoteRequest } from "../types.mjs";
|
|
3
|
+
import type { BridgeAsset, BridgeControllerState, GenericQuoteRequest, QuoteResponse } from "../types.mjs";
|
|
4
4
|
export declare const getDefaultBridgeControllerState: () => BridgeControllerState;
|
|
5
5
|
/**
|
|
6
6
|
* Returns the native swaps or bridge asset for a given chainId
|
|
@@ -59,6 +59,15 @@ export declare const isBitcoinChainId: (chainId: Hex | number | CaipChainId | st
|
|
|
59
59
|
* @returns True if the chain is a supported non-EVM chain, false otherwise
|
|
60
60
|
*/
|
|
61
61
|
export declare const isNonEvmChainId: (chainId: GenericQuoteRequest['srcChainId']) => boolean;
|
|
62
|
+
export declare const isEvmQuoteResponse: (quoteResponse: QuoteResponse) => quoteResponse is QuoteResponse<{
|
|
63
|
+
data: string;
|
|
64
|
+
value: string;
|
|
65
|
+
to: string;
|
|
66
|
+
from: string;
|
|
67
|
+
gasLimit: number | null;
|
|
68
|
+
chainId: number;
|
|
69
|
+
effectiveGas?: number | undefined;
|
|
70
|
+
}>;
|
|
62
71
|
/**
|
|
63
72
|
* Checks whether the transaction is a cross-chain transaction by comparing the source and destination chainIds
|
|
64
73
|
*
|
|
@@ -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,
|
|
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,KAA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BitcoinChainId = (chainId) => {
|
|
|
134
134
|
export const isNonEvmChainId = (chainId) => {
|
|
135
135
|
return isSolanaChainId(chainId) || isBitcoinChainId(chainId);
|
|
136
136
|
};
|
|
137
|
+
export const isEvmQuoteResponse = (quoteResponse) => {
|
|
138
|
+
return !isNonEvmChainId(quoteResponse.quote.srcChainId);
|
|
139
|
+
};
|
|
137
140
|
/**
|
|
138
141
|
* Checks whether the transaction is a cross-chain transaction by comparing the source and destination chainIds
|
|
139
142
|
*
|
|
@@ -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,MAA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,OAAO,KAAK,QAAQ,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;KAChD;IACD,OAAO,OAAO,CAAC,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,eAAe,GAAG,CAC7B,OAA0C,EACjC,EAAE;IACX,OAAO,eAAe,CAAC,OAAO,CAAC,IAAI,gBAAgB,CAAC,OAAO,CAAC,CAAC;AAC/D,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 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"]}
|
|
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,iCA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,CAAC,MAAM,eAAe,GAAG,CAC7B,OAA0C,EACjC,EAAE;IACX,OAAO,eAAe,CAAC,OAAO,CAAC,IAAI,gBAAgB,CAAC,OAAO,CAAC,CAAC;AAC/D,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAChC,aAA4B,EACY,EAAE;IAC1C,OAAO,CAAC,eAAe,CAAC,aAAa,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;AAC1D,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 QuoteResponse,\n TxData,\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\nexport const isEvmQuoteResponse = (\n quoteResponse: QuoteResponse,\n): quoteResponse is QuoteResponse<TxData> => {\n return !isNonEvmChainId(quoteResponse.quote.srcChainId);\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"]}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.fetchServerEvents = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Streams server-sent events from the given URL
|
|
6
|
+
*
|
|
7
|
+
* @param url - The URL to stream events from
|
|
8
|
+
* @param options - The options for the SSE stream
|
|
9
|
+
* @param options.onMessage - The function to call when a message is received
|
|
10
|
+
* @param options.onError - The function to call when an error occurs
|
|
11
|
+
* @param options.onClose - The function to call when the stream finishes successfully
|
|
12
|
+
* @param options.fetchFn - The function to use to fetch the events. Consumers need to provide a fetch function that supports server-sent events.
|
|
13
|
+
*/
|
|
14
|
+
const fetchServerEvents = async (url, { onMessage, onError, onClose, fetchFn, ...requestOptions }) => {
|
|
15
|
+
try {
|
|
16
|
+
const response = await fetchFn(url, requestOptions);
|
|
17
|
+
if (!response.ok || !response.body) {
|
|
18
|
+
throw new Error(`${response.status}`);
|
|
19
|
+
}
|
|
20
|
+
const reader = response.body.getReader();
|
|
21
|
+
const decoder = new TextDecoder('utf-8');
|
|
22
|
+
let buffer = '';
|
|
23
|
+
while (true) {
|
|
24
|
+
const { done, value } = await reader.read();
|
|
25
|
+
if (done) {
|
|
26
|
+
break;
|
|
27
|
+
}
|
|
28
|
+
buffer += decoder.decode(value, { stream: true });
|
|
29
|
+
// Split SSE messages at double newlines
|
|
30
|
+
const parts = buffer.split('\n\n');
|
|
31
|
+
buffer = parts.pop() || '';
|
|
32
|
+
// Split chunks into lines and parse the data
|
|
33
|
+
for (const chunk of parts) {
|
|
34
|
+
const lines = chunk.split('\n');
|
|
35
|
+
let eventName;
|
|
36
|
+
const dataLines = [];
|
|
37
|
+
for (const line of lines) {
|
|
38
|
+
if (line.startsWith('event:')) {
|
|
39
|
+
eventName = line.slice(6).trim();
|
|
40
|
+
}
|
|
41
|
+
else if (line.startsWith('data:')) {
|
|
42
|
+
dataLines.push(line.slice(5).trim());
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (eventName === 'error') {
|
|
46
|
+
throw new Error(`Bridge-api error: ${dataLines.join('\n')}`);
|
|
47
|
+
}
|
|
48
|
+
if (dataLines.length > 0) {
|
|
49
|
+
const parsedJSONData = JSON.parse(dataLines.join('\n'));
|
|
50
|
+
onMessage(parsedJSONData, eventName);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
onClose?.();
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
onError?.(error);
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
exports.fetchServerEvents = fetchServerEvents;
|
|
61
|
+
//# sourceMappingURL=fetch-server-events.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetch-server-events.cjs","sourceRoot":"","sources":["../../src/utils/fetch-server-events.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;GASG;AACI,MAAM,iBAAiB,GAAG,KAAK,EACpC,GAAW,EACX,EACE,SAAS,EACT,OAAO,EACP,OAAO,EACP,OAAO,EACP,GAAG,cAAc,EAMlB,EACD,EAAE;IACF,IAAI;QACF,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;QACpD,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE;YAClC,MAAM,IAAI,KAAK,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;SACvC;QAED,MAAM,MAAM,GAAG,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;QACzC,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,OAAO,CAAC,CAAC;QACzC,IAAI,MAAM,GAAG,EAAE,CAAC;QAEhB,OAAO,IAAI,EAAE;YACX,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;YAE5C,IAAI,IAAI,EAAE;gBACR,MAAM;aACP;YAED,MAAM,IAAI,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;YAElD,wCAAwC;YACxC,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;YACnC,MAAM,GAAG,KAAK,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC;YAE3B,6CAA6C;YAC7C,KAAK,MAAM,KAAK,IAAI,KAAK,EAAE;gBACzB,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;gBAChC,IAAI,SAA6B,CAAC;gBAClC,MAAM,SAAS,GAAa,EAAE,CAAC;gBAE/B,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;oBACxB,IAAI,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE;wBAC7B,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;qBAClC;yBAAM,IAAI,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE;wBACnC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;qBACtC;iBACF;gBAED,IAAI,SAAS,KAAK,OAAO,EAAE;oBACzB,MAAM,IAAI,KAAK,CAAC,qBAAqB,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;iBAC9D;gBACD,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE;oBACxB,MAAM,cAAc,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;oBACxD,SAAS,CAAC,cAAc,EAAE,SAAS,CAAC,CAAC;iBACtC;aACF;SACF;QACD,OAAO,EAAE,EAAE,CAAC;KACb;IAAC,OAAO,KAAK,EAAE;QACd,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC;KAClB;AACH,CAAC,CAAC;AAjEW,QAAA,iBAAiB,qBAiE5B","sourcesContent":["/**\n * Streams server-sent events from the given URL\n *\n * @param url - The URL to stream events from\n * @param options - The options for the SSE stream\n * @param options.onMessage - The function to call when a message is received\n * @param options.onError - The function to call when an error occurs\n * @param options.onClose - The function to call when the stream finishes successfully\n * @param options.fetchFn - The function to use to fetch the events. Consumers need to provide a fetch function that supports server-sent events.\n */\nexport const fetchServerEvents = async (\n url: string,\n {\n onMessage,\n onError,\n onClose,\n fetchFn,\n ...requestOptions\n }: RequestInit & {\n onMessage: (data: Record<string, unknown>, eventName?: string) => void;\n onError?: (err: unknown) => void;\n onClose?: () => void;\n fetchFn: typeof fetch;\n },\n) => {\n try {\n const response = await fetchFn(url, requestOptions);\n if (!response.ok || !response.body) {\n throw new Error(`${response.status}`);\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder('utf-8');\n let buffer = '';\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n\n // Split SSE messages at double newlines\n const parts = buffer.split('\\n\\n');\n buffer = parts.pop() || '';\n\n // Split chunks into lines and parse the data\n for (const chunk of parts) {\n const lines = chunk.split('\\n');\n let eventName: string | undefined;\n const dataLines: string[] = [];\n\n for (const line of lines) {\n if (line.startsWith('event:')) {\n eventName = line.slice(6).trim();\n } else if (line.startsWith('data:')) {\n dataLines.push(line.slice(5).trim());\n }\n }\n\n if (eventName === 'error') {\n throw new Error(`Bridge-api error: ${dataLines.join('\\n')}`);\n }\n if (dataLines.length > 0) {\n const parsedJSONData = JSON.parse(dataLines.join('\\n'));\n onMessage(parsedJSONData, eventName);\n }\n }\n }\n onClose?.();\n } catch (error) {\n onError?.(error);\n }\n};\n"]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streams server-sent events from the given URL
|
|
3
|
+
*
|
|
4
|
+
* @param url - The URL to stream events from
|
|
5
|
+
* @param options - The options for the SSE stream
|
|
6
|
+
* @param options.onMessage - The function to call when a message is received
|
|
7
|
+
* @param options.onError - The function to call when an error occurs
|
|
8
|
+
* @param options.onClose - The function to call when the stream finishes successfully
|
|
9
|
+
* @param options.fetchFn - The function to use to fetch the events. Consumers need to provide a fetch function that supports server-sent events.
|
|
10
|
+
*/
|
|
11
|
+
export declare const fetchServerEvents: (url: string, { onMessage, onError, onClose, fetchFn, ...requestOptions }: RequestInit & {
|
|
12
|
+
onMessage: (data: Record<string, unknown>, eventName?: string) => void;
|
|
13
|
+
onError?: ((err: unknown) => void) | undefined;
|
|
14
|
+
onClose?: (() => void) | undefined;
|
|
15
|
+
fetchFn: typeof fetch;
|
|
16
|
+
}) => Promise<void>;
|
|
17
|
+
//# sourceMappingURL=fetch-server-events.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetch-server-events.d.cts","sourceRoot":"","sources":["../../src/utils/fetch-server-events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,eAAO,MAAM,iBAAiB,QACvB,MAAM;sBAQS,OAAO,MAAM,EAAE,OAAO,CAAC,cAAc,MAAM,KAAK,IAAI;qBACtD,OAAO,KAAK,IAAI;qBAChB,IAAI;aACX,YAAY;mBAqDxB,CAAC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streams server-sent events from the given URL
|
|
3
|
+
*
|
|
4
|
+
* @param url - The URL to stream events from
|
|
5
|
+
* @param options - The options for the SSE stream
|
|
6
|
+
* @param options.onMessage - The function to call when a message is received
|
|
7
|
+
* @param options.onError - The function to call when an error occurs
|
|
8
|
+
* @param options.onClose - The function to call when the stream finishes successfully
|
|
9
|
+
* @param options.fetchFn - The function to use to fetch the events. Consumers need to provide a fetch function that supports server-sent events.
|
|
10
|
+
*/
|
|
11
|
+
export declare const fetchServerEvents: (url: string, { onMessage, onError, onClose, fetchFn, ...requestOptions }: RequestInit & {
|
|
12
|
+
onMessage: (data: Record<string, unknown>, eventName?: string) => void;
|
|
13
|
+
onError?: ((err: unknown) => void) | undefined;
|
|
14
|
+
onClose?: (() => void) | undefined;
|
|
15
|
+
fetchFn: typeof fetch;
|
|
16
|
+
}) => Promise<void>;
|
|
17
|
+
//# sourceMappingURL=fetch-server-events.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetch-server-events.d.mts","sourceRoot":"","sources":["../../src/utils/fetch-server-events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,eAAO,MAAM,iBAAiB,QACvB,MAAM;sBAQS,OAAO,MAAM,EAAE,OAAO,CAAC,cAAc,MAAM,KAAK,IAAI;qBACtD,OAAO,KAAK,IAAI;qBAChB,IAAI;aACX,YAAY;mBAqDxB,CAAC"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streams server-sent events from the given URL
|
|
3
|
+
*
|
|
4
|
+
* @param url - The URL to stream events from
|
|
5
|
+
* @param options - The options for the SSE stream
|
|
6
|
+
* @param options.onMessage - The function to call when a message is received
|
|
7
|
+
* @param options.onError - The function to call when an error occurs
|
|
8
|
+
* @param options.onClose - The function to call when the stream finishes successfully
|
|
9
|
+
* @param options.fetchFn - The function to use to fetch the events. Consumers need to provide a fetch function that supports server-sent events.
|
|
10
|
+
*/
|
|
11
|
+
export const fetchServerEvents = async (url, { onMessage, onError, onClose, fetchFn, ...requestOptions }) => {
|
|
12
|
+
try {
|
|
13
|
+
const response = await fetchFn(url, requestOptions);
|
|
14
|
+
if (!response.ok || !response.body) {
|
|
15
|
+
throw new Error(`${response.status}`);
|
|
16
|
+
}
|
|
17
|
+
const reader = response.body.getReader();
|
|
18
|
+
const decoder = new TextDecoder('utf-8');
|
|
19
|
+
let buffer = '';
|
|
20
|
+
while (true) {
|
|
21
|
+
const { done, value } = await reader.read();
|
|
22
|
+
if (done) {
|
|
23
|
+
break;
|
|
24
|
+
}
|
|
25
|
+
buffer += decoder.decode(value, { stream: true });
|
|
26
|
+
// Split SSE messages at double newlines
|
|
27
|
+
const parts = buffer.split('\n\n');
|
|
28
|
+
buffer = parts.pop() || '';
|
|
29
|
+
// Split chunks into lines and parse the data
|
|
30
|
+
for (const chunk of parts) {
|
|
31
|
+
const lines = chunk.split('\n');
|
|
32
|
+
let eventName;
|
|
33
|
+
const dataLines = [];
|
|
34
|
+
for (const line of lines) {
|
|
35
|
+
if (line.startsWith('event:')) {
|
|
36
|
+
eventName = line.slice(6).trim();
|
|
37
|
+
}
|
|
38
|
+
else if (line.startsWith('data:')) {
|
|
39
|
+
dataLines.push(line.slice(5).trim());
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (eventName === 'error') {
|
|
43
|
+
throw new Error(`Bridge-api error: ${dataLines.join('\n')}`);
|
|
44
|
+
}
|
|
45
|
+
if (dataLines.length > 0) {
|
|
46
|
+
const parsedJSONData = JSON.parse(dataLines.join('\n'));
|
|
47
|
+
onMessage(parsedJSONData, eventName);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
onClose?.();
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
onError?.(error);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
//# sourceMappingURL=fetch-server-events.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fetch-server-events.mjs","sourceRoot":"","sources":["../../src/utils/fetch-server-events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,KAAK,EACpC,GAAW,EACX,EACE,SAAS,EACT,OAAO,EACP,OAAO,EACP,OAAO,EACP,GAAG,cAAc,EAMlB,EACD,EAAE;IACF,IAAI;QACF,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;QACpD,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE;YAClC,MAAM,IAAI,KAAK,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;SACvC;QAED,MAAM,MAAM,GAAG,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;QACzC,MAAM,OAAO,GAAG,IAAI,WAAW,CAAC,OAAO,CAAC,CAAC;QACzC,IAAI,MAAM,GAAG,EAAE,CAAC;QAEhB,OAAO,IAAI,EAAE;YACX,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,GAA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E,CAAC;KACb;IAAC,OAAO,KAAK,EAAE;QACd,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC;KAClB;AACH,CAAC,CAAC","sourcesContent":["/**\n * Streams server-sent events from the given URL\n *\n * @param url - The URL to stream events from\n * @param options - The options for the SSE stream\n * @param options.onMessage - The function to call when a message is received\n * @param options.onError - The function to call when an error occurs\n * @param options.onClose - The function to call when the stream finishes successfully\n * @param options.fetchFn - The function to use to fetch the events. Consumers need to provide a fetch function that supports server-sent events.\n */\nexport const fetchServerEvents = async (\n url: string,\n {\n onMessage,\n onError,\n onClose,\n fetchFn,\n ...requestOptions\n }: RequestInit & {\n onMessage: (data: Record<string, unknown>, eventName?: string) => void;\n onError?: (err: unknown) => void;\n onClose?: () => void;\n fetchFn: typeof fetch;\n },\n) => {\n try {\n const response = await fetchFn(url, requestOptions);\n if (!response.ok || !response.body) {\n throw new Error(`${response.status}`);\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder('utf-8');\n let buffer = '';\n\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n\n // Split SSE messages at double newlines\n const parts = buffer.split('\\n\\n');\n buffer = parts.pop() || '';\n\n // Split chunks into lines and parse the data\n for (const chunk of parts) {\n const lines = chunk.split('\\n');\n let eventName: string | undefined;\n const dataLines: string[] = [];\n\n for (const line of lines) {\n if (line.startsWith('event:')) {\n eventName = line.slice(6).trim();\n } else if (line.startsWith('data:')) {\n dataLines.push(line.slice(5).trim());\n }\n }\n\n if (eventName === 'error') {\n throw new Error(`Bridge-api error: ${dataLines.join('\\n')}`);\n }\n if (dataLines.length > 0) {\n const parsedJSONData = JSON.parse(dataLines.join('\\n'));\n onMessage(parsedJSONData, eventName);\n }\n }\n }\n onClose?.();\n } catch (error) {\n onError?.(error);\n }\n};\n"]}
|
package/dist/utils/fetch.cjs
CHANGED
|
@@ -2,9 +2,8 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.fetchBridgeQuoteStream = exports.fetchAssetPrices = exports.fetchBridgeQuotes = exports.fetchBridgeTokens = exports.getClientHeaders = void 0;
|
|
4
4
|
const superstruct_1 = require("@metamask/superstruct");
|
|
5
|
-
const fetch_event_source_1 = require("@microsoft/fetch-event-source");
|
|
6
|
-
const bridge_1 = require("./bridge.cjs");
|
|
7
5
|
const caip_formatters_1 = require("./caip-formatters.cjs");
|
|
6
|
+
const fetch_server_events_1 = require("./fetch-server-events.cjs");
|
|
8
7
|
const validators_1 = require("./validators.cjs");
|
|
9
8
|
const getClientHeaders = (clientId, clientVersion) => ({
|
|
10
9
|
'X-Client-Id': clientId,
|
|
@@ -102,10 +101,6 @@ async function fetchBridgeQuotes(request, signal, clientId, fetchFn, bridgeApiBa
|
|
|
102
101
|
const filteredQuotes = quotes
|
|
103
102
|
.filter((quoteResponse) => {
|
|
104
103
|
try {
|
|
105
|
-
const isBitcoinQuote = (0, bridge_1.isBitcoinChainId)(request.srcChainId);
|
|
106
|
-
if (isBitcoinQuote) {
|
|
107
|
-
return (0, validators_1.validateBitcoinQuoteResponse)(quoteResponse);
|
|
108
|
-
}
|
|
109
104
|
return (0, validators_1.validateQuoteResponse)(quoteResponse);
|
|
110
105
|
}
|
|
111
106
|
catch (error) {
|
|
@@ -214,18 +209,15 @@ exports.fetchAssetPrices = fetchAssetPrices;
|
|
|
214
209
|
*/
|
|
215
210
|
async function fetchBridgeQuoteStream(fetchFn, request, signal, clientId, bridgeApiBaseUrl, serverEventHandlers, clientVersion) {
|
|
216
211
|
const queryParams = formatQueryParams(request);
|
|
217
|
-
const onMessage = (
|
|
212
|
+
const onMessage = (quoteResponse) => {
|
|
218
213
|
const uniqueValidationFailures = new Set([]);
|
|
219
|
-
if (event.data === '') {
|
|
220
|
-
return;
|
|
221
|
-
}
|
|
222
|
-
const quoteResponse = JSON.parse(event.data);
|
|
223
214
|
try {
|
|
224
|
-
(0, validators_1.validateQuoteResponse)(quoteResponse)
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
215
|
+
if ((0, validators_1.validateQuoteResponse)(quoteResponse)) {
|
|
216
|
+
// eslint-disable-next-line promise/catch-or-return, @typescript-eslint/no-floating-promises
|
|
217
|
+
serverEventHandlers.onValidQuoteReceived(quoteResponse).then((v) => {
|
|
218
|
+
return v;
|
|
219
|
+
});
|
|
220
|
+
}
|
|
229
221
|
}
|
|
230
222
|
catch (error) {
|
|
231
223
|
if (error instanceof superstruct_1.StructError) {
|
|
@@ -251,23 +243,21 @@ async function fetchBridgeQuoteStream(fetchFn, request, signal, clientId, bridge
|
|
|
251
243
|
}
|
|
252
244
|
};
|
|
253
245
|
const urlStream = `${bridgeApiBaseUrl}/getQuoteStream?${queryParams}`;
|
|
254
|
-
await (0,
|
|
246
|
+
await (0, fetch_server_events_1.fetchServerEvents)(urlStream, {
|
|
255
247
|
headers: {
|
|
256
248
|
...(0, exports.getClientHeaders)(clientId, clientVersion),
|
|
257
249
|
'Content-Type': 'text/event-stream',
|
|
258
250
|
},
|
|
259
251
|
signal,
|
|
260
|
-
|
|
261
|
-
|
|
252
|
+
onMessage,
|
|
253
|
+
onError: (e) => {
|
|
262
254
|
// Rethrow error to prevent silent fetch failures
|
|
263
|
-
throw
|
|
255
|
+
throw e;
|
|
264
256
|
},
|
|
265
|
-
|
|
257
|
+
onClose: () => {
|
|
266
258
|
serverEventHandlers.onClose();
|
|
267
259
|
},
|
|
268
|
-
|
|
269
|
-
openWhenHidden: false,
|
|
270
|
-
fetch: fetchFn,
|
|
260
|
+
fetchFn,
|
|
271
261
|
});
|
|
272
262
|
}
|
|
273
263
|
exports.fetchBridgeQuoteStream = fetchBridgeQuoteStream;
|
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;AAGpD,sEAAiE;AAEj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;gBAC5D,mBAAmB,CAAC,mBAAmB,CAAC,kBAAkB,CAAC,CAAC;aAC7D;iBAAM;gBACL,gCAAgC;gBAChC,MAAM,KAAK,CAAC;aACb;SACF;IACH,CAAC,CAAC;IAEF,MAAM,SAAS,GAAG,GAAG,gBAAgB,mBAAmB,WAAW,EAAE,CAAC;IACtE,MAAM,IAAA,qCAAgB,EAAC,SAAS,EAAE;QAChC,OAAO,EAAE;YACP,GAAG,IAAA,wBAAgB,EAAC,QAAQ,EAAE,aAAa,CAAC;YAC5C,cAAc,EAAE,mBAAmB;SACpC;QACD,MAAM;QACN,SAAS,EAAE,SAAS;QACpB,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE;YACb,iDAAiD;YACjD,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC;QAChC,CAAC;QACD,OAAO,EAAE,GAAG,EAAE;YACZ,mBAAmB,CAAC,OAAO,EAAE,CAAC;QAChC,CAAC;QACD,uFAAuF;QACvF,cAAc,EAAE,KAAK;QACrB,KAAK,EAAE,OAAO;KACf,CAAC,CAAC;AACL,CAAC;AAvED,wDAuEC","sourcesContent":["import { StructError } from '@metamask/superstruct';\nimport type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';\nimport type { EventSourceMessage } from '@microsoft/fetch-event-source';\nimport { fetchEventSource } from '@microsoft/fetch-event-source';\n\nimport { isBitcoinChainId } from './bridge';\nimport {\n formatAddressToCaipReference,\n formatChainIdToDec,\n} from './caip-formatters';\nimport type { FeatureId } from './validators';\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\nexport const getClientHeaders = (clientId: string, clientVersion?: string) => ({\n 'X-Client-Id': clientId,\n ...(clientVersion ? { 'Client-Version': clientVersion } : {}),\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 * @param clientVersion - The client version for metrics (optional)\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 clientVersion?: 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: getClientHeaders(clientId, clientVersion),\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 *\n * @param request - The quote request\n * @returns A URLSearchParams object with the query parameters\n */\nconst formatQueryParams = (request: GenericQuoteRequest): URLSearchParams => {\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 return queryParams;\n};\n\n/**\n * Fetches quotes from the bridge-api's getQuote endpoint\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 * @param featureId - The feature ID to append to each quote\n * @param clientVersion - The client version for metrics (optional)\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 featureId: FeatureId | null,\n clientVersion?: string,\n): Promise<{\n quotes: QuoteResponse[];\n validationFailures: string[];\n}> {\n const queryParams = formatQueryParams(request);\n\n const url = `${bridgeApiBaseUrl}/getQuote?${queryParams}`;\n const quotes: unknown[] = await fetchFn(url, {\n headers: getClientHeaders(clientId, clientVersion),\n signal,\n });\n\n const uniqueValidationFailures: Set<string> = new Set<string>([]);\n const filteredQuotes = quotes\n .filter((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 .map((quote) => ({\n ...quote,\n featureId: featureId ?? undefined,\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 clientVersion?: string;\n fetchFn: FetchFunction;\n signal?: AbortSignal;\n}): Promise<Record<CaipAssetType, { [currency: string]: string }>> => {\n const { currency, assetIds, clientId, clientVersion, fetchFn, signal } =\n 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: getClientHeaders(clientId, clientVersion),\n signal,\n })) as Record<CaipAssetType, { [currency: string]: number }>;\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\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 fetchFn - The fetch function to use\n * @param request - The quote request\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @param serverEventHandlers - The server event handlers\n * @param serverEventHandlers.onValidationFailure - The function to handle validation failures\n * @param serverEventHandlers.onValidQuoteReceived - The function to handle valid quotes\n * @param serverEventHandlers.onClose - The function to run when the stream is closed and there are no thrown errors\n * @param clientVersion - The client version for metrics (optional)\n * @returns A list of bridge tx quotes\n */\nexport async function fetchBridgeQuoteStream(\n fetchFn: FetchFunction,\n request: GenericQuoteRequest,\n signal: AbortSignal | undefined,\n clientId: string,\n bridgeApiBaseUrl: string,\n serverEventHandlers: {\n onClose: () => void;\n onValidationFailure: (validationFailures: string[]) => void;\n onValidQuoteReceived: (quotes: QuoteResponse) => Promise<void>;\n },\n clientVersion?: string,\n): Promise<void> {\n const queryParams = formatQueryParams(request);\n\n const onMessage = (event: EventSourceMessage) => {\n const uniqueValidationFailures: Set<string> = new Set<string>([]);\n if (event.data === '') {\n return;\n }\n const quoteResponse = JSON.parse(event.data);\n\n try {\n validateQuoteResponse(quoteResponse);\n // eslint-disable-next-line promise/catch-or-return, @typescript-eslint/no-floating-promises\n serverEventHandlers.onValidQuoteReceived(quoteResponse).then((v) => {\n return v;\n });\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 const validationFailures = Array.from(uniqueValidationFailures);\n if (uniqueValidationFailures.size > 0) {\n console.warn('Quote validation failed', validationFailures);\n serverEventHandlers.onValidationFailure(validationFailures);\n } else {\n // Rethrow any unexpected errors\n throw error;\n }\n }\n };\n\n const urlStream = `${bridgeApiBaseUrl}/getQuoteStream?${queryParams}`;\n await fetchEventSource(urlStream, {\n headers: {\n ...getClientHeaders(clientId, clientVersion),\n 'Content-Type': 'text/event-stream',\n },\n signal,\n onmessage: onMessage,\n onerror: (e) => {\n // Rethrow error to prevent silent fetch failures\n throw new Error(e.toString());\n },\n onclose: () => {\n serverEventHandlers.onClose();\n },\n // Cancels the request when document is hidden, will automatically restart when visible\n openWhenHidden: false,\n fetch: fetchFn,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fetch.cjs","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":";;;AAAA,uDAAoD;AAGpD,2DAG2B;AAC3B,mEAA0D;AAE1D,iDAA+E;AASxE,MAAM,gBAAgB,GAAG,CAAC,QAAgB,EAAE,aAAsB,EAAE,EAAE,CAAC,CAAC;IAC7E,aAAa,EAAE,QAAQ;IACvB,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,gBAAgB,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;CAC9D,CAAC,CAAC;AAHU,QA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,CAAC,CAAC;AACL,CAAC;AAlED,wDAkEC","sourcesContent":["import { StructError } from '@metamask/superstruct';\nimport type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';\n\nimport {\n formatAddressToCaipReference,\n formatChainIdToDec,\n} from './caip-formatters';\nimport { fetchServerEvents } from './fetch-server-events';\nimport type { FeatureId } from './validators';\nimport { validateQuoteResponse, validateSwapsTokenObject } from './validators';\nimport type {\n QuoteResponse,\n FetchFunction,\n GenericQuoteRequest,\n QuoteRequest,\n BridgeAsset,\n} from '../types';\n\nexport const getClientHeaders = (clientId: string, clientVersion?: string) => ({\n 'X-Client-Id': clientId,\n ...(clientVersion ? { 'Client-Version': clientVersion } : {}),\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 * @param clientVersion - The client version for metrics (optional)\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 clientVersion?: 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: getClientHeaders(clientId, clientVersion),\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 *\n * @param request - The quote request\n * @returns A URLSearchParams object with the query parameters\n */\nconst formatQueryParams = (request: GenericQuoteRequest): URLSearchParams => {\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 return queryParams;\n};\n\n/**\n * Fetches quotes from the bridge-api's getQuote endpoint\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 * @param featureId - The feature ID to append to each quote\n * @param clientVersion - The client version for metrics (optional)\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 featureId: FeatureId | null,\n clientVersion?: string,\n): Promise<{\n quotes: QuoteResponse[];\n validationFailures: string[];\n}> {\n const queryParams = formatQueryParams(request);\n\n const url = `${bridgeApiBaseUrl}/getQuote?${queryParams}`;\n const quotes: unknown[] = await fetchFn(url, {\n headers: getClientHeaders(clientId, clientVersion),\n signal,\n });\n\n const uniqueValidationFailures: Set<string> = new Set<string>([]);\n const filteredQuotes = quotes\n .filter((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 .map((quote) => ({\n ...quote,\n featureId: featureId ?? undefined,\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 clientVersion?: string;\n fetchFn: FetchFunction;\n signal?: AbortSignal;\n}): Promise<Record<CaipAssetType, { [currency: string]: string }>> => {\n const { currency, assetIds, clientId, clientVersion, fetchFn, signal } =\n 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: getClientHeaders(clientId, clientVersion),\n signal,\n })) as Record<CaipAssetType, { [currency: string]: number }>;\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\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 fetchFn - The fetch function to use\n * @param request - The quote request\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @param serverEventHandlers - The server event handlers\n * @param serverEventHandlers.onValidationFailure - The function to handle validation failures\n * @param serverEventHandlers.onValidQuoteReceived - The function to handle valid quotes\n * @param serverEventHandlers.onClose - The function to run when the stream is closed and there are no thrown errors\n * @param clientVersion - The client version for metrics (optional)\n * @returns A list of bridge tx quotes\n */\nexport async function fetchBridgeQuoteStream(\n fetchFn: FetchFunction,\n request: GenericQuoteRequest,\n signal: AbortSignal | undefined,\n clientId: string,\n bridgeApiBaseUrl: string,\n serverEventHandlers: {\n onClose: () => void;\n onValidationFailure: (validationFailures: string[]) => void;\n onValidQuoteReceived: (quotes: QuoteResponse) => Promise<void>;\n },\n clientVersion?: string,\n): Promise<void> {\n const queryParams = formatQueryParams(request);\n\n const onMessage = (quoteResponse: unknown) => {\n const uniqueValidationFailures: Set<string> = new Set<string>([]);\n\n try {\n if (validateQuoteResponse(quoteResponse)) {\n // eslint-disable-next-line promise/catch-or-return, @typescript-eslint/no-floating-promises\n serverEventHandlers.onValidQuoteReceived(quoteResponse).then((v) => {\n return v;\n });\n }\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 const validationFailures = Array.from(uniqueValidationFailures);\n if (uniqueValidationFailures.size > 0) {\n console.warn('Quote validation failed', validationFailures);\n serverEventHandlers.onValidationFailure(validationFailures);\n } else {\n // Rethrow any unexpected errors\n throw error;\n }\n }\n };\n\n const urlStream = `${bridgeApiBaseUrl}/getQuoteStream?${queryParams}`;\n await fetchServerEvents(urlStream, {\n headers: {\n ...getClientHeaders(clientId, clientVersion),\n 'Content-Type': 'text/event-stream',\n },\n signal,\n onMessage,\n onError: (e) => {\n // Rethrow error to prevent silent fetch failures\n throw e;\n },\n onClose: () => {\n serverEventHandlers.onClose();\n },\n fetchFn,\n });\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.d.cts","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":"AACA,O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C;IACvB,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;;GAqCA,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;AAEF;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,sBAAsB,CAC1C,OAAO,EAAE,aAAa,EACtB,OAAO,EAAE,mBAAmB,EAC5B,MAAM,EAAE,WAAW,GAAG,SAAS,EAC/B,QAAQ,EAAE,MAAM,EAChB,gBAAgB,EAAE,MAAM,EACxB,mBAAmB,EAAE;IACnB,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB,mBAAmB,EAAE,CAAC,kBAAkB,EAAE,MAAM,EAAE,KAAK,IAAI,CAAC;IAC5D,oBAAoB,EAAE,CAAC,MAAM,EAAE,aAAa,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAChE,EACD,aAAa,CAAC,EAAE,MAAM,GACrB,OAAO,CAAC,IAAI,CAAC,CAsDf"}
|
|
@@ -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;AAOvE,OAAO,KAAK,EAAE,SAAS,EAAE,yBAAqB;AAE9C,OAAO,KAAK,EACV,aAAa,EACb,aAAa,EACb,mBAAmB,EAEnB,WAAW,EACZ,qBAAiB;AAElB,eAAO,MAAM,gBAAgB,aAAc,MAAM,kBAAkB,MAAM;;;CAGvE,CAAC;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B,gBAAgB,EAAE,MAAM,EACxB,mBAAmB,EAAE;IACnB,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB,mBAAmB,EAAE,CAAC,kBAAkB,EAAE,MAAM,EAAE,KAAK,IAAI,CAAC;IAC5D,oBAAoB,EAAE,CAAC,MAAM,EAAE,aAAa,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAChE,EACD,aAAa,CAAC,EAAE,MAAM,GACrB,OAAO,CAAC,IAAI,CAAC,CAsDf"}
|
package/dist/utils/fetch.mjs
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { StructError } from "@metamask/superstruct";
|
|
2
|
-
import { fetchEventSource } from "@microsoft/fetch-event-source";
|
|
3
|
-
import { isBitcoinChainId } from "./bridge.mjs";
|
|
4
2
|
import { formatAddressToCaipReference, formatChainIdToDec } from "./caip-formatters.mjs";
|
|
5
|
-
import {
|
|
3
|
+
import { fetchServerEvents } from "./fetch-server-events.mjs";
|
|
4
|
+
import { validateQuoteResponse, validateSwapsTokenObject } from "./validators.mjs";
|
|
6
5
|
export const getClientHeaders = (clientId, clientVersion) => ({
|
|
7
6
|
'X-Client-Id': clientId,
|
|
8
7
|
...(clientVersion ? { 'Client-Version': clientVersion } : {}),
|
|
@@ -97,10 +96,6 @@ export async function fetchBridgeQuotes(request, signal, clientId, fetchFn, brid
|
|
|
97
96
|
const filteredQuotes = quotes
|
|
98
97
|
.filter((quoteResponse) => {
|
|
99
98
|
try {
|
|
100
|
-
const isBitcoinQuote = isBitcoinChainId(request.srcChainId);
|
|
101
|
-
if (isBitcoinQuote) {
|
|
102
|
-
return validateBitcoinQuoteResponse(quoteResponse);
|
|
103
|
-
}
|
|
104
99
|
return validateQuoteResponse(quoteResponse);
|
|
105
100
|
}
|
|
106
101
|
catch (error) {
|
|
@@ -207,18 +202,15 @@ export const fetchAssetPrices = async (request) => {
|
|
|
207
202
|
*/
|
|
208
203
|
export async function fetchBridgeQuoteStream(fetchFn, request, signal, clientId, bridgeApiBaseUrl, serverEventHandlers, clientVersion) {
|
|
209
204
|
const queryParams = formatQueryParams(request);
|
|
210
|
-
const onMessage = (
|
|
205
|
+
const onMessage = (quoteResponse) => {
|
|
211
206
|
const uniqueValidationFailures = new Set([]);
|
|
212
|
-
if (event.data === '') {
|
|
213
|
-
return;
|
|
214
|
-
}
|
|
215
|
-
const quoteResponse = JSON.parse(event.data);
|
|
216
207
|
try {
|
|
217
|
-
validateQuoteResponse(quoteResponse)
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
208
|
+
if (validateQuoteResponse(quoteResponse)) {
|
|
209
|
+
// eslint-disable-next-line promise/catch-or-return, @typescript-eslint/no-floating-promises
|
|
210
|
+
serverEventHandlers.onValidQuoteReceived(quoteResponse).then((v) => {
|
|
211
|
+
return v;
|
|
212
|
+
});
|
|
213
|
+
}
|
|
222
214
|
}
|
|
223
215
|
catch (error) {
|
|
224
216
|
if (error instanceof StructError) {
|
|
@@ -244,23 +236,21 @@ export async function fetchBridgeQuoteStream(fetchFn, request, signal, clientId,
|
|
|
244
236
|
}
|
|
245
237
|
};
|
|
246
238
|
const urlStream = `${bridgeApiBaseUrl}/getQuoteStream?${queryParams}`;
|
|
247
|
-
await
|
|
239
|
+
await fetchServerEvents(urlStream, {
|
|
248
240
|
headers: {
|
|
249
241
|
...getClientHeaders(clientId, clientVersion),
|
|
250
242
|
'Content-Type': 'text/event-stream',
|
|
251
243
|
},
|
|
252
244
|
signal,
|
|
253
|
-
|
|
254
|
-
|
|
245
|
+
onMessage,
|
|
246
|
+
onError: (e) => {
|
|
255
247
|
// Rethrow error to prevent silent fetch failures
|
|
256
|
-
throw
|
|
248
|
+
throw e;
|
|
257
249
|
},
|
|
258
|
-
|
|
250
|
+
onClose: () => {
|
|
259
251
|
serverEventHandlers.onClose();
|
|
260
252
|
},
|
|
261
|
-
|
|
262
|
-
openWhenHidden: false,
|
|
263
|
-
fetch: fetchFn,
|
|
253
|
+
fetchFn,
|
|
264
254
|
});
|
|
265
255
|
}
|
|
266
256
|
//# sourceMappingURL=fetch.mjs.map
|