@metamask/bridge-controller 33.0.1 → 34.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -1
- package/dist/bridge-controller.cjs.map +1 -1
- package/dist/bridge-controller.d.cts.map +1 -1
- package/dist/bridge-controller.d.mts.map +1 -1
- package/dist/bridge-controller.mjs.map +1 -1
- package/dist/index.cjs +6 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +2 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -1
- package/dist/index.mjs.map +1 -1
- package/dist/selectors.cjs +13 -4
- package/dist/selectors.cjs.map +1 -1
- package/dist/selectors.d.cts +13100 -124
- package/dist/selectors.d.cts.map +1 -1
- package/dist/selectors.d.mts +13100 -124
- package/dist/selectors.d.mts.map +1 -1
- package/dist/selectors.mjs +14 -5
- package/dist/selectors.mjs.map +1 -1
- package/dist/types.cjs +1 -12
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +35 -113
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +35 -113
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs +0 -11
- package/dist/types.mjs.map +1 -1
- package/dist/utils/feature-flags.d.cts +2 -2
- package/dist/utils/feature-flags.d.mts +2 -2
- package/dist/utils/fetch.cjs +1 -0
- package/dist/utils/fetch.cjs.map +1 -1
- package/dist/utils/fetch.d.cts.map +1 -1
- package/dist/utils/fetch.d.mts.map +1 -1
- package/dist/utils/fetch.mjs +1 -0
- package/dist/utils/fetch.mjs.map +1 -1
- package/dist/utils/quote.cjs +58 -19
- package/dist/utils/quote.cjs.map +1 -1
- package/dist/utils/quote.d.cts +7 -2
- package/dist/utils/quote.d.cts.map +1 -1
- package/dist/utils/quote.d.mts +7 -2
- package/dist/utils/quote.d.mts.map +1 -1
- package/dist/utils/quote.mjs +57 -19
- package/dist/utils/quote.mjs.map +1 -1
- package/dist/utils/validators.cjs +134 -73
- package/dist/utils/validators.cjs.map +1 -1
- package/dist/utils/validators.d.cts +1922 -4
- package/dist/utils/validators.d.cts.map +1 -1
- package/dist/utils/validators.d.mts +1922 -4
- package/dist/utils/validators.d.mts.map +1 -1
- package/dist/utils/validators.mjs +132 -71
- package/dist/utils/validators.mjs.map +1 -1
- package/package.json +2 -2
package/dist/types.d.mts
CHANGED
|
@@ -4,9 +4,11 @@ import type { ControllerStateChangeEvent, RestrictedMessenger } from "@metamask/
|
|
|
4
4
|
import type { NetworkControllerFindNetworkClientIdByChainIdAction, NetworkControllerGetStateAction, NetworkControllerGetNetworkClientByIdAction } from "@metamask/network-controller";
|
|
5
5
|
import type { RemoteFeatureFlagControllerGetStateAction } from "@metamask/remote-feature-flag-controller";
|
|
6
6
|
import type { HandleSnapRequest } from "@metamask/snaps-controllers";
|
|
7
|
+
import type { Infer } from "@metamask/superstruct";
|
|
7
8
|
import type { CaipAccountId, CaipAssetId, CaipAssetType, CaipChainId, Hex } from "@metamask/utils";
|
|
8
9
|
import type { BridgeController } from "./bridge-controller.mjs";
|
|
9
10
|
import type { BRIDGE_CONTROLLER_NAME } from "./constants/bridge.mjs";
|
|
11
|
+
import type { BridgeAssetSchema, ChainConfigurationSchema, FeeDataSchema, PlatformConfigSchema, ProtocolSchema, QuoteResponseSchema, QuoteSchema, StepSchema, TxDataSchema } from "./utils/validators.mjs";
|
|
10
12
|
/**
|
|
11
13
|
* Additional options accepted by the extension's fetchWithCache function
|
|
12
14
|
*/
|
|
@@ -33,14 +35,7 @@ export declare enum AssetType {
|
|
|
33
35
|
*/
|
|
34
36
|
unknown = "UNKNOWN"
|
|
35
37
|
}
|
|
36
|
-
export type ChainConfiguration =
|
|
37
|
-
isActiveSrc: boolean;
|
|
38
|
-
isActiveDest: boolean;
|
|
39
|
-
refreshRate?: number;
|
|
40
|
-
topAssets?: string[];
|
|
41
|
-
isUnifiedUIEnabled?: boolean;
|
|
42
|
-
isSnapConfirmationEnabled?: boolean;
|
|
43
|
-
};
|
|
38
|
+
export type ChainConfiguration = Infer<typeof ChainConfigurationSchema>;
|
|
44
39
|
export type L1GasFees = {
|
|
45
40
|
l1GasFeesInHexWei?: string;
|
|
46
41
|
};
|
|
@@ -81,11 +76,26 @@ export type ExchangeRate = {
|
|
|
81
76
|
* Values derived from the quote response
|
|
82
77
|
*/
|
|
83
78
|
export type QuoteMetadata = {
|
|
79
|
+
/**
|
|
80
|
+
* If gas is included, this is the value of the src or dest token that was used to pay for the gas
|
|
81
|
+
*/
|
|
82
|
+
includedTxFees?: TokenAmountValues | null;
|
|
84
83
|
gasFee: TokenAmountValues;
|
|
85
84
|
totalNetworkFee: TokenAmountValues;
|
|
86
85
|
totalMaxNetworkFee: TokenAmountValues;
|
|
86
|
+
/**
|
|
87
|
+
* The amount that the user will receive (destTokenAmount)
|
|
88
|
+
*/
|
|
87
89
|
toTokenAmount: TokenAmountValues;
|
|
90
|
+
/**
|
|
91
|
+
* If gas is included: toTokenAmount
|
|
92
|
+
* Otherwise: toTokenAmount - totalNetworkFee
|
|
93
|
+
*/
|
|
88
94
|
adjustedReturn: Omit<TokenAmountValues, 'amount'>;
|
|
95
|
+
/**
|
|
96
|
+
* The amount that the user will send, including fees
|
|
97
|
+
* srcTokenAmount + metabridgeFee + txFee
|
|
98
|
+
*/
|
|
89
99
|
sentAmount: TokenAmountValues;
|
|
90
100
|
swapRate: string;
|
|
91
101
|
cost: Omit<TokenAmountValues, 'amount'>;
|
|
@@ -101,37 +111,7 @@ export declare enum SortOrder {
|
|
|
101
111
|
* This is the interface for the asset object returned by the bridge-api
|
|
102
112
|
* This type is used in the QuoteResponse and in the fetchBridgeTokens response
|
|
103
113
|
*/
|
|
104
|
-
export type BridgeAsset =
|
|
105
|
-
/**
|
|
106
|
-
* The chainId of the token
|
|
107
|
-
*/
|
|
108
|
-
chainId: ChainId;
|
|
109
|
-
/**
|
|
110
|
-
* An address that the metaswap-api recognizes as the default token
|
|
111
|
-
*/
|
|
112
|
-
address: string;
|
|
113
|
-
/**
|
|
114
|
-
* The symbol of token object
|
|
115
|
-
*/
|
|
116
|
-
symbol: string;
|
|
117
|
-
/**
|
|
118
|
-
* The name for the network
|
|
119
|
-
*/
|
|
120
|
-
name: string;
|
|
121
|
-
/**
|
|
122
|
-
* Number of digits after decimal point
|
|
123
|
-
*/
|
|
124
|
-
decimals: number;
|
|
125
|
-
icon?: string;
|
|
126
|
-
/**
|
|
127
|
-
* URL for token icon
|
|
128
|
-
*/
|
|
129
|
-
iconUrl?: string;
|
|
130
|
-
/**
|
|
131
|
-
* The assetId of the token
|
|
132
|
-
*/
|
|
133
|
-
assetId: CaipAssetType;
|
|
134
|
-
};
|
|
114
|
+
export type BridgeAsset = Infer<typeof BridgeAssetSchema>;
|
|
135
115
|
/**
|
|
136
116
|
* This is the interface for the token object used in the extension client
|
|
137
117
|
* In addition to the {@link BridgeAsset} fields, it includes balance information
|
|
@@ -149,13 +129,7 @@ export type BridgeToken = {
|
|
|
149
129
|
};
|
|
150
130
|
type DecimalChainId = string;
|
|
151
131
|
export type GasMultiplierByChainId = Record<DecimalChainId, number>;
|
|
152
|
-
type
|
|
153
|
-
refreshRate: number;
|
|
154
|
-
maxRefreshCount: number;
|
|
155
|
-
support: boolean;
|
|
156
|
-
chains: Record<string, ChainConfiguration>;
|
|
157
|
-
};
|
|
158
|
-
export type FeatureFlagResponse = FeatureFlagResponsePlatformConfig;
|
|
132
|
+
export type FeatureFlagResponse = Infer<typeof PlatformConfigSchema>;
|
|
159
133
|
/**
|
|
160
134
|
* This is the interface for the quote request sent to the bridge-api
|
|
161
135
|
* and should only be used by the fetchBridgeQuotes utility function
|
|
@@ -178,6 +152,12 @@ export type QuoteRequest<ChainIdType = ChainId | number, TokenAddressType = stri
|
|
|
178
152
|
insufficientBal?: boolean;
|
|
179
153
|
resetApproval?: boolean;
|
|
180
154
|
refuel?: boolean;
|
|
155
|
+
/**
|
|
156
|
+
* Whether the response should include gasless swap quotes
|
|
157
|
+
* This should be true if the user has opted in to STX on the client
|
|
158
|
+
* and the current network has STX support
|
|
159
|
+
*/
|
|
160
|
+
gasIncluded: boolean;
|
|
181
161
|
};
|
|
182
162
|
export declare enum StatusTypes {
|
|
183
163
|
UNKNOWN = "UNKNOWN",
|
|
@@ -194,55 +174,19 @@ export type GenericQuoteRequest = QuoteRequest<Hex | CaipChainId | string | numb
|
|
|
194
174
|
Hex | CaipAssetId | string, // assetIds/addresses
|
|
195
175
|
// assetIds/addresses
|
|
196
176
|
Hex | CaipAccountId | string>;
|
|
197
|
-
export type Protocol =
|
|
198
|
-
|
|
199
|
-
displayName?: string;
|
|
200
|
-
icon?: string;
|
|
201
|
-
};
|
|
202
|
-
export declare enum ActionTypes {
|
|
203
|
-
BRIDGE = "bridge",
|
|
204
|
-
SWAP = "swap",
|
|
205
|
-
REFUEL = "refuel"
|
|
206
|
-
}
|
|
207
|
-
export type Step = {
|
|
208
|
-
action: ActionTypes;
|
|
209
|
-
srcChainId: ChainId;
|
|
210
|
-
destChainId?: ChainId;
|
|
211
|
-
srcAsset?: BridgeAsset;
|
|
212
|
-
destAsset?: BridgeAsset;
|
|
213
|
-
srcAmount: string;
|
|
214
|
-
destAmount: string;
|
|
215
|
-
protocol: Protocol;
|
|
216
|
-
};
|
|
177
|
+
export type Protocol = Infer<typeof ProtocolSchema>;
|
|
178
|
+
export type Step = Infer<typeof StepSchema>;
|
|
217
179
|
export type RefuelData = Step;
|
|
218
|
-
export type
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
srcAsset: BridgeAsset;
|
|
222
|
-
srcTokenAmount: string;
|
|
223
|
-
destChainId: ChainId;
|
|
224
|
-
destAsset: BridgeAsset;
|
|
225
|
-
destTokenAmount: string;
|
|
226
|
-
feeData: Record<FeeType.METABRIDGE, FeeData> & Partial<Record<FeeType, FeeData>>;
|
|
227
|
-
bridgeId: string;
|
|
228
|
-
bridges: string[];
|
|
229
|
-
steps: Step[];
|
|
230
|
-
refuel?: RefuelData;
|
|
231
|
-
priceData?: {
|
|
232
|
-
totalFromAmountUsd?: string;
|
|
233
|
-
totalToAmountUsd?: string;
|
|
234
|
-
priceImpact?: string;
|
|
235
|
-
};
|
|
236
|
-
};
|
|
180
|
+
export type FeeData = Infer<typeof FeeDataSchema>;
|
|
181
|
+
export type Quote = Infer<typeof QuoteSchema>;
|
|
182
|
+
export type TxData = Infer<typeof TxDataSchema>;
|
|
237
183
|
/**
|
|
238
184
|
* This is the type for the quote response from the bridge-api
|
|
239
185
|
* TxDataType can be overriden to be a string when the quote is non-evm
|
|
240
186
|
*/
|
|
241
|
-
export type QuoteResponse<
|
|
242
|
-
|
|
243
|
-
approval?:
|
|
244
|
-
trade: TradeType;
|
|
245
|
-
estimatedProcessingTimeInSeconds: number;
|
|
187
|
+
export type QuoteResponse<TxDataType = TxData> = Infer<typeof QuoteResponseSchema> & {
|
|
188
|
+
trade: TxDataType;
|
|
189
|
+
approval?: TxData;
|
|
246
190
|
};
|
|
247
191
|
export declare enum ChainId {
|
|
248
192
|
ETH = 1,
|
|
@@ -256,29 +200,7 @@ export declare enum ChainId {
|
|
|
256
200
|
LINEA = 59144,
|
|
257
201
|
SOLANA = 1151111081099710
|
|
258
202
|
}
|
|
259
|
-
export
|
|
260
|
-
METABRIDGE = "metabridge",
|
|
261
|
-
REFUEL = "refuel"
|
|
262
|
-
}
|
|
263
|
-
export type FeeData = {
|
|
264
|
-
amount: string;
|
|
265
|
-
asset: BridgeAsset;
|
|
266
|
-
};
|
|
267
|
-
export type TxData = {
|
|
268
|
-
chainId: ChainId;
|
|
269
|
-
to: string;
|
|
270
|
-
from: string;
|
|
271
|
-
value: string;
|
|
272
|
-
data: string;
|
|
273
|
-
gasLimit: number | null;
|
|
274
|
-
};
|
|
275
|
-
export type FeatureFlagsPlatformConfig = {
|
|
276
|
-
minimumVersion: string;
|
|
277
|
-
refreshRate: number;
|
|
278
|
-
maxRefreshCount: number;
|
|
279
|
-
support: boolean;
|
|
280
|
-
chains: Record<CaipChainId, ChainConfiguration>;
|
|
281
|
-
};
|
|
203
|
+
export type FeatureFlagsPlatformConfig = Infer<typeof PlatformConfigSchema>;
|
|
282
204
|
export declare enum RequestStatus {
|
|
283
205
|
LOADING = 0,
|
|
284
206
|
FETCHED = 1,
|
package/dist/types.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.mts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oDAAoD,EAAE,sCAAsC;AAC1G,OAAO,KAAK,EACV,oBAAoB,EACpB,6CAA6C,EAC7C,kCAAkC,EACnC,qCAAqC;AACtC,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,yCAAyC,EAAE,iDAAiD;AAC1G,OAAO,KAAK,EAAE,iBAAiB,EAAE,oCAAoC;AACrE,OAAO,KAAK,EACV,aAAa,EACb,WAAW,EACX,aAAa,EACb,WAAW,EACX,GAAG,EACJ,wBAAwB;AAEzB,OAAO,KAAK,EAAE,gBAAgB,EAAE,gCAA4B;AAC5D,OAAO,KAAK,EAAE,sBAAsB,EAAE,+BAA2B;
|
|
1
|
+
{"version":3,"file":"types.d.mts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oDAAoD,EAAE,sCAAsC;AAC1G,OAAO,KAAK,EACV,oBAAoB,EACpB,6CAA6C,EAC7C,kCAAkC,EACnC,qCAAqC;AACtC,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,yCAAyC,EAAE,iDAAiD;AAC1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,CAAC;AAElC;;GAEG;AACH,MAAM,MAAM,yBAAyB,GAAG,mBAAmB,CACzD,OAAO,sBAAsB,EAC7B,uBAAuB,GAAG,cAAc,EACxC,sBAAsB,GAAG,aAAa,EACtC,cAAc,CAAC,MAAM,CAAC,EACtB,aAAa,CAAC,MAAM,CAAC,CACtB,CAAC"}
|
package/dist/types.mjs
CHANGED
|
@@ -30,12 +30,6 @@ export var StatusTypes;
|
|
|
30
30
|
StatusTypes["PENDING"] = "PENDING";
|
|
31
31
|
StatusTypes["COMPLETE"] = "COMPLETE";
|
|
32
32
|
})(StatusTypes || (StatusTypes = {}));
|
|
33
|
-
export var ActionTypes;
|
|
34
|
-
(function (ActionTypes) {
|
|
35
|
-
ActionTypes["BRIDGE"] = "bridge";
|
|
36
|
-
ActionTypes["SWAP"] = "swap";
|
|
37
|
-
ActionTypes["REFUEL"] = "refuel";
|
|
38
|
-
})(ActionTypes || (ActionTypes = {}));
|
|
39
33
|
export var ChainId;
|
|
40
34
|
(function (ChainId) {
|
|
41
35
|
ChainId[ChainId["ETH"] = 1] = "ETH";
|
|
@@ -49,11 +43,6 @@ export var ChainId;
|
|
|
49
43
|
ChainId[ChainId["LINEA"] = 59144] = "LINEA";
|
|
50
44
|
ChainId[ChainId["SOLANA"] = 1151111081099710] = "SOLANA";
|
|
51
45
|
})(ChainId || (ChainId = {}));
|
|
52
|
-
export var FeeType;
|
|
53
|
-
(function (FeeType) {
|
|
54
|
-
FeeType["METABRIDGE"] = "metabridge";
|
|
55
|
-
FeeType["REFUEL"] = "refuel";
|
|
56
|
-
})(FeeType || (FeeType = {}));
|
|
57
46
|
export var RequestStatus;
|
|
58
47
|
(function (RequestStatus) {
|
|
59
48
|
RequestStatus[RequestStatus["LOADING"] = 0] = "LOADING";
|
package/dist/types.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.mjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AA4CA;;GAEG;AACH,MA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AAb,aAAa,QAIxB;AACD,MAAM,CAAN,IAAY,gBAGX;AAHD,WAAY,gBAAgB;IAC1B,6DAAyC,CAAA;IACzC,0EAAsD,CAAA;AACxD,CAAC,EAHW,gBAAgB,KAAhB,gBAAgB,QAG3B;AACD,MAAM,CAAN,IAAY,sBAMX;AAND,WAAY,sBAAsB;IAChC,8EAAoD,CAAA;IACpD,oDAA0B,CAAA;IAC1B,gFAAsD,CAAA;IACtD,iFAAuD,CAAA;IACvD,0EAAgD,CAAA;AAClD,CAAC,EANW,sBAAsB,KAAtB,sBAAsB,QAMjC","sourcesContent":["import type { AccountsControllerGetSelectedMultichainAccountAction } from '@metamask/accounts-controller';\nimport type {\n GetCurrencyRateState,\n MultichainAssetsRatesControllerGetStateAction,\n TokenRatesControllerGetStateAction,\n} from '@metamask/assets-controllers';\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 { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\nimport type {\n CaipAccountId,\n CaipAssetId,\n CaipAssetType,\n CaipChainId,\n Hex,\n} from '@metamask/utils';\n\nimport type { BridgeController } from './bridge-controller';\nimport type { BRIDGE_CONTROLLER_NAME } from './constants/bridge';\n\n/**\n * Additional options accepted by the extension's fetchWithCache function\n */\ntype FetchWithCacheOptions = {\n cacheOptions?: {\n cacheRefreshTime: number;\n };\n functionName?: string;\n};\n\nexport type FetchFunction = (\n input: RequestInfo | URL,\n init?: RequestInit & FetchWithCacheOptions,\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 */\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 refreshRate?: number;\n topAssets?: string[];\n isUnifiedUIEnabled?: boolean;\n isSnapConfirmationEnabled?: boolean;\n};\n\nexport type L1GasFees = {\n l1GasFeesInHexWei?: string; // l1 fees for approval and trade in hex wei, appended by BridgeController.#appendL1GasFees\n};\n\nexport type SolanaFees = {\n solanaFeesInLamports?: string; // solana fees in lamports, appended by BridgeController.#appendSolanaFees\n};\n\n/**\n * The types of values for the token amount and its values when converted to the user's selected currency and USD\n */\nexport type TokenAmountValues = {\n /**\n * The amount of the token\n *\n * @example \"1000000000000000000\"\n */\n amount: string;\n /**\n * The amount of the token in the user's selected currency\n *\n * @example \"4.55\"\n */\n valueInCurrency: string | null;\n /**\n * The amount of the token in USD\n *\n * @example \"1.234\"\n */\n usd: string | null;\n};\n\n/**\n * Asset exchange rate values for a given chain and address\n */\nexport type ExchangeRate = { exchangeRate?: string; usdExchangeRate?: string };\n\n/**\n * Values derived from the quote response\n */\nexport type QuoteMetadata = {\n gasFee: TokenAmountValues;\n totalNetworkFee: TokenAmountValues; // estimatedGasFees + relayerFees\n totalMaxNetworkFee: TokenAmountValues; // maxGasFees + relayerFees\n toTokenAmount: TokenAmountValues;\n adjustedReturn: Omit<TokenAmountValues, 'amount'>; // destTokenAmount - totalNetworkFee\n sentAmount: TokenAmountValues; // srcTokenAmount + metabridgeFee\n swapRate: string; // destTokenAmount / sentAmount\n cost: Omit<TokenAmountValues, 'amount'>; // sentAmount - adjustedReturn\n};\n\n/**\n * Sort order set by the user\n */\nexport enum SortOrder {\n COST_ASC = 'cost_ascending',\n ETA_ASC = 'time_descending',\n}\n\n/**\n * This is the interface for the asset object returned by the bridge-api\n * This type is used in the QuoteResponse and in the fetchBridgeTokens response\n */\nexport type BridgeAsset = {\n /**\n * The chainId of the token\n */\n chainId: ChainId;\n /**\n * An address that the metaswap-api recognizes as the default token\n */\n address: string;\n /**\n * The symbol of token object\n */\n symbol: string;\n /**\n * The name for the network\n */\n name: string;\n /**\n * Number of digits after decimal point\n */\n decimals: number;\n icon?: string;\n /**\n * URL for token icon\n */\n iconUrl?: string;\n /**\n * The assetId of the token\n */\n assetId: CaipAssetType;\n};\n\n/**\n * This is the interface for the token object used in the extension client\n * In addition to the {@link BridgeAsset} fields, it includes balance information\n */\nexport type BridgeToken = {\n address: string;\n symbol: string;\n image: string;\n decimals: number;\n chainId: number | Hex | ChainId | CaipChainId;\n balance: string; // raw balance\n // TODO deprecate this field and use balance instead\n string: string | undefined; // normalized balance as a stringified number\n tokenFiatAmount?: number | null;\n occurrences?: number;\n};\n\ntype DecimalChainId = string;\nexport type GasMultiplierByChainId = Record<DecimalChainId, number>;\n\ntype FeatureFlagResponsePlatformConfig = {\n refreshRate: number;\n maxRefreshCount: number;\n support: boolean;\n chains: Record<string, ChainConfiguration>;\n};\n\nexport type FeatureFlagResponse = FeatureFlagResponsePlatformConfig;\n\n/**\n * This is the interface for the quote request sent to the bridge-api\n * and should only be used by the fetchBridgeQuotes utility function\n * Components and redux stores should use the {@link GenericQuoteRequest} type\n */\nexport type QuoteRequest<\n ChainIdType = ChainId | number,\n TokenAddressType = string,\n WalletAddressType = string,\n> = {\n walletAddress: WalletAddressType;\n destWalletAddress?: WalletAddressType;\n srcChainId: ChainIdType;\n destChainId: ChainIdType;\n srcTokenAddress: TokenAddressType;\n destTokenAddress: TokenAddressType;\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 enum StatusTypes {\n UNKNOWN = 'UNKNOWN',\n FAILED = 'FAILED',\n PENDING = 'PENDING',\n COMPLETE = 'COMPLETE',\n}\n\n/**\n * These are types that components pass in. Since data is a mix of types when coming from the redux store, we need to use a generic type that can cover all the types.\n * Payloads with this type are transformed into QuoteRequest by fetchBridgeQuotes right before fetching quotes\n */\nexport type GenericQuoteRequest = QuoteRequest<\n Hex | CaipChainId | string | number, // chainIds\n Hex | CaipAssetId | string, // assetIds/addresses\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-arguments\n Hex | CaipAccountId | string // accountIds/addresses\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 priceData?: {\n totalFromAmountUsd?: string;\n totalToAmountUsd?: string;\n priceImpact?: string;\n };\n};\n\n/**\n * This is the type for the quote response from the bridge-api\n * TxDataType can be overriden to be a string when the quote is non-evm\n */\nexport type QuoteResponse<TradeType = TxData, ApprovalType = TxData | null> = {\n quote: Quote;\n approval?: ApprovalType;\n trade: TradeType;\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 SOLANA = 1151111081099710,\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};\n\nexport type FeatureFlagsPlatformConfig = {\n minimumVersion: string;\n refreshRate: number;\n maxRefreshCount: number;\n support: boolean;\n chains: Record<CaipChainId, 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_CHAIN_INTERVAL_LENGTH = 'setChainIntervalLength',\n RESET_STATE = 'resetState',\n GET_BRIDGE_ERC20_ALLOWANCE = 'getBridgeERC20Allowance',\n TRACK_METAMETRICS_EVENT = 'trackUnifiedSwapBridgeEvent',\n STOP_POLLING_FOR_QUOTES = 'stopPollingForQuotes',\n}\n\nexport type BridgeControllerState = {\n quoteRequest: Partial<GenericQuoteRequest>;\n quotes: (QuoteResponse & L1GasFees & SolanaFees)[];\n quotesInitialLoadTime: number | null;\n quotesLastFetched: number | null;\n quotesLoadingStatus: RequestStatus | null;\n quoteFetchError: string | null;\n quotesRefreshCount: number;\n /**\n * Asset exchange rates for EVM and multichain assets that are not indexed by the assets controllers\n */\n assetExchangeRates: Record<CaipAssetType, ExchangeRate>;\n /**\n * When the src token is SOL, this needs to be subtracted from their balance to determine\n * the max amount that can be sent.\n */\n minimumBalanceForRentExemptionInLamports: string | null;\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_CHAIN_INTERVAL_LENGTH>\n | BridgeControllerAction<BridgeBackgroundAction.RESET_STATE>\n | BridgeControllerAction<BridgeBackgroundAction.GET_BRIDGE_ERC20_ALLOWANCE>\n | BridgeControllerAction<BridgeBackgroundAction.TRACK_METAMETRICS_EVENT>\n | BridgeControllerAction<BridgeBackgroundAction.STOP_POLLING_FOR_QUOTES>\n | BridgeControllerAction<BridgeUserAction.UPDATE_QUOTE_PARAMS>;\n\nexport type BridgeControllerEvents = ControllerStateChangeEvent<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerState\n>;\n\nexport type AllowedActions =\n | AccountsControllerGetSelectedMultichainAccountAction\n | GetCurrencyRateState\n | TokenRatesControllerGetStateAction\n | MultichainAssetsRatesControllerGetStateAction\n | HandleSnapRequest\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | RemoteFeatureFlagControllerGetStateAction;\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"]}
|
|
1
|
+
{"version":3,"file":"types.mjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAwDA;;GAEG;AACH,MAAM,CAAN,IAAY,SAYX;AAZD,WAAY,SAAS;IACnB,4DAA4D;IAC5D,8BAAiB,CAAA;IACjB,qBAAqB;IACrB,4BAAe,CAAA;IACf,kCAAkC;IAClC,wBAAW,CAAA;IACX;;;OAGG;IACH,gCAAmB,CAAA;AACrB,CAAC,EAZW,SAAS,KAAT,SAAS,QAYpB;AAsED;;GAEG;AACH,MAAM,CAAN,IAAY,SAGX;AAHD,WAAY,SAAS;IACnB,wCAA2B,CAAA;IAC3B,wCAA2B,CAAA;AAC7B,CAAC,EAHW,SAAS,KAAT,SAAS,QAGpB;AAgED,MAAM,CAAN,IAAY,WAKX;AALD,WAAY,WAAW;IACrB,kCAAmB,CAAA;IACnB,gCAAiB,CAAA;IACjB,kCAAmB,CAAA;IACnB,oCAAqB,CAAA;AACvB,CAAC,EALW,WAAW,KAAX,WAAW,QAKtB;AAmCD,MAAM,CAAN,IAAY,OAWX;AAXD,WAAY,OAAO;IACjB,mCAAO,CAAA;IACP,8CAAa,CAAA;IACb,oCAAQ,CAAA;IACR,6CAAa,CAAA;IACb,2CAAY,CAAA;IACZ,wCAAW,CAAA;IACX,iDAAgB,CAAA;IAChB,mDAAiB,CAAA;IACjB,2CAAa,CAAA;IACb,wDAAyB,CAAA;AAC3B,CAAC,EAXW,OAAO,KAAP,OAAO,QAWlB;AAID,MAAM,CAAN,IAAY,aAIX;AAJD,WAAY,aAAa;IACvB,uDAAO,CAAA;IACP,uDAAO,CAAA;IACP,mDAAK,CAAA;AACP,CAAC,EAJW,aAAa,KAAb,aAAa,QAIxB;AACD,MAAM,CAAN,IAAY,gBAGX;AAHD,WAAY,gBAAgB;IAC1B,6DAAyC,CAAA;IACzC,0EAAsD,CAAA;AACxD,CAAC,EAHW,gBAAgB,KAAhB,gBAAgB,QAG3B;AACD,MAAM,CAAN,IAAY,sBAMX;AAND,WAAY,sBAAsB;IAChC,8EAAoD,CAAA;IACpD,oDAA0B,CAAA;IAC1B,gFAAsD,CAAA;IACtD,iFAAuD,CAAA;IACvD,0EAAgD,CAAA;AAClD,CAAC,EANW,sBAAsB,KAAtB,sBAAsB,QAMjC","sourcesContent":["import type { AccountsControllerGetSelectedMultichainAccountAction } from '@metamask/accounts-controller';\nimport type {\n GetCurrencyRateState,\n MultichainAssetsRatesControllerGetStateAction,\n TokenRatesControllerGetStateAction,\n} from '@metamask/assets-controllers';\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 { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\nimport type { Infer } from '@metamask/superstruct';\nimport type {\n CaipAccountId,\n CaipAssetId,\n CaipAssetType,\n CaipChainId,\n Hex,\n} from '@metamask/utils';\n\nimport type { BridgeController } from './bridge-controller';\nimport type { BRIDGE_CONTROLLER_NAME } from './constants/bridge';\nimport type {\n BridgeAssetSchema,\n ChainConfigurationSchema,\n FeeDataSchema,\n PlatformConfigSchema,\n ProtocolSchema,\n QuoteResponseSchema,\n QuoteSchema,\n StepSchema,\n TxDataSchema,\n} from './utils/validators';\n\n/**\n * Additional options accepted by the extension's fetchWithCache function\n */\ntype FetchWithCacheOptions = {\n cacheOptions?: {\n cacheRefreshTime: number;\n };\n functionName?: string;\n};\n\nexport type FetchFunction = (\n input: RequestInfo | URL,\n init?: RequestInit & FetchWithCacheOptions,\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 */\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 = Infer<typeof ChainConfigurationSchema>;\n\nexport type L1GasFees = {\n l1GasFeesInHexWei?: string; // l1 fees for approval and trade in hex wei, appended by BridgeController.#appendL1GasFees\n};\n\nexport type SolanaFees = {\n solanaFeesInLamports?: string; // solana fees in lamports, appended by BridgeController.#appendSolanaFees\n};\n\n/**\n * The types of values for the token amount and its values when converted to the user's selected currency and USD\n */\nexport type TokenAmountValues = {\n /**\n * The amount of the token\n *\n * @example \"1000000000000000000\"\n */\n amount: string;\n /**\n * The amount of the token in the user's selected currency\n *\n * @example \"4.55\"\n */\n valueInCurrency: string | null;\n /**\n * The amount of the token in USD\n *\n * @example \"1.234\"\n */\n usd: string | null;\n};\n\n/**\n * Asset exchange rate values for a given chain and address\n */\nexport type ExchangeRate = { exchangeRate?: string; usdExchangeRate?: string };\n\n/**\n * Values derived from the quote response\n */\nexport type QuoteMetadata = {\n /**\n * If gas is included, this is the value of the src or dest token that was used to pay for the gas\n */\n includedTxFees?: TokenAmountValues | null;\n gasFee: TokenAmountValues;\n totalNetworkFee: TokenAmountValues; // estimatedGasFees + relayerFees\n totalMaxNetworkFee: TokenAmountValues; // maxGasFees + relayerFees\n /**\n * The amount that the user will receive (destTokenAmount)\n */\n toTokenAmount: TokenAmountValues;\n /**\n * If gas is included: toTokenAmount\n * Otherwise: toTokenAmount - totalNetworkFee\n */\n adjustedReturn: Omit<TokenAmountValues, 'amount'>;\n /**\n * The amount that the user will send, including fees\n * srcTokenAmount + metabridgeFee + txFee\n */\n sentAmount: TokenAmountValues;\n swapRate: string; // destTokenAmount / sentAmount\n cost: Omit<TokenAmountValues, 'amount'>; // sentAmount - adjustedReturn\n};\n\n/**\n * Sort order set by the user\n */\nexport enum SortOrder {\n COST_ASC = 'cost_ascending',\n ETA_ASC = 'time_descending',\n}\n\n/**\n * This is the interface for the asset object returned by the bridge-api\n * This type is used in the QuoteResponse and in the fetchBridgeTokens response\n */\nexport type BridgeAsset = Infer<typeof BridgeAssetSchema>;\n\n/**\n * This is the interface for the token object used in the extension client\n * In addition to the {@link BridgeAsset} fields, it includes balance information\n */\nexport type BridgeToken = {\n address: string;\n symbol: string;\n image: string;\n decimals: number;\n chainId: number | Hex | ChainId | CaipChainId;\n balance: string; // raw balance\n // TODO deprecate this field and use balance instead\n string: string | undefined; // normalized balance as a stringified number\n tokenFiatAmount?: number | null;\n occurrences?: number;\n};\n\ntype DecimalChainId = string;\nexport type GasMultiplierByChainId = Record<DecimalChainId, number>;\n\nexport type FeatureFlagResponse = Infer<typeof PlatformConfigSchema>;\n\n/**\n * This is the interface for the quote request sent to the bridge-api\n * and should only be used by the fetchBridgeQuotes utility function\n * Components and redux stores should use the {@link GenericQuoteRequest} type\n */\nexport type QuoteRequest<\n ChainIdType = ChainId | number,\n TokenAddressType = string,\n WalletAddressType = string,\n> = {\n walletAddress: WalletAddressType;\n destWalletAddress?: WalletAddressType;\n srcChainId: ChainIdType;\n destChainId: ChainIdType;\n srcTokenAddress: TokenAddressType;\n destTokenAddress: TokenAddressType;\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 * Whether the response should include gasless swap quotes\n * This should be true if the user has opted in to STX on the client\n * and the current network has STX support\n */\n gasIncluded: boolean;\n};\n\nexport enum StatusTypes {\n UNKNOWN = 'UNKNOWN',\n FAILED = 'FAILED',\n PENDING = 'PENDING',\n COMPLETE = 'COMPLETE',\n}\n\n/**\n * These are types that components pass in. Since data is a mix of types when coming from the redux store, we need to use a generic type that can cover all the types.\n * Payloads with this type are transformed into QuoteRequest by fetchBridgeQuotes right before fetching quotes\n */\nexport type GenericQuoteRequest = QuoteRequest<\n Hex | CaipChainId | string | number, // chainIds\n Hex | CaipAssetId | string, // assetIds/addresses\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-arguments\n Hex | CaipAccountId | string // accountIds/addresses\n>;\n\nexport type Protocol = Infer<typeof ProtocolSchema>;\n\nexport type Step = Infer<typeof StepSchema>;\n\nexport type RefuelData = Step;\n\nexport type FeeData = Infer<typeof FeeDataSchema>;\n\nexport type Quote = Infer<typeof QuoteSchema>;\n\nexport type TxData = Infer<typeof TxDataSchema>;\n/**\n * This is the type for the quote response from the bridge-api\n * TxDataType can be overriden to be a string when the quote is non-evm\n */\nexport type QuoteResponse<TxDataType = TxData> = Infer<\n typeof QuoteResponseSchema\n> & {\n trade: TxDataType;\n approval?: TxData;\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 SOLANA = 1151111081099710,\n}\n\nexport type FeatureFlagsPlatformConfig = Infer<typeof PlatformConfigSchema>;\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_CHAIN_INTERVAL_LENGTH = 'setChainIntervalLength',\n RESET_STATE = 'resetState',\n GET_BRIDGE_ERC20_ALLOWANCE = 'getBridgeERC20Allowance',\n TRACK_METAMETRICS_EVENT = 'trackUnifiedSwapBridgeEvent',\n STOP_POLLING_FOR_QUOTES = 'stopPollingForQuotes',\n}\n\nexport type BridgeControllerState = {\n quoteRequest: Partial<GenericQuoteRequest>;\n quotes: (QuoteResponse & L1GasFees & SolanaFees)[];\n quotesInitialLoadTime: number | null;\n quotesLastFetched: number | null;\n quotesLoadingStatus: RequestStatus | null;\n quoteFetchError: string | null;\n quotesRefreshCount: number;\n /**\n * Asset exchange rates for EVM and multichain assets that are not indexed by the assets controllers\n */\n assetExchangeRates: Record<CaipAssetType, ExchangeRate>;\n /**\n * When the src token is SOL, this needs to be subtracted from their balance to determine\n * the max amount that can be sent.\n */\n minimumBalanceForRentExemptionInLamports: string | null;\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_CHAIN_INTERVAL_LENGTH>\n | BridgeControllerAction<BridgeBackgroundAction.RESET_STATE>\n | BridgeControllerAction<BridgeBackgroundAction.GET_BRIDGE_ERC20_ALLOWANCE>\n | BridgeControllerAction<BridgeBackgroundAction.TRACK_METAMETRICS_EVENT>\n | BridgeControllerAction<BridgeBackgroundAction.STOP_POLLING_FOR_QUOTES>\n | BridgeControllerAction<BridgeUserAction.UPDATE_QUOTE_PARAMS>;\n\nexport type BridgeControllerEvents = ControllerStateChangeEvent<\n typeof BRIDGE_CONTROLLER_NAME,\n BridgeControllerState\n>;\n\nexport type AllowedActions =\n | AccountsControllerGetSelectedMultichainAccountAction\n | GetCurrencyRateState\n | TokenRatesControllerGetStateAction\n | MultichainAssetsRatesControllerGetStateAction\n | HandleSnapRequest\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | RemoteFeatureFlagControllerGetStateAction;\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"]}
|
|
@@ -2,10 +2,10 @@ import type { RemoteFeatureFlagControllerState } from "@metamask/remote-feature-
|
|
|
2
2
|
import type { FeatureFlagsPlatformConfig } from "../types.cjs";
|
|
3
3
|
export declare const formatFeatureFlags: (bridgeFeatureFlags: FeatureFlagsPlatformConfig) => {
|
|
4
4
|
chains: {};
|
|
5
|
-
|
|
5
|
+
support: boolean;
|
|
6
6
|
refreshRate: number;
|
|
7
|
+
minimumVersion: string;
|
|
7
8
|
maxRefreshCount: number;
|
|
8
|
-
support: boolean;
|
|
9
9
|
};
|
|
10
10
|
export declare const processFeatureFlags: (bridgeFeatureFlags: unknown) => FeatureFlagsPlatformConfig;
|
|
11
11
|
/**
|
|
@@ -2,10 +2,10 @@ import type { RemoteFeatureFlagControllerState } from "@metamask/remote-feature-
|
|
|
2
2
|
import type { FeatureFlagsPlatformConfig } from "../types.mjs";
|
|
3
3
|
export declare const formatFeatureFlags: (bridgeFeatureFlags: FeatureFlagsPlatformConfig) => {
|
|
4
4
|
chains: {};
|
|
5
|
-
|
|
5
|
+
support: boolean;
|
|
6
6
|
refreshRate: number;
|
|
7
|
+
minimumVersion: string;
|
|
7
8
|
maxRefreshCount: number;
|
|
8
|
-
support: boolean;
|
|
9
9
|
};
|
|
10
10
|
export declare const processFeatureFlags: (bridgeFeatureFlags: unknown) => FeatureFlagsPlatformConfig;
|
|
11
11
|
/**
|
package/dist/utils/fetch.cjs
CHANGED
|
@@ -63,6 +63,7 @@ async function fetchBridgeQuotes(request, signal, clientId, fetchFn, bridgeApiBa
|
|
|
63
63
|
srcTokenAmount: request.srcTokenAmount,
|
|
64
64
|
insufficientBal: Boolean(request.insufficientBal),
|
|
65
65
|
resetApproval: Boolean(request.resetApproval),
|
|
66
|
+
gasIncluded: Boolean(request.gasIncluded),
|
|
66
67
|
};
|
|
67
68
|
if (request.slippage !== undefined) {
|
|
68
69
|
normalizedRequest.slippage = request.slippage;
|
package/dist/utils/fetch.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.cjs","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":";;;AAAA,uDAAoD;AAEpD,2CAA2C;AAE3C,2DAG2B;AAC3B,iDAA+E;AAS/E,MAAM,yBAAyB,GAAG,EAAE,GAAG,gBAAQ,CAAC,MAAM,CAAC;AAEhD,MAAM,iBAAiB,GAAG,CAAC,QAAgB,EAAE,EAAE,CAAC,CAAC;IACtD,aAAa,EAAE,QAAQ;CACxB,CAAC,CAAC;AAFU,QAAA,iBAAiB,qBAE3B;AAEH;;;;;;;;GAQG;AACI,KAAK,UAAU,iBAAiB,CACrC,OAA0B,EAC1B,QAAgB,EAChB,OAAsB,EACtB,gBAAwB;IAExB,8BAA8B;IAC9B,MAAM,GAAG,GAAG,GAAG,gBAAgB,sBAAsB,IAAA,oCAAkB,EAAC,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AM,KAAK,WAAW,EAAE;gBACjC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,EAAE,eAAe,CAAC,EAAE,EAAE;oBAClE,MAAM,cAAc,GAAG,GAAG,CAAC,OAAwB,CAAC,CAAC;oBACrD,IAAI,CAAC,cAAc,EAAE;wBACnB,GAAG,CAAC,OAAwB,CAAC,GAAG,EAAE,CAAC;qBACpC;oBACD,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,EAAE;wBAC5D,GAAG,CAAC,OAAwB,CAAC,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;oBAClD,CAAC,CAAC,CAAC;gBACL,CAAC,CAAC,CAAC;aACJ;YACD,OAAO,GAAG,CAAC;QACb,CAAC,EACD,EAA2D,CAC5D,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC;AAnCW,QAAA,gBAAgB,oBAmC3B","sourcesContent":["import { StructError } from '@metamask/superstruct';\nimport type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';\nimport { Duration } from '@metamask/utils';\n\nimport {\n formatAddressToCaipReference,\n formatChainIdToDec,\n} from './caip-formatters';\nimport { validateQuoteResponse, validateSwapsTokenObject } from './validators';\nimport type {\n QuoteResponse,\n FetchFunction,\n GenericQuoteRequest,\n QuoteRequest,\n BridgeAsset,\n} from '../types';\n\nconst CACHE_REFRESH_TEN_MINUTES = 10 * Duration.Minute;\n\nexport const getClientIdHeader = (clientId: string) => ({\n 'X-Client-Id': clientId,\n});\n\n/**\n * Returns a list of enabled (unblocked) tokens\n *\n * @param chainId - The chain ID to fetch tokens for\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of enabled (unblocked) tokens\n */\nexport async function fetchBridgeTokens(\n chainId: Hex | CaipChainId,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<Record<string, BridgeAsset>> {\n // TODO make token api v2 call\n const url = `${bridgeApiBaseUrl}/getTokens?chainId=${formatChainIdToDec(chainId)}`;\n\n // TODO we will need to cache these. In Extension fetchWithCache is used. This is due to the following:\n // If we allow selecting dest networks which the user has not imported,\n // note that the Assets controller won't be able to provide tokens. In extension we fetch+cache the token list from bridge-api to handle this\n const tokens = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: CACHE_REFRESH_TEN_MINUTES },\n functionName: 'fetchBridgeTokens',\n });\n\n const transformedTokens: Record<string, BridgeAsset> = {};\n tokens.forEach((token: unknown) => {\n if (validateSwapsTokenObject(token)) {\n transformedTokens[token.address] = token;\n }\n });\n return transformedTokens;\n}\n\n/**\n * Converts the generic quote request to the type that the bridge-api expects\n * then fetches quotes from the bridge-api\n *\n * @param request - The quote request\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of bridge tx quotes\n */\nexport async function fetchBridgeQuotes(\n request: GenericQuoteRequest,\n signal: AbortSignal,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<QuoteResponse[]> {\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 };\n if (request.slippage !== undefined) {\n normalizedRequest.slippage = request.slippage;\n }\n\n const queryParams = new URLSearchParams();\n Object.entries(normalizedRequest).forEach(([key, value]) => {\n queryParams.append(key, value.toString());\n });\n const url = `${bridgeApiBaseUrl}/getQuote?${queryParams}`;\n const quotes: unknown[] = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n signal,\n cacheOptions: { cacheRefreshTime: 0 },\n functionName: 'fetchBridgeQuotes',\n });\n\n const validationFailuresByAggregator: {\n [aggregator: string]: Set<string>;\n } = {};\n const filteredQuotes = quotes.filter((quoteResponse: unknown) => {\n try {\n return validateQuoteResponse(quoteResponse);\n } catch (error) {\n if (error instanceof StructError) {\n error.failures().forEach(({ branch, path }) => {\n const aggregatorId = branch?.[0]?.quote?.bridgeId;\n if (!validationFailuresByAggregator[aggregatorId]) {\n validationFailuresByAggregator[aggregatorId] = new Set([]);\n }\n const pathString = path?.join('.') || 'unknown';\n validationFailuresByAggregator[aggregatorId].add(pathString);\n });\n }\n return false;\n }\n });\n\n if (Object.keys(validationFailuresByAggregator).length > 0) {\n console.error('Quote validation failed', validationFailuresByAggregator);\n }\n return filteredQuotes as QuoteResponse[];\n}\n\nconst fetchAssetPricesForCurrency = async (request: {\n currency: string;\n assetIds: Set<CaipAssetType>;\n clientId: string;\n fetchFn: FetchFunction;\n}): Promise<Record<CaipAssetType, { [currency: string]: string }>> => {\n const { currency, assetIds, clientId, fetchFn } = request;\n const validAssetIds = Array.from(assetIds).filter(Boolean);\n if (validAssetIds.length === 0) {\n return {};\n }\n\n const queryParams = new URLSearchParams({\n assetIds: validAssetIds.filter(Boolean).join(','),\n vsCurrency: currency,\n });\n const url = `https://price.api.cx.metamask.io/v3/spot-prices?${queryParams}`;\n const priceApiResponse = (await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: Number(Duration.Second * 30) },\n functionName: 'fetchAssetExchangeRates',\n })) as Record<CaipAssetType, { [currency: string]: number }>;\n\n if (!priceApiResponse || typeof priceApiResponse !== 'object') {\n return {};\n }\n\n return Object.entries(priceApiResponse).reduce(\n (acc, [assetId, currencyToPrice]) => {\n if (!currencyToPrice) {\n return acc;\n }\n if (!acc[assetId as CaipAssetType]) {\n acc[assetId as CaipAssetType] = {};\n }\n if (currencyToPrice[currency]) {\n acc[assetId as CaipAssetType][currency] =\n currencyToPrice[currency].toString();\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n};\n\n/**\n * Fetches the asset prices from the price API for multiple currencies\n *\n * @param request - The request object\n * @returns The asset prices by assetId\n */\nexport const fetchAssetPrices = async (\n request: {\n currencies: Set<string>;\n } & Omit<Parameters<typeof fetchAssetPricesForCurrency>[0], 'currency'>,\n): Promise<\n Record<CaipAssetType, { [currency: string]: string } | undefined>\n> => {\n const { currencies, ...args } = request;\n\n const combinedPrices = await Promise.allSettled(\n Array.from(currencies).map(\n async (currency) =>\n await fetchAssetPricesForCurrency({ ...args, currency }),\n ),\n ).then((priceApiResponse) => {\n return priceApiResponse.reduce(\n (acc, result) => {\n if (result.status === 'fulfilled') {\n Object.entries(result.value).forEach(([assetId, currencyToPrice]) => {\n const existingPrices = acc[assetId as CaipAssetType];\n if (!existingPrices) {\n acc[assetId as CaipAssetType] = {};\n }\n Object.entries(currencyToPrice).forEach(([currency, price]) => {\n acc[assetId as CaipAssetType][currency] = price;\n });\n });\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n });\n\n return combinedPrices;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"fetch.cjs","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":";;;AAAA,uDAAoD;AAEpD,2CAA2C;AAE3C,2DAG2B;AAC3B,iDAA+E;AAS/E,MAAM,yBAAyB,GAAG,EAAE,GAAG,gBAAQ,CAAC,MAAM,CAAC;AAEhD,MAAM,iBAAiB,GAAG,CAAC,QAAgB,EAAE,EAAE,CAAC,CAAC;IACtD,aAAa,EAAE,QA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,UAAU,CAAC,CAAC,GAAG,CACxB,KAAK,EAAE,QAAQ,EAAE,EAAE,CACjB,MAAM,2BAA2B,CAAC,EAAE,GAAG,IAAI,EAAE,QAAQ,EAAE,CAAC,CAC3D,CACF,CAAC,IAAI,CAAC,CAAC,gBAAgB,EAAE,EAAE;QAC1B,OAAO,gBAAgB,CAAC,MAAM,CAC5B,CAAC,GAAG,EAAE,MAAM,EAAE,EAAE;YACd,IAAI,MAAM,CAAC,MAAM,KAAK,WAAW,EAAE;gBACjC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,EAAE,eAAe,CAAC,EAAE,EAAE;oBAClE,MAAM,cAAc,GAAG,GAAG,CAAC,OAAwB,CAAC,CAAC;oBACrD,IAAI,CAAC,cAAc,EAAE;wBACnB,GAAG,CAAC,OAAwB,CAAC,GAAG,EAAE,CAAC;qBACpC;oBACD,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,EAAE;wBAC5D,GAAG,CAAC,OAAwB,CAAC,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;oBAClD,CAAC,CAAC,CAAC;gBACL,CAAC,CAAC,CAAC;aACJ;YACD,OAAO,GAAG,CAAC;QACb,CAAC,EACD,EAA2D,CAC5D,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC;AAnCW,QAAA,gBAAgB,oBAmC3B","sourcesContent":["import { StructError } from '@metamask/superstruct';\nimport type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';\nimport { Duration } from '@metamask/utils';\n\nimport {\n formatAddressToCaipReference,\n formatChainIdToDec,\n} from './caip-formatters';\nimport { validateQuoteResponse, validateSwapsTokenObject } from './validators';\nimport type {\n QuoteResponse,\n FetchFunction,\n GenericQuoteRequest,\n QuoteRequest,\n BridgeAsset,\n} from '../types';\n\nconst CACHE_REFRESH_TEN_MINUTES = 10 * Duration.Minute;\n\nexport const getClientIdHeader = (clientId: string) => ({\n 'X-Client-Id': clientId,\n});\n\n/**\n * Returns a list of enabled (unblocked) tokens\n *\n * @param chainId - The chain ID to fetch tokens for\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of enabled (unblocked) tokens\n */\nexport async function fetchBridgeTokens(\n chainId: Hex | CaipChainId,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<Record<string, BridgeAsset>> {\n // TODO make token api v2 call\n const url = `${bridgeApiBaseUrl}/getTokens?chainId=${formatChainIdToDec(chainId)}`;\n\n // TODO we will need to cache these. In Extension fetchWithCache is used. This is due to the following:\n // If we allow selecting dest networks which the user has not imported,\n // note that the Assets controller won't be able to provide tokens. In extension we fetch+cache the token list from bridge-api to handle this\n const tokens = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: CACHE_REFRESH_TEN_MINUTES },\n functionName: 'fetchBridgeTokens',\n });\n\n const transformedTokens: Record<string, BridgeAsset> = {};\n tokens.forEach((token: unknown) => {\n if (validateSwapsTokenObject(token)) {\n transformedTokens[token.address] = token;\n }\n });\n return transformedTokens;\n}\n\n/**\n * Converts the generic quote request to the type that the bridge-api expects\n * then fetches quotes from the bridge-api\n *\n * @param request - The quote request\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of bridge tx quotes\n */\nexport async function fetchBridgeQuotes(\n request: GenericQuoteRequest,\n signal: AbortSignal,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<QuoteResponse[]> {\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 };\n if (request.slippage !== undefined) {\n normalizedRequest.slippage = request.slippage;\n }\n\n const queryParams = new URLSearchParams();\n Object.entries(normalizedRequest).forEach(([key, value]) => {\n queryParams.append(key, value.toString());\n });\n const url = `${bridgeApiBaseUrl}/getQuote?${queryParams}`;\n const quotes: unknown[] = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n signal,\n cacheOptions: { cacheRefreshTime: 0 },\n functionName: 'fetchBridgeQuotes',\n });\n\n const validationFailuresByAggregator: {\n [aggregator: string]: Set<string>;\n } = {};\n const filteredQuotes = quotes.filter((quoteResponse: unknown) => {\n try {\n return validateQuoteResponse(quoteResponse);\n } catch (error) {\n if (error instanceof StructError) {\n error.failures().forEach(({ branch, path }) => {\n const aggregatorId = branch?.[0]?.quote?.bridgeId;\n if (!validationFailuresByAggregator[aggregatorId]) {\n validationFailuresByAggregator[aggregatorId] = new Set([]);\n }\n const pathString = path?.join('.') || 'unknown';\n validationFailuresByAggregator[aggregatorId].add(pathString);\n });\n }\n return false;\n }\n });\n\n if (Object.keys(validationFailuresByAggregator).length > 0) {\n console.error('Quote validation failed', validationFailuresByAggregator);\n }\n return filteredQuotes as QuoteResponse[];\n}\n\nconst fetchAssetPricesForCurrency = async (request: {\n currency: string;\n assetIds: Set<CaipAssetType>;\n clientId: string;\n fetchFn: FetchFunction;\n}): Promise<Record<CaipAssetType, { [currency: string]: string }>> => {\n const { currency, assetIds, clientId, fetchFn } = request;\n const validAssetIds = Array.from(assetIds).filter(Boolean);\n if (validAssetIds.length === 0) {\n return {};\n }\n\n const queryParams = new URLSearchParams({\n assetIds: validAssetIds.filter(Boolean).join(','),\n vsCurrency: currency,\n });\n const url = `https://price.api.cx.metamask.io/v3/spot-prices?${queryParams}`;\n const priceApiResponse = (await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: Number(Duration.Second * 30) },\n functionName: 'fetchAssetExchangeRates',\n })) as Record<CaipAssetType, { [currency: string]: number }>;\n\n if (!priceApiResponse || typeof priceApiResponse !== 'object') {\n return {};\n }\n\n return Object.entries(priceApiResponse).reduce(\n (acc, [assetId, currencyToPrice]) => {\n if (!currencyToPrice) {\n return acc;\n }\n if (!acc[assetId as CaipAssetType]) {\n acc[assetId as CaipAssetType] = {};\n }\n if (currencyToPrice[currency]) {\n acc[assetId as CaipAssetType][currency] =\n currencyToPrice[currency].toString();\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n};\n\n/**\n * Fetches the asset prices from the price API for multiple currencies\n *\n * @param request - The request object\n * @returns The asset prices by assetId\n */\nexport const fetchAssetPrices = async (\n request: {\n currencies: Set<string>;\n } & Omit<Parameters<typeof fetchAssetPricesForCurrency>[0], 'currency'>,\n): Promise<\n Record<CaipAssetType, { [currency: string]: string } | undefined>\n> => {\n const { currencies, ...args } = request;\n\n const combinedPrices = await Promise.allSettled(\n Array.from(currencies).map(\n async (currency) =>\n await fetchAssetPricesForCurrency({ ...args, currency }),\n ),\n ).then((priceApiResponse) => {\n return priceApiResponse.reduce(\n (acc, result) => {\n if (result.status === 'fulfilled') {\n Object.entries(result.value).forEach(([assetId, currencyToPrice]) => {\n const existingPrices = acc[assetId as CaipAssetType];\n if (!existingPrices) {\n acc[assetId as CaipAssetType] = {};\n }\n Object.entries(currencyToPrice).forEach(([currency, price]) => {\n acc[assetId as CaipAssetType][currency] = price;\n });\n });\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n });\n\n return combinedPrices;\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.d.cts","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,EAAE,wBAAwB;AAQvE,OAAO,KAAK,EACV,aAAa,EACb,aAAa,EACb,mBAAmB,EAEnB,WAAW,EACZ,qBAAiB;AAIlB,eAAO,MAAM,iBAAiB,aAAc,MAAM;;CAEhD,CAAC;AAEH;;;;;;;;GAQG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,GAAG,GAAG,WAAW,EAC1B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,aAAa,EACtB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAoBtC;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,mBAAmB,EAC5B,MAAM,EAAE,WAAW,EACnB,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,aAAa,EACtB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC,aAAa,EAAE,CAAC,
|
|
1
|
+
{"version":3,"file":"fetch.d.cts","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,EAAE,wBAAwB;AAQvE,OAAO,KAAK,EACV,aAAa,EACb,aAAa,EACb,mBAAmB,EAEnB,WAAW,EACZ,qBAAiB;AAIlB,eAAO,MAAM,iBAAiB,aAAc,MAAM;;CAEhD,CAAC;AAEH;;;;;;;;GAQG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,GAAG,GAAG,WAAW,EAC1B,QAAQ,EAAE,MAAM,EAChB,OAAO,EAAE,aAAa,EACtB,gBAAgB,EAAE,MAAM,GACvB,OAAO,CAAC,MAAM,CAAC,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/dist/utils/fetch.mjs
CHANGED
|
@@ -58,6 +58,7 @@ export async function fetchBridgeQuotes(request, signal, clientId, fetchFn, brid
|
|
|
58
58
|
srcTokenAmount: request.srcTokenAmount,
|
|
59
59
|
insufficientBal: Boolean(request.insufficientBal),
|
|
60
60
|
resetApproval: Boolean(request.resetApproval),
|
|
61
|
+
gasIncluded: Boolean(request.gasIncluded),
|
|
61
62
|
};
|
|
62
63
|
if (request.slippage !== undefined) {
|
|
63
64
|
normalizedRequest.slippage = request.slippage;
|
package/dist/utils/fetch.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.mjs","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,8BAA8B;AAEpD,OAAO,EAAE,QAAQ,EAAE,wBAAwB;AAE3C,OAAO,EACL,4BAA4B,EAC5B,kBAAkB,EACnB,8BAA0B;AAC3B,OAAO,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,yBAAqB;AAS/E,MAAM,yBAAyB,GAAG,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC;AAEvD,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,QAAgB,EAAE,EAAE,CAAC,CAAC;IACtD,aAAa,EAAE,QAAQ;CACxB,CAAC,CAAC;AAEH;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,OAA0B,EAC1B,QAAgB,EAChB,OAAsB,EACtB,gBAAwB;IAExB,8BAA8B;IAC9B,MAAM,GAAG,GAAG,GAAG,gBAAgB,sBAAsB,kBAAkB,CAAC,OAAO,CAAC,EAAE,CAAC;IAEnF,uGAAuG;IACvG,uEAAuE;IACvE,6IAA6I;IAC7I,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,GAAG,EAAE;QAChC,OAAO,EAAE,iBAAiB,CAAC,QAAQ,CAAC;QACpC,YAAY,EAAE,EAAE,gBAAgB,EAAE,yBAAy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BACD,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,EAAE;wBAC5D,GAAG,CAAC,OAAwB,CAAC,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;oBAClD,CAAC,CAAC,CAAC;gBACL,CAAC,CAAC,CAAC;aACJ;YACD,OAAO,GAAG,CAAC;QACb,CAAC,EACD,EAA2D,CAC5D,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC","sourcesContent":["import { StructError } from '@metamask/superstruct';\nimport type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';\nimport { Duration } from '@metamask/utils';\n\nimport {\n formatAddressToCaipReference,\n formatChainIdToDec,\n} from './caip-formatters';\nimport { validateQuoteResponse, validateSwapsTokenObject } from './validators';\nimport type {\n QuoteResponse,\n FetchFunction,\n GenericQuoteRequest,\n QuoteRequest,\n BridgeAsset,\n} from '../types';\n\nconst CACHE_REFRESH_TEN_MINUTES = 10 * Duration.Minute;\n\nexport const getClientIdHeader = (clientId: string) => ({\n 'X-Client-Id': clientId,\n});\n\n/**\n * Returns a list of enabled (unblocked) tokens\n *\n * @param chainId - The chain ID to fetch tokens for\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of enabled (unblocked) tokens\n */\nexport async function fetchBridgeTokens(\n chainId: Hex | CaipChainId,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<Record<string, BridgeAsset>> {\n // TODO make token api v2 call\n const url = `${bridgeApiBaseUrl}/getTokens?chainId=${formatChainIdToDec(chainId)}`;\n\n // TODO we will need to cache these. In Extension fetchWithCache is used. This is due to the following:\n // If we allow selecting dest networks which the user has not imported,\n // note that the Assets controller won't be able to provide tokens. In extension we fetch+cache the token list from bridge-api to handle this\n const tokens = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: CACHE_REFRESH_TEN_MINUTES },\n functionName: 'fetchBridgeTokens',\n });\n\n const transformedTokens: Record<string, BridgeAsset> = {};\n tokens.forEach((token: unknown) => {\n if (validateSwapsTokenObject(token)) {\n transformedTokens[token.address] = token;\n }\n });\n return transformedTokens;\n}\n\n/**\n * Converts the generic quote request to the type that the bridge-api expects\n * then fetches quotes from the bridge-api\n *\n * @param request - The quote request\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of bridge tx quotes\n */\nexport async function fetchBridgeQuotes(\n request: GenericQuoteRequest,\n signal: AbortSignal,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<QuoteResponse[]> {\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 };\n if (request.slippage !== undefined) {\n normalizedRequest.slippage = request.slippage;\n }\n\n const queryParams = new URLSearchParams();\n Object.entries(normalizedRequest).forEach(([key, value]) => {\n queryParams.append(key, value.toString());\n });\n const url = `${bridgeApiBaseUrl}/getQuote?${queryParams}`;\n const quotes: unknown[] = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n signal,\n cacheOptions: { cacheRefreshTime: 0 },\n functionName: 'fetchBridgeQuotes',\n });\n\n const validationFailuresByAggregator: {\n [aggregator: string]: Set<string>;\n } = {};\n const filteredQuotes = quotes.filter((quoteResponse: unknown) => {\n try {\n return validateQuoteResponse(quoteResponse);\n } catch (error) {\n if (error instanceof StructError) {\n error.failures().forEach(({ branch, path }) => {\n const aggregatorId = branch?.[0]?.quote?.bridgeId;\n if (!validationFailuresByAggregator[aggregatorId]) {\n validationFailuresByAggregator[aggregatorId] = new Set([]);\n }\n const pathString = path?.join('.') || 'unknown';\n validationFailuresByAggregator[aggregatorId].add(pathString);\n });\n }\n return false;\n }\n });\n\n if (Object.keys(validationFailuresByAggregator).length > 0) {\n console.error('Quote validation failed', validationFailuresByAggregator);\n }\n return filteredQuotes as QuoteResponse[];\n}\n\nconst fetchAssetPricesForCurrency = async (request: {\n currency: string;\n assetIds: Set<CaipAssetType>;\n clientId: string;\n fetchFn: FetchFunction;\n}): Promise<Record<CaipAssetType, { [currency: string]: string }>> => {\n const { currency, assetIds, clientId, fetchFn } = request;\n const validAssetIds = Array.from(assetIds).filter(Boolean);\n if (validAssetIds.length === 0) {\n return {};\n }\n\n const queryParams = new URLSearchParams({\n assetIds: validAssetIds.filter(Boolean).join(','),\n vsCurrency: currency,\n });\n const url = `https://price.api.cx.metamask.io/v3/spot-prices?${queryParams}`;\n const priceApiResponse = (await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: Number(Duration.Second * 30) },\n functionName: 'fetchAssetExchangeRates',\n })) as Record<CaipAssetType, { [currency: string]: number }>;\n\n if (!priceApiResponse || typeof priceApiResponse !== 'object') {\n return {};\n }\n\n return Object.entries(priceApiResponse).reduce(\n (acc, [assetId, currencyToPrice]) => {\n if (!currencyToPrice) {\n return acc;\n }\n if (!acc[assetId as CaipAssetType]) {\n acc[assetId as CaipAssetType] = {};\n }\n if (currencyToPrice[currency]) {\n acc[assetId as CaipAssetType][currency] =\n currencyToPrice[currency].toString();\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n};\n\n/**\n * Fetches the asset prices from the price API for multiple currencies\n *\n * @param request - The request object\n * @returns The asset prices by assetId\n */\nexport const fetchAssetPrices = async (\n request: {\n currencies: Set<string>;\n } & Omit<Parameters<typeof fetchAssetPricesForCurrency>[0], 'currency'>,\n): Promise<\n Record<CaipAssetType, { [currency: string]: string } | undefined>\n> => {\n const { currencies, ...args } = request;\n\n const combinedPrices = await Promise.allSettled(\n Array.from(currencies).map(\n async (currency) =>\n await fetchAssetPricesForCurrency({ ...args, currency }),\n ),\n ).then((priceApiResponse) => {\n return priceApiResponse.reduce(\n (acc, result) => {\n if (result.status === 'fulfilled') {\n Object.entries(result.value).forEach(([assetId, currencyToPrice]) => {\n const existingPrices = acc[assetId as CaipAssetType];\n if (!existingPrices) {\n acc[assetId as CaipAssetType] = {};\n }\n Object.entries(currencyToPrice).forEach(([currency, price]) => {\n acc[assetId as CaipAssetType][currency] = price;\n });\n });\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n });\n\n return combinedPrices;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"fetch.mjs","sourceRoot":"","sources":["../../src/utils/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,8BAA8B;AAEpD,OAAO,EAAE,QAAQ,EAAE,wBAAwB;AAE3C,OAAO,EACL,4BAA4B,EAC5B,kBAAkB,EACnB,8BAA0B;AAC3B,OAAO,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,yBAAqB;AAS/E,MAAM,yBAAyB,GAAG,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC;AAEvD,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,QAAgB,EAAE,EAAE,CAAC,CAAC;IACtD,aAAa,EAAE,QAAQ;CACxB,CAAC,CAAC;AAEH;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,OAA0B,EAC1B,QAAgB,EAChB,OAAsB,EACtB,gBAAwB;IAExB,8BAA8B;IAC9B,MAAM,GAAG,GAAG,GAAG,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M,CAAC,MAAM,KAAK,WAAW,EAAE;gBACjC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,EAAE,eAAe,CAAC,EAAE,EAAE;oBAClE,MAAM,cAAc,GAAG,GAAG,CAAC,OAAwB,CAAC,CAAC;oBACrD,IAAI,CAAC,cAAc,EAAE;wBACnB,GAAG,CAAC,OAAwB,CAAC,GAAG,EAAE,CAAC;qBACpC;oBACD,MAAM,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,EAAE;wBAC5D,GAAG,CAAC,OAAwB,CAAC,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;oBAClD,CAAC,CAAC,CAAC;gBACL,CAAC,CAAC,CAAC;aACJ;YACD,OAAO,GAAG,CAAC;QACb,CAAC,EACD,EAA2D,CAC5D,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,cAAc,CAAC;AACxB,CAAC,CAAC","sourcesContent":["import { StructError } from '@metamask/superstruct';\nimport type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';\nimport { Duration } from '@metamask/utils';\n\nimport {\n formatAddressToCaipReference,\n formatChainIdToDec,\n} from './caip-formatters';\nimport { validateQuoteResponse, validateSwapsTokenObject } from './validators';\nimport type {\n QuoteResponse,\n FetchFunction,\n GenericQuoteRequest,\n QuoteRequest,\n BridgeAsset,\n} from '../types';\n\nconst CACHE_REFRESH_TEN_MINUTES = 10 * Duration.Minute;\n\nexport const getClientIdHeader = (clientId: string) => ({\n 'X-Client-Id': clientId,\n});\n\n/**\n * Returns a list of enabled (unblocked) tokens\n *\n * @param chainId - The chain ID to fetch tokens for\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of enabled (unblocked) tokens\n */\nexport async function fetchBridgeTokens(\n chainId: Hex | CaipChainId,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<Record<string, BridgeAsset>> {\n // TODO make token api v2 call\n const url = `${bridgeApiBaseUrl}/getTokens?chainId=${formatChainIdToDec(chainId)}`;\n\n // TODO we will need to cache these. In Extension fetchWithCache is used. This is due to the following:\n // If we allow selecting dest networks which the user has not imported,\n // note that the Assets controller won't be able to provide tokens. In extension we fetch+cache the token list from bridge-api to handle this\n const tokens = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: CACHE_REFRESH_TEN_MINUTES },\n functionName: 'fetchBridgeTokens',\n });\n\n const transformedTokens: Record<string, BridgeAsset> = {};\n tokens.forEach((token: unknown) => {\n if (validateSwapsTokenObject(token)) {\n transformedTokens[token.address] = token;\n }\n });\n return transformedTokens;\n}\n\n/**\n * Converts the generic quote request to the type that the bridge-api expects\n * then fetches quotes from the bridge-api\n *\n * @param request - The quote request\n * @param signal - The abort signal\n * @param clientId - The client ID for metrics\n * @param fetchFn - The fetch function to use\n * @param bridgeApiBaseUrl - The base URL for the bridge API\n * @returns A list of bridge tx quotes\n */\nexport async function fetchBridgeQuotes(\n request: GenericQuoteRequest,\n signal: AbortSignal,\n clientId: string,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<QuoteResponse[]> {\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 };\n if (request.slippage !== undefined) {\n normalizedRequest.slippage = request.slippage;\n }\n\n const queryParams = new URLSearchParams();\n Object.entries(normalizedRequest).forEach(([key, value]) => {\n queryParams.append(key, value.toString());\n });\n const url = `${bridgeApiBaseUrl}/getQuote?${queryParams}`;\n const quotes: unknown[] = await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n signal,\n cacheOptions: { cacheRefreshTime: 0 },\n functionName: 'fetchBridgeQuotes',\n });\n\n const validationFailuresByAggregator: {\n [aggregator: string]: Set<string>;\n } = {};\n const filteredQuotes = quotes.filter((quoteResponse: unknown) => {\n try {\n return validateQuoteResponse(quoteResponse);\n } catch (error) {\n if (error instanceof StructError) {\n error.failures().forEach(({ branch, path }) => {\n const aggregatorId = branch?.[0]?.quote?.bridgeId;\n if (!validationFailuresByAggregator[aggregatorId]) {\n validationFailuresByAggregator[aggregatorId] = new Set([]);\n }\n const pathString = path?.join('.') || 'unknown';\n validationFailuresByAggregator[aggregatorId].add(pathString);\n });\n }\n return false;\n }\n });\n\n if (Object.keys(validationFailuresByAggregator).length > 0) {\n console.error('Quote validation failed', validationFailuresByAggregator);\n }\n return filteredQuotes as QuoteResponse[];\n}\n\nconst fetchAssetPricesForCurrency = async (request: {\n currency: string;\n assetIds: Set<CaipAssetType>;\n clientId: string;\n fetchFn: FetchFunction;\n}): Promise<Record<CaipAssetType, { [currency: string]: string }>> => {\n const { currency, assetIds, clientId, fetchFn } = request;\n const validAssetIds = Array.from(assetIds).filter(Boolean);\n if (validAssetIds.length === 0) {\n return {};\n }\n\n const queryParams = new URLSearchParams({\n assetIds: validAssetIds.filter(Boolean).join(','),\n vsCurrency: currency,\n });\n const url = `https://price.api.cx.metamask.io/v3/spot-prices?${queryParams}`;\n const priceApiResponse = (await fetchFn(url, {\n headers: getClientIdHeader(clientId),\n cacheOptions: { cacheRefreshTime: Number(Duration.Second * 30) },\n functionName: 'fetchAssetExchangeRates',\n })) as Record<CaipAssetType, { [currency: string]: number }>;\n\n if (!priceApiResponse || typeof priceApiResponse !== 'object') {\n return {};\n }\n\n return Object.entries(priceApiResponse).reduce(\n (acc, [assetId, currencyToPrice]) => {\n if (!currencyToPrice) {\n return acc;\n }\n if (!acc[assetId as CaipAssetType]) {\n acc[assetId as CaipAssetType] = {};\n }\n if (currencyToPrice[currency]) {\n acc[assetId as CaipAssetType][currency] =\n currencyToPrice[currency].toString();\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n};\n\n/**\n * Fetches the asset prices from the price API for multiple currencies\n *\n * @param request - The request object\n * @returns The asset prices by assetId\n */\nexport const fetchAssetPrices = async (\n request: {\n currencies: Set<string>;\n } & Omit<Parameters<typeof fetchAssetPricesForCurrency>[0], 'currency'>,\n): Promise<\n Record<CaipAssetType, { [currency: string]: string } | undefined>\n> => {\n const { currencies, ...args } = request;\n\n const combinedPrices = await Promise.allSettled(\n Array.from(currencies).map(\n async (currency) =>\n await fetchAssetPricesForCurrency({ ...args, currency }),\n ),\n ).then((priceApiResponse) => {\n return priceApiResponse.reduce(\n (acc, result) => {\n if (result.status === 'fulfilled') {\n Object.entries(result.value).forEach(([assetId, currencyToPrice]) => {\n const existingPrices = acc[assetId as CaipAssetType];\n if (!existingPrices) {\n acc[assetId as CaipAssetType] = {};\n }\n Object.entries(currencyToPrice).forEach(([currency, price]) => {\n acc[assetId as CaipAssetType][currency] = price;\n });\n });\n }\n return acc;\n },\n {} as Record<CaipAssetType, { [currency: string]: string }>,\n );\n });\n\n return combinedPrices;\n};\n"]}
|