@metamask/bridge-controller 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/LICENSE +20 -0
  3. package/README.md +15 -0
  4. package/dist/bridge-controller.cjs +249 -0
  5. package/dist/bridge-controller.cjs.map +1 -0
  6. package/dist/bridge-controller.d.cts +56 -0
  7. package/dist/bridge-controller.d.cts.map +1 -0
  8. package/dist/bridge-controller.d.mts +56 -0
  9. package/dist/bridge-controller.d.mts.map +1 -0
  10. package/dist/bridge-controller.mjs +245 -0
  11. package/dist/bridge-controller.mjs.map +1 -0
  12. package/dist/constants/bridge.cjs +60 -0
  13. package/dist/constants/bridge.cjs.map +1 -0
  14. package/dist/constants/bridge.d.cts +23 -0
  15. package/dist/constants/bridge.d.cts.map +1 -0
  16. package/dist/constants/bridge.d.mts +23 -0
  17. package/dist/constants/bridge.d.mts.map +1 -0
  18. package/dist/constants/bridge.mjs +57 -0
  19. package/dist/constants/bridge.mjs.map +1 -0
  20. package/dist/constants/chains.cjs +168 -0
  21. package/dist/constants/chains.cjs.map +1 -0
  22. package/dist/constants/chains.d.cts +156 -0
  23. package/dist/constants/chains.d.cts.map +1 -0
  24. package/dist/constants/chains.d.mts +156 -0
  25. package/dist/constants/chains.d.mts.map +1 -0
  26. package/dist/constants/chains.mjs +165 -0
  27. package/dist/constants/chains.mjs.map +1 -0
  28. package/dist/constants/swaps.cjs +5 -0
  29. package/dist/constants/swaps.cjs.map +1 -0
  30. package/dist/constants/swaps.d.cts +2 -0
  31. package/dist/constants/swaps.d.cts.map +1 -0
  32. package/dist/constants/swaps.d.mts +2 -0
  33. package/dist/constants/swaps.d.mts.map +1 -0
  34. package/dist/constants/swaps.mjs +2 -0
  35. package/dist/constants/swaps.mjs.map +1 -0
  36. package/dist/constants/tokens.cjs +109 -0
  37. package/dist/constants/tokens.cjs.map +1 -0
  38. package/dist/constants/tokens.d.cts +73 -0
  39. package/dist/constants/tokens.d.cts.map +1 -0
  40. package/dist/constants/tokens.d.mts +73 -0
  41. package/dist/constants/tokens.d.mts.map +1 -0
  42. package/dist/constants/tokens.mjs +106 -0
  43. package/dist/constants/tokens.mjs.map +1 -0
  44. package/dist/index.cjs +26 -0
  45. package/dist/index.cjs.map +1 -0
  46. package/dist/index.d.cts +9 -0
  47. package/dist/index.d.cts.map +1 -0
  48. package/dist/index.d.mts +9 -0
  49. package/dist/index.d.mts.map +1 -0
  50. package/dist/index.mjs +6 -0
  51. package/dist/index.mjs.map +1 -0
  52. package/dist/types.cjs +77 -0
  53. package/dist/types.cjs.map +1 -0
  54. package/dist/types.d.cts +232 -0
  55. package/dist/types.d.cts.map +1 -0
  56. package/dist/types.d.mts +232 -0
  57. package/dist/types.d.mts.map +1 -0
  58. package/dist/types.mjs +74 -0
  59. package/dist/types.mjs.map +1 -0
  60. package/dist/utils/balance.cjs +31 -0
  61. package/dist/utils/balance.cjs.map +1 -0
  62. package/dist/utils/balance.d.cts +6 -0
  63. package/dist/utils/balance.d.cts.map +1 -0
  64. package/dist/utils/balance.d.mts +6 -0
  65. package/dist/utils/balance.d.mts.map +1 -0
  66. package/dist/utils/balance.mjs +25 -0
  67. package/dist/utils/balance.mjs.map +1 -0
  68. package/dist/utils/bridge.cjs +81 -0
  69. package/dist/utils/bridge.cjs.map +1 -0
  70. package/dist/utils/bridge.d.cts +31 -0
  71. package/dist/utils/bridge.d.cts.map +1 -0
  72. package/dist/utils/bridge.d.mts +31 -0
  73. package/dist/utils/bridge.d.mts.map +1 -0
  74. package/dist/utils/bridge.mjs +71 -0
  75. package/dist/utils/bridge.mjs.map +1 -0
  76. package/dist/utils/fetch.cjs +122 -0
  77. package/dist/utils/fetch.cjs.map +1 -0
  78. package/dist/utils/fetch.d.cts +33 -0
  79. package/dist/utils/fetch.d.cts.map +1 -0
  80. package/dist/utils/fetch.d.mts +33 -0
  81. package/dist/utils/fetch.d.mts.map +1 -0
  82. package/dist/utils/fetch.mjs +115 -0
  83. package/dist/utils/fetch.mjs.map +1 -0
  84. package/dist/utils/quote.cjs +27 -0
  85. package/dist/utils/quote.cjs.map +1 -0
  86. package/dist/utils/quote.d.cts +3 -0
  87. package/dist/utils/quote.d.cts.map +1 -0
  88. package/dist/utils/quote.d.mts +3 -0
  89. package/dist/utils/quote.d.mts.map +1 -0
  90. package/dist/utils/quote.mjs +23 -0
  91. package/dist/utils/quote.mjs.map +1 -0
  92. package/dist/utils/validators.cjs +112 -0
  93. package/dist/utils/validators.cjs.map +1 -0
  94. package/dist/utils/validators.d.cts +30 -0
  95. package/dist/utils/validators.d.cts.map +1 -0
  96. package/dist/utils/validators.d.mts +30 -0
  97. package/dist/utils/validators.d.mts.map +1 -0
  98. package/dist/utils/validators.mjs +104 -0
  99. package/dist/utils/validators.mjs.map +1 -0
  100. package/package.json +86 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.mts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0CAA0C,EAAE,sCAAsC;AAChG,OAAO,KAAK,EACV,0BAA0B,EAC1B,mBAAmB,EACpB,kCAAkC;AACnC,OAAO,KAAK,EACV,mDAAmD,EACnD,+BAA+B,EAC/B,2CAA2C,EAC5C,qCAAqC;AACtC,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAC3C,OAAO,KAAK,EAAE,SAAS,EAAE,qBAAqB;AAE9C,OAAO,KAAK,EAAE,gBAAgB,EAAE,gCAA4B;AAC5D,OAAO,KAAK,EAAE,sBAAsB,EAAE,+BAA2B;AAEjE,MAAM,MAAM,aAAa,GAAG,CAC1B,KAAK,EAAE,WAAW,GAAG,GAAG,EACxB,IAAI,CAAC,EAAE,WAAW,KAEf,OAAO,CAAC,GAAG,CAAC,CAAC;AAElB;;;GAGG;AACH,oBAAY,SAAS;IACnB,4DAA4D;IAC5D,MAAM,WAAW;IACjB,qBAAqB;IACrB,KAAK,UAAU;IACf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AAC,MAAM,CAAC,CACtB,CAAC"}
package/dist/types.mjs ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The types of assets that a user can send
3
+ *
4
+ */
5
+ export var AssetType;
6
+ (function (AssetType) {
7
+ /** The native asset for the current network, such as ETH */
8
+ AssetType["native"] = "NATIVE";
9
+ /** An ERC20 token */
10
+ AssetType["token"] = "TOKEN";
11
+ /** An ERC721 or ERC1155 token. */
12
+ AssetType["NFT"] = "NFT";
13
+ /**
14
+ * A transaction interacting with a contract that isn't a token method
15
+ * interaction will be marked as dealing with an unknown asset type.
16
+ */
17
+ AssetType["unknown"] = "UNKNOWN";
18
+ })(AssetType || (AssetType = {}));
19
+ // Sort order set by the user
20
+ export var SortOrder;
21
+ (function (SortOrder) {
22
+ SortOrder["COST_ASC"] = "cost_ascending";
23
+ SortOrder["ETA_ASC"] = "time_descending";
24
+ })(SortOrder || (SortOrder = {}));
25
+ // Types copied from Metabridge API
26
+ export var BridgeFlag;
27
+ (function (BridgeFlag) {
28
+ BridgeFlag["EXTENSION_CONFIG"] = "extension-config";
29
+ })(BridgeFlag || (BridgeFlag = {}));
30
+ export var ActionTypes;
31
+ (function (ActionTypes) {
32
+ ActionTypes["BRIDGE"] = "bridge";
33
+ ActionTypes["SWAP"] = "swap";
34
+ ActionTypes["REFUEL"] = "refuel";
35
+ })(ActionTypes || (ActionTypes = {}));
36
+ export var ChainId;
37
+ (function (ChainId) {
38
+ ChainId[ChainId["ETH"] = 1] = "ETH";
39
+ ChainId[ChainId["OPTIMISM"] = 10] = "OPTIMISM";
40
+ ChainId[ChainId["BSC"] = 56] = "BSC";
41
+ ChainId[ChainId["POLYGON"] = 137] = "POLYGON";
42
+ ChainId[ChainId["ZKSYNC"] = 324] = "ZKSYNC";
43
+ ChainId[ChainId["BASE"] = 8453] = "BASE";
44
+ ChainId[ChainId["ARBITRUM"] = 42161] = "ARBITRUM";
45
+ ChainId[ChainId["AVALANCHE"] = 43114] = "AVALANCHE";
46
+ ChainId[ChainId["LINEA"] = 59144] = "LINEA";
47
+ })(ChainId || (ChainId = {}));
48
+ export var FeeType;
49
+ (function (FeeType) {
50
+ FeeType["METABRIDGE"] = "metabridge";
51
+ FeeType["REFUEL"] = "refuel";
52
+ })(FeeType || (FeeType = {}));
53
+ export var BridgeFeatureFlagsKey;
54
+ (function (BridgeFeatureFlagsKey) {
55
+ BridgeFeatureFlagsKey["EXTENSION_CONFIG"] = "extensionConfig";
56
+ })(BridgeFeatureFlagsKey || (BridgeFeatureFlagsKey = {}));
57
+ export var RequestStatus;
58
+ (function (RequestStatus) {
59
+ RequestStatus[RequestStatus["LOADING"] = 0] = "LOADING";
60
+ RequestStatus[RequestStatus["FETCHED"] = 1] = "FETCHED";
61
+ RequestStatus[RequestStatus["ERROR"] = 2] = "ERROR";
62
+ })(RequestStatus || (RequestStatus = {}));
63
+ export var BridgeUserAction;
64
+ (function (BridgeUserAction) {
65
+ BridgeUserAction["SELECT_DEST_NETWORK"] = "selectDestNetwork";
66
+ BridgeUserAction["UPDATE_QUOTE_PARAMS"] = "updateBridgeQuoteRequestParams";
67
+ })(BridgeUserAction || (BridgeUserAction = {}));
68
+ export var BridgeBackgroundAction;
69
+ (function (BridgeBackgroundAction) {
70
+ BridgeBackgroundAction["SET_FEATURE_FLAGS"] = "setBridgeFeatureFlags";
71
+ BridgeBackgroundAction["RESET_STATE"] = "resetState";
72
+ BridgeBackgroundAction["GET_BRIDGE_ERC20_ALLOWANCE"] = "getBridgeERC20Allowance";
73
+ })(BridgeBackgroundAction || (BridgeBackgroundAction = {}));
74
+ //# sourceMappingURL=types.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.mjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAsBA;;;GAGG;AACH,MAAM,CAAN,IAAY,SAYX;AAZD,WAAY,SAAS;IACnB,4DAA4D;IAC5D,8BAAiB,CAAA;IACjB,qBAAqB;IACrB,4BAAe,CAAA;IACf,kCAAkC;IAClC,wBAAW,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AyC,CAAA;IACzC,0EAAsD,CAAA;AACxD,CAAC,EAHW,gBAAgB,KAAhB,gBAAgB,QAG3B;AACD,MAAM,CAAN,IAAY,sBAIX;AAJD,WAAY,sBAAsB;IAChC,qEAA2C,CAAA;IAC3C,oDAA0B,CAAA;IAC1B,gFAAsD,CAAA;AACxD,CAAC,EAJW,sBAAsB,KAAtB,sBAAsB,QAIjC","sourcesContent":["import type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';\nimport type {\n ControllerStateChangeEvent,\n RestrictedMessenger,\n} from '@metamask/base-controller';\nimport type {\n NetworkControllerFindNetworkClientIdByChainIdAction,\n NetworkControllerGetStateAction,\n NetworkControllerGetNetworkClientByIdAction,\n} from '@metamask/network-controller';\nimport type { Hex } from '@metamask/utils';\nimport type { BigNumber } from 'bignumber.js';\n\nimport type { BridgeController } from './bridge-controller';\nimport type { BRIDGE_CONTROLLER_NAME } from './constants/bridge';\n\nexport type FetchFunction = (\n input: RequestInfo | URL,\n init?: RequestInit,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n) => Promise<any>;\n\n/**\n * The types of assets that a user can send\n *\n */\nexport enum AssetType {\n /** The native asset for the current network, such as ETH */\n native = 'NATIVE',\n /** An ERC20 token */\n token = 'TOKEN',\n /** An ERC721 or ERC1155 token. */\n NFT = 'NFT',\n /**\n * A transaction interacting with a contract that isn't a token method\n * interaction will be marked as dealing with an unknown asset type.\n */\n unknown = 'UNKNOWN',\n}\n\nexport type ChainConfiguration = {\n isActiveSrc: boolean;\n isActiveDest: boolean;\n};\n\nexport type L1GasFees = {\n l1GasFeesInHexWei?: string; // l1 fees for approval and trade in hex wei, appended by controller\n};\n// Values derived from the quote response\n// valueInCurrency values are calculated based on the user's selected currency\n\nexport type QuoteMetadata = {\n gasFee: { amount: BigNumber; valueInCurrency: BigNumber | null };\n totalNetworkFee: { amount: BigNumber; valueInCurrency: BigNumber | null }; // estimatedGasFees + relayerFees\n totalMaxNetworkFee: { amount: BigNumber; valueInCurrency: BigNumber | null }; // maxGasFees + relayerFees\n toTokenAmount: { amount: BigNumber; valueInCurrency: BigNumber | null };\n adjustedReturn: { valueInCurrency: BigNumber | null }; // destTokenAmount - totalNetworkFee\n sentAmount: { amount: BigNumber; valueInCurrency: BigNumber | null }; // srcTokenAmount + metabridgeFee\n swapRate: BigNumber; // destTokenAmount / sentAmount\n cost: { valueInCurrency: BigNumber | null }; // sentAmount - adjustedReturn\n};\n// Sort order set by the user\n\nexport enum SortOrder {\n COST_ASC = 'cost_ascending',\n ETA_ASC = 'time_descending',\n}\n\nexport type BridgeToken = {\n type: AssetType.native | AssetType.token;\n address: string;\n symbol: string;\n image: string;\n decimals: number;\n chainId: Hex;\n balance: string; // raw balance\n string: string | undefined; // normalized balance as a stringified number\n tokenFiatAmount?: number | null;\n} | null;\n// Types copied from Metabridge API\n\nexport enum BridgeFlag {\n EXTENSION_CONFIG = 'extension-config',\n}\ntype DecimalChainId = string;\nexport type GasMultiplierByChainId = Record<DecimalChainId, number>;\n\nexport type FeatureFlagResponse = {\n [BridgeFlag.EXTENSION_CONFIG]: {\n refreshRate: number;\n maxRefreshCount: number;\n support: boolean;\n chains: Record<number, ChainConfiguration>;\n };\n};\n\nexport type BridgeAsset = {\n chainId: ChainId;\n address: string;\n symbol: string;\n name: string;\n decimals: number;\n icon?: string;\n};\n\nexport type QuoteRequest = {\n walletAddress: string;\n destWalletAddress?: string;\n srcChainId: ChainId;\n destChainId: ChainId;\n srcTokenAddress: string;\n destTokenAddress: string;\n /**\n * This is the amount sent, in atomic amount\n */\n srcTokenAmount: string;\n slippage: number;\n aggIds?: string[];\n bridgeIds?: string[];\n insufficientBal?: boolean;\n resetApproval?: boolean;\n refuel?: boolean;\n};\n\nexport type Protocol = {\n name: string;\n displayName?: string;\n icon?: string;\n};\n\nexport enum ActionTypes {\n BRIDGE = 'bridge',\n SWAP = 'swap',\n REFUEL = 'refuel',\n}\n\nexport type Step = {\n action: ActionTypes;\n srcChainId: ChainId;\n destChainId?: ChainId;\n srcAsset: BridgeAsset;\n destAsset: BridgeAsset;\n srcAmount: string;\n destAmount: string;\n protocol: Protocol;\n};\n\nexport type RefuelData = Step;\n\nexport type Quote = {\n requestId: string;\n srcChainId: ChainId;\n srcAsset: BridgeAsset;\n // Some tokens have a fee of 0, so sometimes it's equal to amount sent\n srcTokenAmount: string; // Atomic amount, the amount sent - fees\n destChainId: ChainId;\n destAsset: BridgeAsset;\n destTokenAmount: string; // Atomic amount, the amount received\n feeData: Record<FeeType.METABRIDGE, FeeData> &\n Partial<Record<FeeType, FeeData>>;\n bridgeId: string;\n bridges: string[];\n steps: Step[];\n refuel?: RefuelData;\n};\n\nexport type QuoteResponse = {\n quote: Quote;\n approval: TxData | null;\n trade: TxData;\n estimatedProcessingTimeInSeconds: number;\n};\n\nexport enum ChainId {\n ETH = 1,\n OPTIMISM = 10,\n BSC = 56,\n POLYGON = 137,\n ZKSYNC = 324,\n BASE = 8453,\n ARBITRUM = 42161,\n AVALANCHE = 43114,\n LINEA = 59144,\n}\n\nexport enum FeeType {\n METABRIDGE = 'metabridge',\n REFUEL = 'refuel',\n}\nexport type FeeData = {\n amount: string;\n asset: BridgeAsset;\n};\nexport type TxData = {\n chainId: ChainId;\n to: string;\n from: string;\n value: string;\n data: string;\n gasLimit: number | null;\n};\nexport enum BridgeFeatureFlagsKey {\n EXTENSION_CONFIG = 'extensionConfig',\n}\n\nexport type BridgeFeatureFlags = {\n [BridgeFeatureFlagsKey.EXTENSION_CONFIG]: {\n refreshRate: number;\n maxRefreshCount: number;\n support: boolean;\n chains: Record<Hex, ChainConfiguration>;\n };\n};\nexport enum RequestStatus {\n LOADING,\n FETCHED,\n ERROR,\n}\nexport enum BridgeUserAction {\n SELECT_DEST_NETWORK = 'selectDestNetwork',\n UPDATE_QUOTE_PARAMS = 'updateBridgeQuoteRequestParams',\n}\nexport enum BridgeBackgroundAction {\n SET_FEATURE_FLAGS = 'setBridgeFeatureFlags',\n RESET_STATE = 'resetState',\n GET_BRIDGE_ERC20_ALLOWANCE = 'getBridgeERC20Allowance',\n}\nexport type BridgeControllerState = {\n bridgeFeatureFlags: BridgeFeatureFlags;\n quoteRequest: Partial<QuoteRequest>;\n quotes: (QuoteResponse & L1GasFees)[];\n quotesInitialLoadTime?: number;\n quotesLastFetched?: number;\n quotesLoadingStatus?: RequestStatus;\n quoteFetchError?: string;\n quotesRefreshCount: number;\n};\n\nexport type BridgeControllerAction<\n FunctionName extends keyof BridgeController,\n> = {\n type: `${typeof BRIDGE_CONTROLLER_NAME}:${FunctionName}`;\n handler: BridgeController[FunctionName];\n};\n\n// Maps to BridgeController function names\nexport type BridgeControllerActions =\n | BridgeControllerAction<BridgeBackgroundAction.SET_FEATURE_FLAGS>\n | BridgeControllerAction<BridgeBackgroundAction.RESET_STATE>\n | BridgeControllerAction<BridgeBackgroundAction.GET_BRIDGE_ERC20_ALLOWANCE>\n | BridgeControllerAction<BridgeUserAction.UPDATE_QUOTE_PARAMS>;\n\nexport type BridgeControllerEvents = ControllerStateChangeEvent<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerState\n>;\n\nexport type AllowedActions =\n | AccountsControllerGetSelectedAccountAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction;\nexport type AllowedEvents = never;\n\n/**\n * The messenger for the BridgeController.\n */\nexport type BridgeControllerMessenger = RestrictedMessenger<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerActions | AllowedActions,\n BridgeControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n"]}
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hasSufficientBalance = exports.calcLatestSrcBalance = exports.fetchTokenBalance = void 0;
4
+ const metamask_eth_abis_1 = require("@metamask/metamask-eth-abis");
5
+ const ethers_1 = require("ethers");
6
+ const fetchTokenBalance = async (address, userAddress, provider) => {
7
+ const ethersProvider = new ethers_1.BrowserProvider(provider);
8
+ const tokenContract = new ethers_1.Contract(address, metamask_eth_abis_1.abiERC20, ethersProvider);
9
+ const tokenBalancePromise = typeof tokenContract?.balanceOf === 'function'
10
+ ? tokenContract.balanceOf(userAddress)
11
+ : Promise.resolve(undefined);
12
+ return await tokenBalancePromise;
13
+ };
14
+ exports.fetchTokenBalance = fetchTokenBalance;
15
+ const calcLatestSrcBalance = async (provider, selectedAddress, tokenAddress, chainId) => {
16
+ if (tokenAddress && chainId) {
17
+ if (tokenAddress === ethers_1.ZeroAddress) {
18
+ const ethersProvider = new ethers_1.BrowserProvider(provider);
19
+ return await ethersProvider.getBalance((0, ethers_1.getAddress)(selectedAddress));
20
+ }
21
+ return await (0, exports.fetchTokenBalance)(tokenAddress, selectedAddress, provider);
22
+ }
23
+ return undefined;
24
+ };
25
+ exports.calcLatestSrcBalance = calcLatestSrcBalance;
26
+ const hasSufficientBalance = async (provider, selectedAddress, tokenAddress, fromTokenAmount, chainId) => {
27
+ const srcTokenBalance = await (0, exports.calcLatestSrcBalance)(provider, selectedAddress, tokenAddress, chainId);
28
+ return srcTokenBalance ? srcTokenBalance >= BigInt(fromTokenAmount) : false;
29
+ };
30
+ exports.hasSufficientBalance = hasSufficientBalance;
31
+ //# sourceMappingURL=balance.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"balance.cjs","sourceRoot":"","sources":["../../src/utils/balance.ts"],"names":[],"mappings":";;;AAAA,mEAAuD;AAGvD,mCAA4E;AAErE,MAAM,iBAAiB,GAAG,KAAK,EACpC,OAAe,EACf,WAAmB,EACnB,QAAkB,EACW,EAAE;IAC/B,MAAM,cAAc,GAAG,IAAI,wBAAe,CAAC,QAAQ,CAAC,CAAC;IACrD,MAAM,aAAa,GAAG,IAAI,iBAAQ,CAAC,OAAO,EAAE,4BAAQ,EAAE,cAAc,CAAC,CAAC;IACtE,MAAM,mBAAmB,GACvB,OAAO,aAAa,EAAE,SAAS,KAAK,UAAU;QAC5C,CAAC,CAAC,aAAa,CAAC,SAAS,CAAC,WAAW,CAAC;QACtC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACjC,OAAO,MAAM,mBAAmB,CAAC;AACnC,CAAC,CAAC;AAZW,QAAA,iBAAiB,qBAY5B;AAEK,MAAM,oBAAoB,GAAG,KAAK,EACvC,QAAkB,EAClB,eAAuB,EACvB,YAAoB,EACpB,OAAY,EACiB,EAAE;IAC/B,IAAI,YAAY,IAAI,OAAO,EAAE;QAC3B,IAAI,YAAY,KAAK,oBAAW,EAAE;YAChC,MAAM,cAAc,GAAG,IAAI,wBAAe,CAAC,QAAQ,CAAC,CAAC;YACrD,OAAO,MAAM,cAAc,CAAC,UAAU,CAAC,IAAA,mBAAU,EAAC,eAAe,CAAC,CAAC,CAAC;SACrE;QACD,OAAO,MAAM,IAAA,yBAAiB,EAAC,YAAY,EAAE,eAAe,EAAE,QAAQ,CAAC,CAAC;KACzE;IACD,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC;AAdW,QAAA,oBAAoB,wBAc/B;AAEK,MAAM,oBAAoB,GAAG,KAAK,EACvC,QAAkB,EAClB,eAAuB,EACvB,YAAoB,EACpB,eAAuB,EACvB,OAAY,EACZ,EAAE;IACF,MAAM,eAAe,GAAG,MAAM,IAAA,4BAAoB,EAChD,QAAQ,EACR,eAAe,EACf,YAAY,EACZ,OAAO,CACR,CAAC;IAEF,OAAO,eAAe,CAAC,CAAC,CAAC,eAAe,IAAI,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;AAC9E,CAAC,CAAC;AAfW,QAAA,oBAAoB,wBAe/B","sourcesContent":["import { abiERC20 } from '@metamask/metamask-eth-abis';\nimport type { Provider } from '@metamask/network-controller';\nimport type { Hex } from '@metamask/utils';\nimport { BrowserProvider, Contract, getAddress, ZeroAddress } from 'ethers';\n\nexport const fetchTokenBalance = async (\n address: string,\n userAddress: string,\n provider: Provider,\n): Promise<bigint | undefined> => {\n const ethersProvider = new BrowserProvider(provider);\n const tokenContract = new Contract(address, abiERC20, ethersProvider);\n const tokenBalancePromise =\n typeof tokenContract?.balanceOf === 'function'\n ? tokenContract.balanceOf(userAddress)\n : Promise.resolve(undefined);\n return await tokenBalancePromise;\n};\n\nexport const calcLatestSrcBalance = async (\n provider: Provider,\n selectedAddress: string,\n tokenAddress: string,\n chainId: Hex,\n): Promise<bigint | undefined> => {\n if (tokenAddress && chainId) {\n if (tokenAddress === ZeroAddress) {\n const ethersProvider = new BrowserProvider(provider);\n return await ethersProvider.getBalance(getAddress(selectedAddress));\n }\n return await fetchTokenBalance(tokenAddress, selectedAddress, provider);\n }\n return undefined;\n};\n\nexport const hasSufficientBalance = async (\n provider: Provider,\n selectedAddress: string,\n tokenAddress: string,\n fromTokenAmount: string,\n chainId: Hex,\n) => {\n const srcTokenBalance = await calcLatestSrcBalance(\n provider,\n selectedAddress,\n tokenAddress,\n chainId,\n );\n\n return srcTokenBalance ? srcTokenBalance >= BigInt(fromTokenAmount) : false;\n};\n"]}
@@ -0,0 +1,6 @@
1
+ import type { Provider } from "@metamask/network-controller";
2
+ import type { Hex } from "@metamask/utils";
3
+ export declare const fetchTokenBalance: (address: string, userAddress: string, provider: Provider) => Promise<bigint | undefined>;
4
+ export declare const calcLatestSrcBalance: (provider: Provider, selectedAddress: string, tokenAddress: string, chainId: Hex) => Promise<bigint | undefined>;
5
+ export declare const hasSufficientBalance: (provider: Provider, selectedAddress: string, tokenAddress: string, fromTokenAmount: string, chainId: Hex) => Promise<boolean>;
6
+ //# sourceMappingURL=balance.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"balance.d.cts","sourceRoot":"","sources":["../../src/utils/balance.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,qCAAqC;AAC7D,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAG3C,eAAO,MAAM,iBAAiB,YACnB,MAAM,eACF,MAAM,YACT,QAAQ,KACjB,QAAQ,MAAM,GAAG,SAAS,CAQ5B,CAAC;AAEF,eAAO,MAAM,oBAAoB,aACrB,QAAQ,mBACD,MAAM,gBACT,MAAM,WACX,GAAG,KACX,QAAQ,MAAM,GAAG,SAAS,CAS5B,CAAC;AAEF,eAAO,MAAM,oBAAoB,aACrB,QAAQ,mBACD,MAAM,gBACT,MAAM,mBACH,MAAM,WACd,GAAG,qBAUb,CAAC"}
@@ -0,0 +1,6 @@
1
+ import type { Provider } from "@metamask/network-controller";
2
+ import type { Hex } from "@metamask/utils";
3
+ export declare const fetchTokenBalance: (address: string, userAddress: string, provider: Provider) => Promise<bigint | undefined>;
4
+ export declare const calcLatestSrcBalance: (provider: Provider, selectedAddress: string, tokenAddress: string, chainId: Hex) => Promise<bigint | undefined>;
5
+ export declare const hasSufficientBalance: (provider: Provider, selectedAddress: string, tokenAddress: string, fromTokenAmount: string, chainId: Hex) => Promise<boolean>;
6
+ //# sourceMappingURL=balance.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"balance.d.mts","sourceRoot":"","sources":["../../src/utils/balance.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,qCAAqC;AAC7D,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAG3C,eAAO,MAAM,iBAAiB,YACnB,MAAM,eACF,MAAM,YACT,QAAQ,KACjB,QAAQ,MAAM,GAAG,SAAS,CAQ5B,CAAC;AAEF,eAAO,MAAM,oBAAoB,aACrB,QAAQ,mBACD,MAAM,gBACT,MAAM,WACX,GAAG,KACX,QAAQ,MAAM,GAAG,SAAS,CAS5B,CAAC;AAEF,eAAO,MAAM,oBAAoB,aACrB,QAAQ,mBACD,MAAM,gBACT,MAAM,mBACH,MAAM,WACd,GAAG,qBAUb,CAAC"}
@@ -0,0 +1,25 @@
1
+ import { abiERC20 } from "@metamask/metamask-eth-abis";
2
+ import { BrowserProvider, Contract, getAddress, ZeroAddress } from "ethers";
3
+ export const fetchTokenBalance = async (address, userAddress, provider) => {
4
+ const ethersProvider = new BrowserProvider(provider);
5
+ const tokenContract = new Contract(address, abiERC20, ethersProvider);
6
+ const tokenBalancePromise = typeof tokenContract?.balanceOf === 'function'
7
+ ? tokenContract.balanceOf(userAddress)
8
+ : Promise.resolve(undefined);
9
+ return await tokenBalancePromise;
10
+ };
11
+ export const calcLatestSrcBalance = async (provider, selectedAddress, tokenAddress, chainId) => {
12
+ if (tokenAddress && chainId) {
13
+ if (tokenAddress === ZeroAddress) {
14
+ const ethersProvider = new BrowserProvider(provider);
15
+ return await ethersProvider.getBalance(getAddress(selectedAddress));
16
+ }
17
+ return await fetchTokenBalance(tokenAddress, selectedAddress, provider);
18
+ }
19
+ return undefined;
20
+ };
21
+ export const hasSufficientBalance = async (provider, selectedAddress, tokenAddress, fromTokenAmount, chainId) => {
22
+ const srcTokenBalance = await calcLatestSrcBalance(provider, selectedAddress, tokenAddress, chainId);
23
+ return srcTokenBalance ? srcTokenBalance >= BigInt(fromTokenAmount) : false;
24
+ };
25
+ //# sourceMappingURL=balance.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"balance.mjs","sourceRoot":"","sources":["../../src/utils/balance.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,oCAAoC;AAGvD,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,UAAU,EAAE,WAAW,EAAE,eAAe;AAE5E,MAAM,CAAC,MAAM,iBAAiB,GAAG,KAAK,EACpC,OAAe,EACf,WAAmB,EACnB,QAAkB,EACW,EAAE;IAC/B,MAAM,cAAc,GAAG,IAAI,eAAe,CAAC,QAAQ,CAAC,CAAC;IACrD,MAAM,aAAa,GAAG,IAAI,QAAQ,CAAC,OAAO,EAAE,QAAQ,EAAE,cAAc,CAAC,CAAC;IACtE,MAAM,mBAAmB,GACvB,OAAO,aAAa,EAAE,SAAS,KAAK,UAAU;QAC5C,CAAC,CAAC,aAAa,CAAC,SAAS,CAAC,WAAW,CAAC;QACtC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACjC,OAAO,MAAM,mBAAmB,CAAC;AACnC,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,oBAAoB,GAAG,KAAK,EACvC,QAAkB,EAClB,eAAuB,EACvB,YAAoB,EACpB,OAAY,EACiB,EAAE;IAC/B,IAAI,YAAY,IAAI,OAAO,EAAE;QAC3B,IAAI,YAAY,KAAK,WAAW,EAAE;YAChC,MAAM,cAAc,GAAG,IAAI,eAAe,CAAC,QAAQ,CAAC,CAAC;YACrD,OAAO,MAAM,cAAc,CAAC,UAAU,CAAC,UAAU,CAAC,eAAe,CAAC,CAAC,CAAC;SACrE;QACD,OAAO,MAAM,iBAAiB,CAAC,YAAY,EAAE,eAAe,EAAE,QAAQ,CAAC,CAAC;KACzE;IACD,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,oBAAoB,GAAG,KAAK,EACvC,QAAkB,EAClB,eAAuB,EACvB,YAAoB,EACpB,eAAuB,EACvB,OAAY,EACZ,EAAE;IACF,MAAM,eAAe,GAAG,MAAM,oBAAoB,CAChD,QAAQ,EACR,eAAe,EACf,YAAY,EACZ,OAAO,CACR,CAAC;IAEF,OAAO,eAAe,CAAC,CAAC,CAAC,eAAe,IAAI,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;AAC9E,CAAC,CAAC","sourcesContent":["import { abiERC20 } from '@metamask/metamask-eth-abis';\nimport type { Provider } from '@metamask/network-controller';\nimport type { Hex } from '@metamask/utils';\nimport { BrowserProvider, Contract, getAddress, ZeroAddress } from 'ethers';\n\nexport const fetchTokenBalance = async (\n address: string,\n userAddress: string,\n provider: Provider,\n): Promise<bigint | undefined> => {\n const ethersProvider = new BrowserProvider(provider);\n const tokenContract = new Contract(address, abiERC20, ethersProvider);\n const tokenBalancePromise =\n typeof tokenContract?.balanceOf === 'function'\n ? tokenContract.balanceOf(userAddress)\n : Promise.resolve(undefined);\n return await tokenBalancePromise;\n};\n\nexport const calcLatestSrcBalance = async (\n provider: Provider,\n selectedAddress: string,\n tokenAddress: string,\n chainId: Hex,\n): Promise<bigint | undefined> => {\n if (tokenAddress && chainId) {\n if (tokenAddress === ZeroAddress) {\n const ethersProvider = new BrowserProvider(provider);\n return await ethersProvider.getBalance(getAddress(selectedAddress));\n }\n return await fetchTokenBalance(tokenAddress, selectedAddress, provider);\n }\n return undefined;\n};\n\nexport const hasSufficientBalance = async (\n provider: Provider,\n selectedAddress: string,\n tokenAddress: string,\n fromTokenAmount: string,\n chainId: Hex,\n) => {\n const srcTokenBalance = await calcLatestSrcBalance(\n provider,\n selectedAddress,\n tokenAddress,\n chainId,\n );\n\n return srcTokenBalance ? srcTokenBalance >= BigInt(fromTokenAmount) : false;\n};\n"]}
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isSwapsDefaultTokenSymbol = exports.isSwapsDefaultTokenAddress = exports.sumHexes = exports.isEthUsdt = exports.getEthUsdtResetData = exports.getBridgeApiBaseUrl = exports.getDefaultBridgeControllerState = void 0;
4
+ const metamask_eth_abis_1 = require("@metamask/metamask-eth-abis");
5
+ const ethers_1 = require("ethers");
6
+ const bridge_1 = require("../constants/bridge.cjs");
7
+ const chains_1 = require("../constants/chains.cjs");
8
+ const tokens_1 = require("../constants/tokens.cjs");
9
+ const getDefaultBridgeControllerState = () => {
10
+ return bridge_1.DEFAULT_BRIDGE_CONTROLLER_STATE;
11
+ };
12
+ exports.getDefaultBridgeControllerState = getDefaultBridgeControllerState;
13
+ const getBridgeApiBaseUrl = () => {
14
+ if (process.env.BRIDGE_CUSTOM_API_BASE_URL) {
15
+ return process.env.BRIDGE_CUSTOM_API_BASE_URL;
16
+ }
17
+ if (process.env.BRIDGE_USE_DEV_APIS) {
18
+ return bridge_1.BRIDGE_DEV_API_BASE_URL;
19
+ }
20
+ return bridge_1.BRIDGE_PROD_API_BASE_URL;
21
+ };
22
+ exports.getBridgeApiBaseUrl = getBridgeApiBaseUrl;
23
+ /**
24
+ * A function to return the txParam data for setting allowance to 0 for USDT on Ethereum
25
+ *
26
+ * @returns The txParam data that will reset allowance to 0, combine it with the approval tx params received from Bridge API
27
+ */
28
+ const getEthUsdtResetData = () => {
29
+ const UsdtContractInterface = new ethers_1.Contract(bridge_1.ETH_USDT_ADDRESS, metamask_eth_abis_1.abiERC20)
30
+ .interface;
31
+ const data = UsdtContractInterface.encodeFunctionData('approve', [
32
+ bridge_1.METABRIDGE_ETHEREUM_ADDRESS,
33
+ '0',
34
+ ]);
35
+ return data;
36
+ };
37
+ exports.getEthUsdtResetData = getEthUsdtResetData;
38
+ const isEthUsdt = (chainId, address) => chainId === chains_1.CHAIN_IDS.MAINNET &&
39
+ address.toLowerCase() === bridge_1.ETH_USDT_ADDRESS.toLowerCase();
40
+ exports.isEthUsdt = isEthUsdt;
41
+ const sumHexes = (...hexStrings) => {
42
+ if (hexStrings.length === 0) {
43
+ return '0x0';
44
+ }
45
+ const sum = hexStrings.reduce((acc, hex) => acc + BigInt(hex), BigInt(0));
46
+ return `0x${sum.toString(16)}`;
47
+ };
48
+ exports.sumHexes = sumHexes;
49
+ /**
50
+ * Checks whether the provided address is strictly equal to the address for
51
+ * the default swaps token of the provided chain.
52
+ *
53
+ * @param address - The string to compare to the default token address
54
+ * @param chainId - The hex encoded chain ID of the default swaps token to check
55
+ * @returns Whether the address is the provided chain's default token address
56
+ */
57
+ const isSwapsDefaultTokenAddress = (address, chainId) => {
58
+ if (!address || !chainId) {
59
+ return false;
60
+ }
61
+ return (address ===
62
+ tokens_1.SWAPS_CHAINID_DEFAULT_TOKEN_MAP[chainId]?.address);
63
+ };
64
+ exports.isSwapsDefaultTokenAddress = isSwapsDefaultTokenAddress;
65
+ /**
66
+ * Checks whether the provided symbol is strictly equal to the symbol for
67
+ * the default swaps token of the provided chain.
68
+ *
69
+ * @param symbol - The string to compare to the default token symbol
70
+ * @param chainId - The hex encoded chain ID of the default swaps token to check
71
+ * @returns Whether the symbol is the provided chain's default token symbol
72
+ */
73
+ const isSwapsDefaultTokenSymbol = (symbol, chainId) => {
74
+ if (!symbol || !chainId) {
75
+ return false;
76
+ }
77
+ return (symbol ===
78
+ tokens_1.SWAPS_CHAINID_DEFAULT_TOKEN_MAP[chainId]?.symbol);
79
+ };
80
+ exports.isSwapsDefaultTokenSymbol = isSwapsDefaultTokenSymbol;
81
+ //# sourceMappingURL=bridge.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bridge.cjs","sourceRoot":"","sources":["../../src/utils/bridge.ts"],"names":[],"mappings":";;;AAAA,mEAAuD;AAEvD,mCAAkC;AAElC,oDAM6B;AAC7B,oDAAgD;AAChD,oDAAsE;AAG/D,MAAM,+BAA+B,GAAG,GAA0B,EAAE;IACzE,OAAO,wCAA+B,CAAC;AACzC,CAAC,CAAC;AAFW,QAAA,+BAA+B,mCAE1C;AAEK,MAAM,mBAAmB,GAAG,GAAG,EAAE;IACtC,IAAI,OAAO,CAAC,GAAG,CAAC,0BAA0B,EAAE;QAC1C,OAAO,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC;KAC/C;IAED,IAAI,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE;QACnC,OAAO,gCAAuB,CAAC;KAChC;IAED,OAAO,iCAAwB,CAAC;AAClC,CAAC,CAAC;AAVW,QAAA,mBAAmB,uBAU9B;AACF;;;;GAIG;AAEI,MAAM,mBAAmB,GAAG,GAAG,EAAE;IACtC,MAAM,qBAAqB,GAAG,IAAI,iBAAQ,CAAC,yBAAgB,EAAE,4BAAQ,CAAC;SACnE,SAAS,CAAC;IACb,MAAM,IAAI,GAAG,qBAAqB,CAAC,kBAAkB,CAAC,SAAS,EAAE;QAC/D,oCAA2B;QAC3B,GAAG;KACJ,CAAC,CAAC;IAEH,OAAO,IAAI,CAAC;AACd,CAAC,CAAC;AATW,QAAA,mBAAmB,uBAS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} from '@metamask/utils';\nimport { Contract } from 'ethers';\n\nimport {\n DEFAULT_BRIDGE_CONTROLLER_STATE,\n BRIDGE_DEV_API_BASE_URL,\n BRIDGE_PROD_API_BASE_URL,\n ETH_USDT_ADDRESS,\n METABRIDGE_ETHEREUM_ADDRESS,\n} from '../constants/bridge';\nimport { CHAIN_IDS } from '../constants/chains';\nimport { SWAPS_CHAINID_DEFAULT_TOKEN_MAP } from '../constants/tokens';\nimport type { BridgeControllerState } from '../types';\n\nexport const getDefaultBridgeControllerState = (): BridgeControllerState => {\n return DEFAULT_BRIDGE_CONTROLLER_STATE;\n};\n\nexport const getBridgeApiBaseUrl = () => {\n if (process.env.BRIDGE_CUSTOM_API_BASE_URL) {\n return process.env.BRIDGE_CUSTOM_API_BASE_URL;\n }\n\n if (process.env.BRIDGE_USE_DEV_APIS) {\n return BRIDGE_DEV_API_BASE_URL;\n }\n\n return BRIDGE_PROD_API_BASE_URL;\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 */\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 * 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 */\n\nexport const isSwapsDefaultTokenAddress = (address: string, chainId: Hex) => {\n if (!address || !chainId) {\n return false;\n }\n\n return (\n address ===\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n chainId as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ]?.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 */\n\nexport const isSwapsDefaultTokenSymbol = (symbol: string, chainId: Hex) => {\n if (!symbol || !chainId) {\n return false;\n }\n\n return (\n symbol ===\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n chainId as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ]?.symbol\n );\n};\n"]}
@@ -0,0 +1,31 @@
1
+ import type { Hex } from "@metamask/utils";
2
+ import type { BridgeControllerState } from "../types.cjs";
3
+ export declare const getDefaultBridgeControllerState: () => BridgeControllerState;
4
+ export declare const getBridgeApiBaseUrl: () => string;
5
+ /**
6
+ * A function to return the txParam data for setting allowance to 0 for USDT on Ethereum
7
+ *
8
+ * @returns The txParam data that will reset allowance to 0, combine it with the approval tx params received from Bridge API
9
+ */
10
+ export declare const getEthUsdtResetData: () => string;
11
+ export declare const isEthUsdt: (chainId: Hex, address: string) => boolean;
12
+ export declare const sumHexes: (...hexStrings: string[]) => Hex;
13
+ /**
14
+ * Checks whether the provided address is strictly equal to the address for
15
+ * the default swaps token of the provided chain.
16
+ *
17
+ * @param address - The string to compare to the default token address
18
+ * @param chainId - The hex encoded chain ID of the default swaps token to check
19
+ * @returns Whether the address is the provided chain's default token address
20
+ */
21
+ export declare const isSwapsDefaultTokenAddress: (address: string, chainId: Hex) => boolean;
22
+ /**
23
+ * Checks whether the provided symbol is strictly equal to the symbol for
24
+ * the default swaps token of the provided chain.
25
+ *
26
+ * @param symbol - The string to compare to the default token symbol
27
+ * @param chainId - The hex encoded chain ID of the default swaps token to check
28
+ * @returns Whether the symbol is the provided chain's default token symbol
29
+ */
30
+ export declare const isSwapsDefaultTokenSymbol: (symbol: string, chainId: Hex) => boolean;
31
+ //# sourceMappingURL=bridge.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bridge.d.cts","sourceRoot":"","sources":["../../src/utils/bridge.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAY3C,OAAO,KAAK,EAAE,qBAAqB,EAAE,qBAAiB;AAEtD,eAAO,MAAM,+BAA+B,QAAO,qBAElD,CAAC;AAEF,eAAO,MAAM,mBAAmB,cAU/B,CAAC;AACF;;;;GAIG;AAEH,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;AACF;;;;;;;GAOG;AAEH,eAAO,MAAM,0BAA0B,YAAa,MAAM,WAAW,GAAG,YAWvE,CAAC;AACF;;;;;;;GAOG;AAEH,eAAO,MAAM,yBAAyB,WAAY,MAAM,WAAW,GAAG,YAWrE,CAAC"}
@@ -0,0 +1,31 @@
1
+ import type { Hex } from "@metamask/utils";
2
+ import type { BridgeControllerState } from "../types.mjs";
3
+ export declare const getDefaultBridgeControllerState: () => BridgeControllerState;
4
+ export declare const getBridgeApiBaseUrl: () => string;
5
+ /**
6
+ * A function to return the txParam data for setting allowance to 0 for USDT on Ethereum
7
+ *
8
+ * @returns The txParam data that will reset allowance to 0, combine it with the approval tx params received from Bridge API
9
+ */
10
+ export declare const getEthUsdtResetData: () => string;
11
+ export declare const isEthUsdt: (chainId: Hex, address: string) => boolean;
12
+ export declare const sumHexes: (...hexStrings: string[]) => Hex;
13
+ /**
14
+ * Checks whether the provided address is strictly equal to the address for
15
+ * the default swaps token of the provided chain.
16
+ *
17
+ * @param address - The string to compare to the default token address
18
+ * @param chainId - The hex encoded chain ID of the default swaps token to check
19
+ * @returns Whether the address is the provided chain's default token address
20
+ */
21
+ export declare const isSwapsDefaultTokenAddress: (address: string, chainId: Hex) => boolean;
22
+ /**
23
+ * Checks whether the provided symbol is strictly equal to the symbol for
24
+ * the default swaps token of the provided chain.
25
+ *
26
+ * @param symbol - The string to compare to the default token symbol
27
+ * @param chainId - The hex encoded chain ID of the default swaps token to check
28
+ * @returns Whether the symbol is the provided chain's default token symbol
29
+ */
30
+ export declare const isSwapsDefaultTokenSymbol: (symbol: string, chainId: Hex) => boolean;
31
+ //# sourceMappingURL=bridge.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bridge.d.mts","sourceRoot":"","sources":["../../src/utils/bridge.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAY3C,OAAO,KAAK,EAAE,qBAAqB,EAAE,qBAAiB;AAEtD,eAAO,MAAM,+BAA+B,QAAO,qBAElD,CAAC;AAEF,eAAO,MAAM,mBAAmB,cAU/B,CAAC;AACF;;;;GAIG;AAEH,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;AACF;;;;;;;GAOG;AAEH,eAAO,MAAM,0BAA0B,YAAa,MAAM,WAAW,GAAG,YAWvE,CAAC;AACF;;;;;;;GAOG;AAEH,eAAO,MAAM,yBAAyB,WAAY,MAAM,WAAW,GAAG,YAWrE,CAAC"}
@@ -0,0 +1,71 @@
1
+ import { abiERC20 } from "@metamask/metamask-eth-abis";
2
+ import { Contract } from "ethers";
3
+ import { DEFAULT_BRIDGE_CONTROLLER_STATE, BRIDGE_DEV_API_BASE_URL, BRIDGE_PROD_API_BASE_URL, ETH_USDT_ADDRESS, METABRIDGE_ETHEREUM_ADDRESS } from "../constants/bridge.mjs";
4
+ import { CHAIN_IDS } from "../constants/chains.mjs";
5
+ import { SWAPS_CHAINID_DEFAULT_TOKEN_MAP } from "../constants/tokens.mjs";
6
+ export const getDefaultBridgeControllerState = () => {
7
+ return DEFAULT_BRIDGE_CONTROLLER_STATE;
8
+ };
9
+ export const getBridgeApiBaseUrl = () => {
10
+ if (process.env.BRIDGE_CUSTOM_API_BASE_URL) {
11
+ return process.env.BRIDGE_CUSTOM_API_BASE_URL;
12
+ }
13
+ if (process.env.BRIDGE_USE_DEV_APIS) {
14
+ return BRIDGE_DEV_API_BASE_URL;
15
+ }
16
+ return BRIDGE_PROD_API_BASE_URL;
17
+ };
18
+ /**
19
+ * A function to return the txParam data for setting allowance to 0 for USDT on Ethereum
20
+ *
21
+ * @returns The txParam data that will reset allowance to 0, combine it with the approval tx params received from Bridge API
22
+ */
23
+ export const getEthUsdtResetData = () => {
24
+ const UsdtContractInterface = new Contract(ETH_USDT_ADDRESS, abiERC20)
25
+ .interface;
26
+ const data = UsdtContractInterface.encodeFunctionData('approve', [
27
+ METABRIDGE_ETHEREUM_ADDRESS,
28
+ '0',
29
+ ]);
30
+ return data;
31
+ };
32
+ export const isEthUsdt = (chainId, address) => chainId === CHAIN_IDS.MAINNET &&
33
+ address.toLowerCase() === ETH_USDT_ADDRESS.toLowerCase();
34
+ export const sumHexes = (...hexStrings) => {
35
+ if (hexStrings.length === 0) {
36
+ return '0x0';
37
+ }
38
+ const sum = hexStrings.reduce((acc, hex) => acc + BigInt(hex), BigInt(0));
39
+ return `0x${sum.toString(16)}`;
40
+ };
41
+ /**
42
+ * Checks whether the provided address is strictly equal to the address for
43
+ * the default swaps token of the provided chain.
44
+ *
45
+ * @param address - The string to compare to the default token address
46
+ * @param chainId - The hex encoded chain ID of the default swaps token to check
47
+ * @returns Whether the address is the provided chain's default token address
48
+ */
49
+ export const isSwapsDefaultTokenAddress = (address, chainId) => {
50
+ if (!address || !chainId) {
51
+ return false;
52
+ }
53
+ return (address ===
54
+ SWAPS_CHAINID_DEFAULT_TOKEN_MAP[chainId]?.address);
55
+ };
56
+ /**
57
+ * Checks whether the provided symbol is strictly equal to the symbol for
58
+ * the default swaps token of the provided chain.
59
+ *
60
+ * @param symbol - The string to compare to the default token symbol
61
+ * @param chainId - The hex encoded chain ID of the default swaps token to check
62
+ * @returns Whether the symbol is the provided chain's default token symbol
63
+ */
64
+ export const isSwapsDefaultTokenSymbol = (symbol, chainId) => {
65
+ if (!symbol || !chainId) {
66
+ return false;
67
+ }
68
+ return (symbol ===
69
+ SWAPS_CHAINID_DEFAULT_TOKEN_MAP[chainId]?.symbol);
70
+ };
71
+ //# sourceMappingURL=bridge.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bridge.mjs","sourceRoot":"","sources":["../../src/utils/bridge.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,oCAAoC;AAEvD,OAAO,EAAE,QAAQ,EAAE,eAAe;AAElC,OAAO,EACL,+BAA+B,EAC/B,uBAAuB,EACvB,wBAAwB,EACxB,gBAAgB,EAChB,2BAA2B,EAC5B,gCAA4B;AAC7B,OAAO,EAAE,SAAS,EAAE,gCAA4B;AAChD,OAAO,EAAE,+BAA+B,EAAE,gCAA4B;AAGtE,MAAM,CAAC,MAAM,+BAA+B,GAAG,GAA0B,EAAE;IACzE,OAAO,+BAA+B,CAAC;AACzC,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,EAAE;IACtC,IAAI,OAAO,CAAC,GAAG,CAAC,0BAA0B,EAAE;QAC1C,OAAO,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC;KAC/C;IAED,IAAI,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE;QACnC,OAAO,uBAAuB,CAAC;KAChC;IAED,OAAO,wBAAwB,CAAC;AAClC,CAAC,CAAC;AACF;;;;GAIG;AAEH,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,EAA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;QACvB,OAAO,KAAK,CAAC;KACd;IAED,OAAO,CACL,MAAM;QACN,+BAA+B,CAC7B,OAAuD,CACxD,EAAE,MAAM,CACV,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import { abiERC20 } from '@metamask/metamask-eth-abis';\nimport type { Hex } from '@metamask/utils';\nimport { Contract } from 'ethers';\n\nimport {\n DEFAULT_BRIDGE_CONTROLLER_STATE,\n BRIDGE_DEV_API_BASE_URL,\n BRIDGE_PROD_API_BASE_URL,\n ETH_USDT_ADDRESS,\n METABRIDGE_ETHEREUM_ADDRESS,\n} from '../constants/bridge';\nimport { CHAIN_IDS } from '../constants/chains';\nimport { SWAPS_CHAINID_DEFAULT_TOKEN_MAP } from '../constants/tokens';\nimport type { BridgeControllerState } from '../types';\n\nexport const getDefaultBridgeControllerState = (): BridgeControllerState => {\n return DEFAULT_BRIDGE_CONTROLLER_STATE;\n};\n\nexport const getBridgeApiBaseUrl = () => {\n if (process.env.BRIDGE_CUSTOM_API_BASE_URL) {\n return process.env.BRIDGE_CUSTOM_API_BASE_URL;\n }\n\n if (process.env.BRIDGE_USE_DEV_APIS) {\n return BRIDGE_DEV_API_BASE_URL;\n }\n\n return BRIDGE_PROD_API_BASE_URL;\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 */\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 * 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 */\n\nexport const isSwapsDefaultTokenAddress = (address: string, chainId: Hex) => {\n if (!address || !chainId) {\n return false;\n }\n\n return (\n address ===\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n chainId as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ]?.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 */\n\nexport const isSwapsDefaultTokenSymbol = (symbol: string, chainId: Hex) => {\n if (!symbol || !chainId) {\n return false;\n }\n\n return (\n symbol ===\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n chainId as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ]?.symbol\n );\n};\n"]}
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fetchBridgeQuotes = exports.fetchBridgeTokens = exports.fetchBridgeFeatureFlags = exports.getClientIdHeader = void 0;
4
+ const utils_1 = require("@metamask/utils");
5
+ const bridge_1 = require("./bridge.cjs");
6
+ const validators_1 = require("./validators.cjs");
7
+ const bridge_2 = require("../constants/bridge.cjs");
8
+ const tokens_1 = require("../constants/tokens.cjs");
9
+ const types_1 = require("../types.cjs");
10
+ // TODO put this back in once we have a fetchWithCache equivalent
11
+ // const CACHE_REFRESH_TEN_MINUTES = 10 * Duration.Minute;
12
+ const getClientIdHeader = (clientId) => ({
13
+ 'X-Client-Id': clientId,
14
+ });
15
+ exports.getClientIdHeader = getClientIdHeader;
16
+ /**
17
+ * Fetches the bridge feature flags
18
+ *
19
+ * @param clientId - The client ID for metrics
20
+ * @param fetchFn - The fetch function to use
21
+ * @returns The bridge feature flags
22
+ */
23
+ async function fetchBridgeFeatureFlags(clientId, fetchFn) {
24
+ const url = `${(0, bridge_1.getBridgeApiBaseUrl)()}/getAllFeatureFlags`;
25
+ const rawFeatureFlags = await fetchFn(url, {
26
+ headers: (0, exports.getClientIdHeader)(clientId),
27
+ });
28
+ if ((0, validators_1.validateResponse)(validators_1.FEATURE_FLAG_VALIDATORS, rawFeatureFlags, url)) {
29
+ return {
30
+ [types_1.BridgeFeatureFlagsKey.EXTENSION_CONFIG]: {
31
+ ...rawFeatureFlags[types_1.BridgeFlag.EXTENSION_CONFIG],
32
+ chains: Object.entries(rawFeatureFlags[types_1.BridgeFlag.EXTENSION_CONFIG].chains).reduce((acc, [chainId, value]) => ({
33
+ ...acc,
34
+ [(0, utils_1.numberToHex)(Number(chainId))]: value,
35
+ }), {}),
36
+ },
37
+ };
38
+ }
39
+ return {
40
+ [types_1.BridgeFeatureFlagsKey.EXTENSION_CONFIG]: {
41
+ refreshRate: bridge_2.REFRESH_INTERVAL_MS,
42
+ maxRefreshCount: 5,
43
+ support: false,
44
+ chains: {},
45
+ },
46
+ };
47
+ }
48
+ exports.fetchBridgeFeatureFlags = fetchBridgeFeatureFlags;
49
+ /**
50
+ * Returns a list of enabled (unblocked) tokens
51
+ *
52
+ * @param chainId - The chain ID to fetch tokens for
53
+ * @param clientId - The client ID for metrics
54
+ * @param fetchFn - The fetch function to use
55
+ * @returns A list of enabled (unblocked) tokens
56
+ */
57
+ async function fetchBridgeTokens(chainId, clientId, fetchFn) {
58
+ // TODO make token api v2 call
59
+ const url = `${(0, bridge_1.getBridgeApiBaseUrl)()}/getTokens?chainId=${(0, utils_1.hexToNumber)(chainId)}`;
60
+ // TODO we will need to cache these. In Extension fetchWithCache is used. This is due to the following:
61
+ // If we allow selecting dest networks which the user has not imported,
62
+ // 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
63
+ const tokens = await fetchFn(url, {
64
+ headers: (0, exports.getClientIdHeader)(clientId),
65
+ });
66
+ const nativeToken = tokens_1.SWAPS_CHAINID_DEFAULT_TOKEN_MAP[chainId];
67
+ const transformedTokens = {};
68
+ if (nativeToken) {
69
+ transformedTokens[nativeToken.address] = nativeToken;
70
+ }
71
+ tokens.forEach((token) => {
72
+ if ((0, validators_1.validateResponse)(validators_1.TOKEN_VALIDATORS, token, url, false) &&
73
+ !((0, bridge_1.isSwapsDefaultTokenSymbol)(token.symbol, chainId) ||
74
+ (0, bridge_1.isSwapsDefaultTokenAddress)(token.address, chainId))) {
75
+ transformedTokens[token.address] = token;
76
+ }
77
+ });
78
+ return transformedTokens;
79
+ }
80
+ exports.fetchBridgeTokens = fetchBridgeTokens;
81
+ // Returns a list of bridge tx quotes
82
+ /**
83
+ *
84
+ * @param request - The quote request
85
+ * @param signal - The abort signal
86
+ * @param clientId - The client ID for metrics
87
+ * @param fetchFn - The fetch function to use
88
+ * @returns A list of bridge tx quotes
89
+ */
90
+ async function fetchBridgeQuotes(request, signal, clientId, fetchFn) {
91
+ const queryParams = new URLSearchParams({
92
+ walletAddress: request.walletAddress,
93
+ srcChainId: request.srcChainId.toString(),
94
+ destChainId: request.destChainId.toString(),
95
+ srcTokenAddress: request.srcTokenAddress,
96
+ destTokenAddress: request.destTokenAddress,
97
+ srcTokenAmount: request.srcTokenAmount,
98
+ slippage: request.slippage.toString(),
99
+ insufficientBal: request.insufficientBal ? 'true' : 'false',
100
+ resetApproval: request.resetApproval ? 'true' : 'false',
101
+ });
102
+ const url = `${(0, bridge_1.getBridgeApiBaseUrl)()}/getQuote?${queryParams}`;
103
+ const quotes = await fetchFn(url, {
104
+ headers: (0, exports.getClientIdHeader)(clientId),
105
+ signal,
106
+ });
107
+ const filteredQuotes = quotes.filter((quoteResponse) => {
108
+ const { quote, approval, trade } = quoteResponse;
109
+ return ((0, validators_1.validateResponse)(validators_1.QUOTE_RESPONSE_VALIDATORS, quoteResponse, url) &&
110
+ (0, validators_1.validateResponse)(validators_1.QUOTE_VALIDATORS, quote, url) &&
111
+ (0, validators_1.validateResponse)(validators_1.TOKEN_VALIDATORS, quote.srcAsset, url) &&
112
+ (0, validators_1.validateResponse)(validators_1.TOKEN_VALIDATORS, quote.destAsset, url) &&
113
+ (0, validators_1.validateResponse)(validators_1.TX_DATA_VALIDATORS, trade, url) &&
114
+ (0, validators_1.validateResponse)(validators_1.FEE_DATA_VALIDATORS, quote.feeData[types_1.FeeType.METABRIDGE], url) &&
115
+ (approval
116
+ ? (0, validators_1.validateResponse)(validators_1.TX_DATA_VALIDATORS, approval, url)
117
+ : true));
118
+ });
119
+ return filteredQuotes;
120
+ }
121
+ exports.fetchBridgeQuotes = fetchBridgeQuotes;
122
+ //# sourceMappingURL=fetch.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.cjs","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":";;;AACA,2CAA2D;AAE3D,yCAIkB;AAClB,iDAQsB;AACtB,oDAA0D;AAE1D,oDAAsE;AAWtE,wCAAsE;AAEtE,iEAAiE;AACjE,0DAA0D;AAEnD,MAAM,iBAAiB,GAAG,CAAC,QAAgB,EAAE,EAAE,CAAC,CAAC;IACtD,aAAa,EAAE,QAAQ;CACxB,CAAC,CAAC;AAFU,QAAA,iBAAiB,qBAE3B;AAEH;;;;;;GAMG;AACI,KAAK,UAAU,uBAAuB,CAC3C,QAAgB,EAChB,OAAsB;IAEtB,MAAM,GAAG,GAAG,GAAG,IAAA,4BAAmB,GAAE,qBAAqB,CAAC;IAC1D,MAAM,eAAe,GAAG,MAAM,OAAO,CAAC,GAAG,EAAE;QACzC,OAAO,EAAE,IAAA,yBAAiB,EAAC,QAAQ,CAAC;KACrC,CAAC,CAAC;IAEH,IACE,IAAA,6BAAgB,EACd,oCAAuB,EACvB,eAAe,EACf,GAAG,CACJ,EACD;QACA,OAAO;YACL,CAAC,6BAA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;KACP,CAAC,CAAC;IAEH,MAAM,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,aAA4B,EAAE,EAAE;QACpE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,GAAG,aAAa,CAAC;QACjD,OAAO,CACL,IAAA,6BAAgB,EACd,sCAAyB,EACzB,aAAa,EACb,GAAG,CACJ;YACD,IAAA,6BAAgB,EAAQ,6BAAgB,EAAE,KAAK,EAAE,GAAG,CAAC;YACrD,IAAA,6BAAgB,EACd,6BAAgB,EAChB,KAAK,CAAC,QAAQ,EACd,GAAG,CACJ;YACD,IAAA,6BAAgB,EACd,6BAAgB,EAChB,KAAK,CAAC,SAAS,EACf,GAAG,CACJ;YACD,IAAA,6BAAgB,EAAS,+BAAkB,EAAE,KAAK,EAAE,GAAG,CAAC;YACxD,IAAA,6BAAgB,EACd,gCAAmB,EACnB,KAAK,CAAC,OAAO,CAAC,eAAO,CAAC,UAAU,CAAC,EACjC,GAAG,CACJ;YACD,CAAC,QAAQ;gBACP,CAAC,CAAC,IAAA,6BAAgB,EAAS,+BAAkB,EAAE,QAAQ,EAAE,GAAG,CAAC;gBAC7D,CAAC,CAAC,IAAI,CAAC,CACV,CAAC;IACJ,CAAC,CAAC,CAAC;IACH,OAAO,cAAc,CAAC;AACxB,CAAC;AAtDD,8CAsDC","sourcesContent":["import type { Hex } from '@metamask/utils';\nimport { hexToNumber, numberToHex } from '@metamask/utils';\n\nimport {\n isSwapsDefaultTokenAddress,\n isSwapsDefaultTokenSymbol,\n getBridgeApiBaseUrl,\n} from './bridge';\nimport {\n FEATURE_FLAG_VALIDATORS,\n QUOTE_VALIDATORS,\n TX_DATA_VALIDATORS,\n TOKEN_VALIDATORS,\n validateResponse,\n QUOTE_RESPONSE_VALIDATORS,\n FEE_DATA_VALIDATORS,\n} from './validators';\nimport { REFRESH_INTERVAL_MS } from '../constants/bridge';\nimport type { SwapsTokenObject } from '../constants/tokens';\nimport { SWAPS_CHAINID_DEFAULT_TOKEN_MAP } from '../constants/tokens';\nimport type {\n FeatureFlagResponse,\n FeeData,\n Quote,\n QuoteRequest,\n QuoteResponse,\n TxData,\n BridgeFeatureFlags,\n FetchFunction,\n} from '../types';\nimport { BridgeFlag, FeeType, BridgeFeatureFlagsKey } from '../types';\n\n// TODO put this back in once we have a fetchWithCache equivalent\n// const CACHE_REFRESH_TEN_MINUTES = 10 * Duration.Minute;\n\nexport const getClientIdHeader = (clientId: string) => ({\n 'X-Client-Id': clientId,\n});\n\n/**\n * Fetches the bridge feature flags\n *\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @returns The bridge feature flags\n */\nexport async function fetchBridgeFeatureFlags(\n clientId: string,\n fetchFn: FetchFunction,\n): Promise<BridgeFeatureFlags> {\n const url = `${getBridgeApiBaseUrl()}/getAllFeatureFlags`;\n const rawFeatureFlags = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n });\n\n if (\n validateResponse<FeatureFlagResponse>(\n FEATURE_FLAG_VALIDATORS,\n rawFeatureFlags,\n url,\n )\n ) {\n return {\n [BridgeFeatureFlagsKey.EXTENSION_CONFIG]: {\n ...rawFeatureFlags[BridgeFlag.EXTENSION_CONFIG],\n chains: Object.entries(\n rawFeatureFlags[BridgeFlag.EXTENSION_CONFIG].chains,\n ).reduce(\n (acc, [chainId, value]) => ({\n ...acc,\n [numberToHex(Number(chainId))]: value,\n }),\n {},\n ),\n },\n };\n }\n\n return {\n [BridgeFeatureFlagsKey.EXTENSION_CONFIG]: {\n refreshRate: REFRESH_INTERVAL_MS,\n maxRefreshCount: 5,\n support: false,\n chains: {},\n },\n };\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 * @returns A list of enabled (unblocked) tokens\n */\nexport async function fetchBridgeTokens(\n chainId: Hex,\n clientId: string,\n fetchFn: FetchFunction,\n): Promise<Record<string, SwapsTokenObject>> {\n // TODO make token api v2 call\n const url = `${getBridgeApiBaseUrl()}/getTokens?chainId=${hexToNumber(\n chainId,\n )}`;\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 });\n\n const nativeToken =\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n chainId as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ];\n\n const transformedTokens: Record<string, SwapsTokenObject> = {};\n if (nativeToken) {\n transformedTokens[nativeToken.address] = nativeToken;\n }\n\n tokens.forEach((token: unknown) => {\n if (\n validateResponse<SwapsTokenObject>(TOKEN_VALIDATORS, token, url, false) &&\n !(\n isSwapsDefaultTokenSymbol(token.symbol, chainId) ||\n isSwapsDefaultTokenAddress(token.address, chainId)\n )\n ) {\n transformedTokens[token.address] = token;\n }\n });\n return transformedTokens;\n}\n\n// Returns a list of bridge tx quotes\n/**\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 * @returns A list of bridge tx quotes\n */\nexport async function fetchBridgeQuotes(\n request: QuoteRequest,\n signal: AbortSignal,\n clientId: string,\n fetchFn: FetchFunction,\n): Promise<QuoteResponse[]> {\n const queryParams = new URLSearchParams({\n walletAddress: request.walletAddress,\n srcChainId: request.srcChainId.toString(),\n destChainId: request.destChainId.toString(),\n srcTokenAddress: request.srcTokenAddress,\n destTokenAddress: request.destTokenAddress,\n srcTokenAmount: request.srcTokenAmount,\n slippage: request.slippage.toString(),\n insufficientBal: request.insufficientBal ? 'true' : 'false',\n resetApproval: request.resetApproval ? 'true' : 'false',\n });\n const url = `${getBridgeApiBaseUrl()}/getQuote?${queryParams}`;\n const quotes = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n signal,\n });\n\n const filteredQuotes = quotes.filter((quoteResponse: QuoteResponse) => {\n const { quote, approval, trade } = quoteResponse;\n return (\n validateResponse<QuoteResponse>(\n QUOTE_RESPONSE_VALIDATORS,\n quoteResponse,\n url,\n ) &&\n validateResponse<Quote>(QUOTE_VALIDATORS, quote, url) &&\n validateResponse<SwapsTokenObject>(\n TOKEN_VALIDATORS,\n quote.srcAsset,\n url,\n ) &&\n validateResponse<SwapsTokenObject>(\n TOKEN_VALIDATORS,\n quote.destAsset,\n url,\n ) &&\n validateResponse<TxData>(TX_DATA_VALIDATORS, trade, url) &&\n validateResponse<FeeData>(\n FEE_DATA_VALIDATORS,\n quote.feeData[FeeType.METABRIDGE],\n url,\n ) &&\n (approval\n ? validateResponse<TxData>(TX_DATA_VALIDATORS, approval, url)\n : true)\n );\n });\n return filteredQuotes;\n}\n"]}