@metamask-previews/bridge-status-controller 12.0.1-preview-fa52096c → 13.1.0-preview-3d7a30d
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 +35 -2
- package/dist/bridge-status-controller.cjs +257 -7
- package/dist/bridge-status-controller.cjs.map +1 -1
- package/dist/bridge-status-controller.d.cts +23 -3
- package/dist/bridge-status-controller.d.cts.map +1 -1
- package/dist/bridge-status-controller.d.mts +23 -3
- package/dist/bridge-status-controller.d.mts.map +1 -1
- package/dist/bridge-status-controller.mjs +259 -9
- package/dist/bridge-status-controller.mjs.map +1 -1
- package/dist/constants.cjs +3 -1
- package/dist/constants.cjs.map +1 -1
- package/dist/constants.d.cts +2 -0
- package/dist/constants.d.cts.map +1 -1
- package/dist/constants.d.mts +2 -0
- package/dist/constants.d.mts.map +1 -1
- package/dist/constants.mjs +2 -0
- package/dist/constants.mjs.map +1 -1
- package/dist/index.cjs +4 -1
- 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/types.cjs +10 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +28 -7
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +28 -7
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs +9 -0
- package/dist/types.mjs.map +1 -1
- package/dist/utils/bridge-status.cjs +6 -5
- package/dist/utils/bridge-status.cjs.map +1 -1
- package/dist/utils/bridge-status.d.cts.map +1 -1
- package/dist/utils/bridge-status.d.mts.map +1 -1
- package/dist/utils/bridge-status.mjs +6 -5
- package/dist/utils/bridge-status.mjs.map +1 -1
- package/dist/utils/gas.cjs +31 -0
- package/dist/utils/gas.cjs.map +1 -0
- package/dist/utils/gas.d.cts +20 -0
- package/dist/utils/gas.d.cts.map +1 -0
- package/dist/utils/gas.d.mts +20 -0
- package/dist/utils/gas.d.mts.map +1 -0
- package/dist/utils/gas.mjs +27 -0
- package/dist/utils/gas.mjs.map +1 -0
- package/dist/utils/transaction.cjs +115 -0
- package/dist/utils/transaction.cjs.map +1 -0
- package/dist/utils/transaction.d.cts +45 -0
- package/dist/utils/transaction.d.cts.map +1 -0
- package/dist/utils/transaction.d.mts +45 -0
- package/dist/utils/transaction.d.mts.map +1 -0
- package/dist/utils/transaction.mjs +106 -0
- package/dist/utils/transaction.mjs.map +1 -0
- package/dist/utils/validators.cjs +1 -1
- package/dist/utils/validators.cjs.map +1 -1
- package/dist/utils/validators.mjs +2 -2
- package/dist/utils/validators.mjs.map +1 -1
- package/package.json +14 -3
@@ -1,7 +1,11 @@
|
|
1
|
-
import type
|
1
|
+
import { type QuoteResponse } from "@metamask/bridge-controller";
|
2
|
+
import type { QuoteMetadata, TxData } from "@metamask/bridge-controller";
|
3
|
+
import type { TransactionController } from "@metamask/transaction-controller";
|
4
|
+
import { type TransactionMeta } from "@metamask/transaction-controller";
|
5
|
+
import type { UserOperationController } from "@metamask/user-operation-controller";
|
2
6
|
import { BRIDGE_STATUS_CONTROLLER_NAME } from "./constants.mjs";
|
3
7
|
import { type BridgeStatusControllerMessenger } from "./types.mjs";
|
4
|
-
import type { BridgeStatusControllerState, StartPollingForBridgeTxStatusArgsSerialized, FetchFunction } from "./types.mjs";
|
8
|
+
import type { BridgeStatusControllerState, StartPollingForBridgeTxStatusArgsSerialized, FetchFunction, BridgeClientId, SolanaTransactionMeta } from "./types.mjs";
|
5
9
|
/** The input to start polling for the {@link BridgeStatusController} */
|
6
10
|
type BridgeStatusPollingInput = FetchBridgeTxStatusArgs;
|
7
11
|
export type FetchBridgeTxStatusArgs = {
|
@@ -24,11 +28,14 @@ declare const BridgeStatusController_base: (abstract new (...args: any[]) => {
|
|
24
28
|
}) & typeof import("@metamask/base-controller").BaseController;
|
25
29
|
export declare class BridgeStatusController extends BridgeStatusController_base<typeof BRIDGE_STATUS_CONTROLLER_NAME, BridgeStatusControllerState, BridgeStatusControllerMessenger> {
|
26
30
|
#private;
|
27
|
-
constructor({ messenger, state, clientId, fetchFn, config, }: {
|
31
|
+
constructor({ messenger, state, clientId, fetchFn, addTransactionFn, addUserOperationFromTransactionFn, estimateGasFeeFn, config, }: {
|
28
32
|
messenger: BridgeStatusControllerMessenger;
|
29
33
|
state?: Partial<BridgeStatusControllerState>;
|
30
34
|
clientId: BridgeClientId;
|
31
35
|
fetchFn: FetchFunction;
|
36
|
+
addTransactionFn: typeof TransactionController.prototype.addTransaction;
|
37
|
+
estimateGasFeeFn: typeof TransactionController.prototype.estimateGasFee;
|
38
|
+
addUserOperationFromTransactionFn?: typeof UserOperationController.prototype.addUserOperationFromTransaction;
|
32
39
|
config?: {
|
33
40
|
customBridgeApiBaseUrl?: string;
|
34
41
|
};
|
@@ -38,8 +45,21 @@ export declare class BridgeStatusController extends BridgeStatusController_base<
|
|
38
45
|
address: string;
|
39
46
|
ignoreNetwork: boolean;
|
40
47
|
}) => void;
|
48
|
+
/**
|
49
|
+
* Starts polling for the bridge tx status
|
50
|
+
*
|
51
|
+
* @param startPollingForBridgeTxStatusArgs - The args to start polling for the bridge tx status
|
52
|
+
*/
|
41
53
|
startPollingForBridgeTxStatus: (startPollingForBridgeTxStatusArgs: StartPollingForBridgeTxStatusArgsSerialized) => void;
|
42
54
|
_executePoll: (pollingInput: BridgeStatusPollingInput) => Promise<void>;
|
55
|
+
/**
|
56
|
+
* Submits a cross-chain swap transaction
|
57
|
+
*
|
58
|
+
* @param quoteResponse - The quote response
|
59
|
+
* @param isStxEnabledOnClient - Whether smart transactions are enabled on the client, for example the getSmartTransactionsEnabled selector value from the extension
|
60
|
+
* @returns The transaction meta
|
61
|
+
*/
|
62
|
+
submitTx: (quoteResponse: QuoteResponse<TxData | string> & QuoteMetadata, isStxEnabledOnClient: boolean) => Promise<TransactionMeta & Partial<SolanaTransactionMeta>>;
|
43
63
|
}
|
44
64
|
export {};
|
45
65
|
//# sourceMappingURL=bridge-status-controller.d.mts.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"bridge-status-controller.d.mts","sourceRoot":"","sources":["../src/bridge-status-controller.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,
|
1
|
+
{"version":3,"file":"bridge-status-controller.d.mts","sourceRoot":"","sources":["../src/bridge-status-controller.ts"],"names":[],"mappings":"AACA,OAAO,EAML,KAAK,aAAa,EACnB,oCAAoC;AACrC,OAAO,KAAK,EAEV,aAAa,EACb,MAAM,EACP,oCAAoC;AAIrC,OAAO,KAAK,EACV,qBAAqB,EAEtB,yCAAyC;AAC1C,OAAO,EAGL,KAAK,eAAe,EACrB,yCAAyC;AAC1C,OAAO,KAAK,EAAE,uBAAuB,EAAE,4CAA4C;AAInF,OAAO,EAEL,6BAA6B,EAG9B,wBAAoB;AACrB,OAAO,EAAe,KAAK,+BAA+B,EAAE,oBAAgB;AAC5E,OAAO,KAAK,EACV,2BAA2B,EAC3B,2CAA2C,EAC3C,aAAa,EACb,cAAc,EACd,qBAAqB,EACtB,oBAAgB;AAwBjB,wEAAwE;AACxE,KAAK,wBAAwB,GAAG,uBAAuB,CAAC;AAGxD,MAAM,MAAM,uBAAuB,GAAG;IACpC,cAAc,EAAE,MAAM,CAAC;CACxB,CAAC;;;;;;;;;;;;;;;;AACF,qBAAa,sBAAuB,SAAQ,4BAC1C,OAAO,6BAA6B,EACpC,2BAA2B,EAC3B,+BAA+B,CAChC;;gBAiBa,EACV,SAAS,EACT,KAAK,EACL,QAAQ,EACR,OAAO,EACP,gBAAgB,EAChB,iCAAiC,EACjC,gBAAgB,EAChB,MAAM,GACP,EAAE;QACD,SAAS,EAAE,+BAA+B,CAAC;QAC3C,KAAK,CAAC,EAAE,OAAO,CAAC,2BAA2B,CAAC,CAAC;QAC7C,QAAQ,EAAE,cAAc,CAAC;QACzB,OAAO,EAAE,aAAa,CAAC;QACvB,gBAAgB,EAAE,OAAO,qBAAqB,CAAC,SAAS,CAAC,cAAc,CAAC;QACxE,gBAAgB,EAAE,OAAO,qBAAqB,CAAC,SAAS,CAAC,cAAc,CAAC;QACxE,iCAAiC,CAAC,EAAE,OAAO,uBAAuB,CAAC,SAAS,CAAC,+BAA+B,CAAC;QAC7G,MAAM,CAAC,EAAE;YACP,sBAAsB,CAAC,EAAE,MAAM,CAAC;SACjC,CAAC;KACH;IAiDD,UAAU,aAIR;IAEF,gBAAgB;iBAIL,MAAM;uBACA,OAAO;eAmBtB;IA8BF;;;;OAIG;IACH,6BAA6B,sCACQ,2CAA2C,UAmD9E;IAIF,YAAY,iBAAwB,wBAAwB,mBAE1D;IA+bF;;;;;;OAMG;IACH,QAAQ,kBACS,cAAc,MAAM,GAAG,MAAM,CAAC,GAAG,aAAa,wBACvC,OAAO,+DA+D7B;CACH"}
|
@@ -9,13 +9,20 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
9
9
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
10
10
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
11
11
|
};
|
12
|
-
var _BridgeStatusController_instances, _BridgeStatusController_pollingTokensByTxMetaId, _BridgeStatusController_clientId, _BridgeStatusController_fetchFn, _BridgeStatusController_config, _BridgeStatusController_restartPollingForIncompleteHistoryItems, _BridgeStatusController_getMultichainSelectedAccountAddress, _BridgeStatusController_fetchBridgeTxStatus, _BridgeStatusController_getSrcTxHash, _BridgeStatusController_updateSrcTxHash, _BridgeStatusController_wipeBridgeStatusByChainId;
|
13
|
-
import {
|
12
|
+
var _BridgeStatusController_instances, _BridgeStatusController_pollingTokensByTxMetaId, _BridgeStatusController_clientId, _BridgeStatusController_fetchFn, _BridgeStatusController_config, _BridgeStatusController_addTransactionFn, _BridgeStatusController_estimateGasFeeFn, _BridgeStatusController_addUserOperationFromTransactionFn, _BridgeStatusController_restartPollingForIncompleteHistoryItems, _BridgeStatusController_getMultichainSelectedAccount, _BridgeStatusController_getMultichainSelectedAccountAddress, _BridgeStatusController_fetchBridgeTxStatus, _BridgeStatusController_getSrcTxHash, _BridgeStatusController_updateSrcTxHash, _BridgeStatusController_wipeBridgeStatusByChainId, _BridgeStatusController_handleSolanaTx, _BridgeStatusController_waitForHashAndReturnFinalTxMeta, _BridgeStatusController_handleApprovalTx, _BridgeStatusController_handleEvmSmartTransaction, _BridgeStatusController_handleEvmTransaction, _BridgeStatusController_addTokens, _BridgeStatusController_handleUSDTAllowanceReset, _BridgeStatusController_calculateGasFees;
|
13
|
+
import { formatChainIdToHex, getEthUsdtResetData, isEthUsdt, isNativeAddress, isSolanaChainId } from "@metamask/bridge-controller";
|
14
|
+
import { toHex } from "@metamask/controller-utils";
|
15
|
+
import { EthAccountType } from "@metamask/keyring-api";
|
14
16
|
import { StaticIntervalPollingController } from "@metamask/polling-controller";
|
17
|
+
import { TransactionStatus, TransactionType } from "@metamask/transaction-controller";
|
15
18
|
import { numberToHex } from "@metamask/utils";
|
16
|
-
import {
|
19
|
+
import { BigNumber } from "bignumber.js";
|
20
|
+
import { BRIDGE_PROD_API_BASE_URL, BRIDGE_STATUS_CONTROLLER_NAME, DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE, REFRESH_INTERVAL_MS } from "./constants.mjs";
|
17
21
|
import { StatusTypes } from "./types.mjs";
|
18
22
|
import { fetchBridgeTxStatus, getStatusRequestWithSrcTxHash } from "./utils/bridge-status.mjs";
|
23
|
+
import { getTxGasEstimates } from "./utils/gas.mjs";
|
24
|
+
import { getKeyringRequest, getStatusRequestParams, getTxMetaFields, handleLineaDelay, handleSolanaTxResponse } from "./utils/transaction.mjs";
|
25
|
+
import { generateActionId } from "./utils/transaction.mjs";
|
19
26
|
const metadata = {
|
20
27
|
// We want to persist the bridge status state so that we can show the proper data for the Activity list
|
21
28
|
// basically match the behavior of TransactionController
|
@@ -25,7 +32,7 @@ const metadata = {
|
|
25
32
|
},
|
26
33
|
};
|
27
34
|
export class BridgeStatusController extends StaticIntervalPollingController() {
|
28
|
-
constructor({ messenger, state, clientId, fetchFn, config, }) {
|
35
|
+
constructor({ messenger, state, clientId, fetchFn, addTransactionFn, addUserOperationFromTransactionFn, estimateGasFeeFn, config, }) {
|
29
36
|
super({
|
30
37
|
name: BRIDGE_STATUS_CONTROLLER_NAME,
|
31
38
|
metadata,
|
@@ -41,6 +48,9 @@ export class BridgeStatusController extends StaticIntervalPollingController() {
|
|
41
48
|
_BridgeStatusController_clientId.set(this, void 0);
|
42
49
|
_BridgeStatusController_fetchFn.set(this, void 0);
|
43
50
|
_BridgeStatusController_config.set(this, void 0);
|
51
|
+
_BridgeStatusController_addTransactionFn.set(this, void 0);
|
52
|
+
_BridgeStatusController_estimateGasFeeFn.set(this, void 0);
|
53
|
+
_BridgeStatusController_addUserOperationFromTransactionFn.set(this, void 0);
|
44
54
|
this.resetState = () => {
|
45
55
|
this.update((state) => {
|
46
56
|
state.txHistory = DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE.txHistory;
|
@@ -82,8 +92,13 @@ export class BridgeStatusController extends StaticIntervalPollingController() {
|
|
82
92
|
});
|
83
93
|
});
|
84
94
|
});
|
95
|
+
/**
|
96
|
+
* Starts polling for the bridge tx status
|
97
|
+
*
|
98
|
+
* @param startPollingForBridgeTxStatusArgs - The args to start polling for the bridge tx status
|
99
|
+
*/
|
85
100
|
this.startPollingForBridgeTxStatus = (startPollingForBridgeTxStatusArgs) => {
|
86
|
-
const { bridgeTxMeta, statusRequest, quoteResponse, startTime, slippagePercentage, initialDestAssetBalance, targetContractAddress, } = startPollingForBridgeTxStatusArgs;
|
101
|
+
const { bridgeTxMeta, statusRequest, quoteResponse, startTime, slippagePercentage, initialDestAssetBalance, targetContractAddress, approvalTxId, } = startPollingForBridgeTxStatusArgs;
|
87
102
|
const accountAddress = __classPrivateFieldGet(this, _BridgeStatusController_instances, "m", _BridgeStatusController_getMultichainSelectedAccountAddress).call(this);
|
88
103
|
// Write all non-status fields to state so we can reference the quote in Activity list without the Bridge API
|
89
104
|
// We know it's in progress but not the exact status yet
|
@@ -112,6 +127,7 @@ export class BridgeStatusController extends StaticIntervalPollingController() {
|
|
112
127
|
},
|
113
128
|
},
|
114
129
|
hasApprovalTx: Boolean(quoteResponse.approval),
|
130
|
+
approvalTxId,
|
115
131
|
};
|
116
132
|
this.update((state) => {
|
117
133
|
// Use the txMeta.id as the key so we can reference the txMeta in TransactionController
|
@@ -139,7 +155,7 @@ export class BridgeStatusController extends StaticIntervalPollingController() {
|
|
139
155
|
}
|
140
156
|
__classPrivateFieldGet(this, _BridgeStatusController_updateSrcTxHash, "f").call(this, bridgeTxMetaId, srcTxHash);
|
141
157
|
const statusRequest = getStatusRequestWithSrcTxHash(historyItem.quote, srcTxHash);
|
142
|
-
const status = await fetchBridgeTxStatus(statusRequest, __classPrivateFieldGet(this, _BridgeStatusController_clientId, "f"), __classPrivateFieldGet(this, _BridgeStatusController_fetchFn, "f"), __classPrivateFieldGet(this, _BridgeStatusController_config, "f").customBridgeApiBaseUrl
|
158
|
+
const status = await fetchBridgeTxStatus(statusRequest, __classPrivateFieldGet(this, _BridgeStatusController_clientId, "f"), __classPrivateFieldGet(this, _BridgeStatusController_fetchFn, "f"), __classPrivateFieldGet(this, _BridgeStatusController_config, "f").customBridgeApiBaseUrl);
|
143
159
|
const newBridgeHistoryItem = {
|
144
160
|
...historyItem,
|
145
161
|
status,
|
@@ -216,13 +232,245 @@ export class BridgeStatusController extends StaticIntervalPollingController() {
|
|
216
232
|
}, state.txHistory);
|
217
233
|
});
|
218
234
|
});
|
235
|
+
/**
|
236
|
+
* ******************************************************
|
237
|
+
* TX SUBMISSION HANDLING
|
238
|
+
*******************************************************
|
239
|
+
*/
|
240
|
+
/**
|
241
|
+
* Submits the transaction to the snap using the keyring rpc method
|
242
|
+
* This adds an approval tx to the ApprovalsController in the background
|
243
|
+
* The client needs to handle the approval tx by redirecting to the confirmation page with the approvalTxId in the URL
|
244
|
+
*
|
245
|
+
* @param quoteResponse - The quote response
|
246
|
+
* @param quoteResponse.quote - The quote
|
247
|
+
* @returns The transaction meta
|
248
|
+
*/
|
249
|
+
_BridgeStatusController_handleSolanaTx.set(this, async (quoteResponse) => {
|
250
|
+
const selectedAccount = __classPrivateFieldGet(this, _BridgeStatusController_instances, "m", _BridgeStatusController_getMultichainSelectedAccount).call(this);
|
251
|
+
if (!selectedAccount) {
|
252
|
+
throw new Error('Failed to submit cross-chain swap transaction: undefined multichain account');
|
253
|
+
}
|
254
|
+
if (!selectedAccount.metadata?.snap?.id ||
|
255
|
+
!selectedAccount.options?.scope) {
|
256
|
+
throw new Error('Failed to submit cross-chain swap transaction: undefined snap id or scope');
|
257
|
+
}
|
258
|
+
const keyringRequest = getKeyringRequest(quoteResponse, selectedAccount);
|
259
|
+
const keyringResponse = (await this.messagingSystem.call('SnapController:handleRequest', keyringRequest));
|
260
|
+
// The extension client actually redirects before it can do anytyhing with this meta
|
261
|
+
const txMeta = handleSolanaTxResponse(keyringResponse, quoteResponse, selectedAccount);
|
262
|
+
// TODO remove this eventually, just returning it now to match extension behavior
|
263
|
+
// OR if the snap can propagate the snapRequestId or keyringReqId to the ApprovalsController, this can return the approvalTxId instead and clients won't need to subscribe to the ApprovalsController state to redirect
|
264
|
+
return txMeta;
|
265
|
+
});
|
266
|
+
_BridgeStatusController_waitForHashAndReturnFinalTxMeta.set(this, async (hashPromise) => {
|
267
|
+
const transactionHash = await hashPromise;
|
268
|
+
const finalTransactionMeta = this.messagingSystem
|
269
|
+
.call('TransactionController:getState')
|
270
|
+
.transactions.find((tx) => tx.hash === transactionHash);
|
271
|
+
return finalTransactionMeta;
|
272
|
+
});
|
273
|
+
_BridgeStatusController_handleApprovalTx.set(this, async (quoteResponse) => {
|
274
|
+
if (quoteResponse.approval) {
|
275
|
+
await __classPrivateFieldGet(this, _BridgeStatusController_handleUSDTAllowanceReset, "f").call(this, quoteResponse);
|
276
|
+
const approvalTxMeta = await __classPrivateFieldGet(this, _BridgeStatusController_handleEvmTransaction, "f").call(this, TransactionType.bridgeApproval, quoteResponse.approval, quoteResponse);
|
277
|
+
if (!approvalTxMeta) {
|
278
|
+
throw new Error('Failed to submit bridge tx: approval txMeta is undefined');
|
279
|
+
}
|
280
|
+
await handleLineaDelay(quoteResponse);
|
281
|
+
return approvalTxMeta;
|
282
|
+
}
|
283
|
+
return undefined;
|
284
|
+
});
|
285
|
+
_BridgeStatusController_handleEvmSmartTransaction.set(this, async (trade, quoteResponse, approvalTxId) => {
|
286
|
+
return await __classPrivateFieldGet(this, _BridgeStatusController_handleEvmTransaction, "f").call(this, TransactionType.bridge, trade, quoteResponse, approvalTxId, false);
|
287
|
+
});
|
288
|
+
/**
|
289
|
+
* Submits an EVM transaction to the TransactionController
|
290
|
+
*
|
291
|
+
* @param transactionType - The type of transaction to submit
|
292
|
+
* @param trade - The trade data to confirm
|
293
|
+
* @param quoteResponse - The quote response
|
294
|
+
* @param quoteResponse.quote - The quote
|
295
|
+
* @param approvalTxId - The tx id of the approval tx
|
296
|
+
* @param shouldWaitForHash - Whether to wait for the hash of the transaction
|
297
|
+
* @returns The transaction meta
|
298
|
+
*/
|
299
|
+
_BridgeStatusController_handleEvmTransaction.set(this, async (transactionType, trade, quoteResponse, approvalTxId, shouldWaitForHash = true) => {
|
300
|
+
const actionId = generateActionId().toString();
|
301
|
+
const selectedAccount = this.messagingSystem.call('AccountsController:getAccountByAddress', trade.from);
|
302
|
+
if (!selectedAccount) {
|
303
|
+
throw new Error('Failed to submit cross-chain swap transaction: unknown account in trade data');
|
304
|
+
}
|
305
|
+
const hexChainId = formatChainIdToHex(trade.chainId);
|
306
|
+
const networkClientId = this.messagingSystem.call('NetworkController:findNetworkClientIdByChainId', hexChainId);
|
307
|
+
const requestOptions = {
|
308
|
+
actionId,
|
309
|
+
networkClientId,
|
310
|
+
requireApproval: false,
|
311
|
+
type: transactionType,
|
312
|
+
origin: 'metamask',
|
313
|
+
};
|
314
|
+
const transactionParams = {
|
315
|
+
...trade,
|
316
|
+
chainId: hexChainId,
|
317
|
+
gasLimit: trade.gasLimit?.toString(),
|
318
|
+
gas: trade.gasLimit?.toString(),
|
319
|
+
};
|
320
|
+
const transactionParamsWithMaxGas = {
|
321
|
+
...transactionParams,
|
322
|
+
...(await __classPrivateFieldGet(this, _BridgeStatusController_calculateGasFees, "f").call(this, transactionParams, networkClientId, hexChainId)),
|
323
|
+
};
|
324
|
+
let result;
|
325
|
+
let transactionMeta;
|
326
|
+
const isSmartContractAccount = selectedAccount.type === EthAccountType.Erc4337;
|
327
|
+
if (isSmartContractAccount && __classPrivateFieldGet(this, _BridgeStatusController_addUserOperationFromTransactionFn, "f")) {
|
328
|
+
const smartAccountTxResult = await __classPrivateFieldGet(this, _BridgeStatusController_addUserOperationFromTransactionFn, "f").call(this, transactionParamsWithMaxGas, requestOptions);
|
329
|
+
result = smartAccountTxResult.transactionHash;
|
330
|
+
transactionMeta = {
|
331
|
+
...requestOptions,
|
332
|
+
chainId: hexChainId,
|
333
|
+
txParams: transactionParamsWithMaxGas,
|
334
|
+
time: Date.now(),
|
335
|
+
id: smartAccountTxResult.id,
|
336
|
+
status: TransactionStatus.confirmed,
|
337
|
+
};
|
338
|
+
}
|
339
|
+
else {
|
340
|
+
const addTransactionResult = await __classPrivateFieldGet(this, _BridgeStatusController_addTransactionFn, "f").call(this, transactionParamsWithMaxGas, requestOptions);
|
341
|
+
result = addTransactionResult.result;
|
342
|
+
transactionMeta = addTransactionResult.transactionMeta;
|
343
|
+
}
|
344
|
+
if (shouldWaitForHash) {
|
345
|
+
return await __classPrivateFieldGet(this, _BridgeStatusController_waitForHashAndReturnFinalTxMeta, "f").call(this, result);
|
346
|
+
}
|
347
|
+
// TODO why is this needed?
|
348
|
+
// Note that updateTransaction doesn't actually error if you add fields that don't conform the to the txMeta type
|
349
|
+
// they will be there at runtime, but you just don't get any type safety checks on them
|
350
|
+
// const fieldsToAddToTxMeta = getTxMetaFields(quoteResponse, approvalTxId);
|
351
|
+
// dispatch(updateTransaction(completeTxMeta);
|
352
|
+
return {
|
353
|
+
...getTxMetaFields(quoteResponse, approvalTxId),
|
354
|
+
...transactionMeta,
|
355
|
+
};
|
356
|
+
});
|
357
|
+
// Only adds tokens if the source or dest chain is an EVM chain bc non-evm tokens
|
358
|
+
// are detected by the multichain asset controllers
|
359
|
+
_BridgeStatusController_addTokens.set(this, (asset) => {
|
360
|
+
if (isNativeAddress(asset.address) || isSolanaChainId(asset.chainId)) {
|
361
|
+
return;
|
362
|
+
}
|
363
|
+
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
364
|
+
this.messagingSystem.call('TokensController:addDetectedTokens', [
|
365
|
+
{
|
366
|
+
address: asset.address,
|
367
|
+
decimals: asset.decimals,
|
368
|
+
image: asset.iconUrl,
|
369
|
+
name: asset.name,
|
370
|
+
symbol: asset.symbol,
|
371
|
+
},
|
372
|
+
], {
|
373
|
+
chainId: formatChainIdToHex(asset.chainId),
|
374
|
+
selectedAddress: __classPrivateFieldGet(this, _BridgeStatusController_instances, "m", _BridgeStatusController_getMultichainSelectedAccountAddress).call(this),
|
375
|
+
});
|
376
|
+
});
|
377
|
+
_BridgeStatusController_handleUSDTAllowanceReset.set(this, async (quoteResponse) => {
|
378
|
+
const hexChainId = formatChainIdToHex(quoteResponse.quote.srcChainId);
|
379
|
+
if (quoteResponse.approval &&
|
380
|
+
isEthUsdt(hexChainId, quoteResponse.quote.srcAsset.address)) {
|
381
|
+
const allowance = new BigNumber(await this.messagingSystem.call('BridgeController:getBridgeERC20Allowance', quoteResponse.quote.srcAsset.address, hexChainId));
|
382
|
+
const shouldResetApproval = allowance.lt(quoteResponse.sentAmount.amount) && allowance.gt(0);
|
383
|
+
if (shouldResetApproval) {
|
384
|
+
await __classPrivateFieldGet(this, _BridgeStatusController_handleEvmTransaction, "f").call(this, TransactionType.bridgeApproval, { ...quoteResponse.approval, data: getEthUsdtResetData() }, quoteResponse);
|
385
|
+
}
|
386
|
+
}
|
387
|
+
});
|
388
|
+
_BridgeStatusController_calculateGasFees.set(this, async (transactionParams, networkClientId, chainId) => {
|
389
|
+
const { gasFeeEstimates } = this.messagingSystem.call('GasFeeController:getState');
|
390
|
+
const { estimates: txGasFeeEstimates } = await __classPrivateFieldGet(this, _BridgeStatusController_estimateGasFeeFn, "f").call(this, {
|
391
|
+
transactionParams,
|
392
|
+
chainId,
|
393
|
+
networkClientId,
|
394
|
+
});
|
395
|
+
const { maxFeePerGas, maxPriorityFeePerGas } = getTxGasEstimates({
|
396
|
+
networkGasFeeEstimates: gasFeeEstimates,
|
397
|
+
txGasFeeEstimates,
|
398
|
+
});
|
399
|
+
const maxGasLimit = toHex(transactionParams.gas ?? 0);
|
400
|
+
return {
|
401
|
+
maxFeePerGas,
|
402
|
+
maxPriorityFeePerGas,
|
403
|
+
gas: maxGasLimit,
|
404
|
+
};
|
405
|
+
});
|
406
|
+
/**
|
407
|
+
* Submits a cross-chain swap transaction
|
408
|
+
*
|
409
|
+
* @param quoteResponse - The quote response
|
410
|
+
* @param isStxEnabledOnClient - Whether smart transactions are enabled on the client, for example the getSmartTransactionsEnabled selector value from the extension
|
411
|
+
* @returns The transaction meta
|
412
|
+
*/
|
413
|
+
this.submitTx = async (quoteResponse, isStxEnabledOnClient) => {
|
414
|
+
let txMeta;
|
415
|
+
// Submit SOLANA tx
|
416
|
+
if (isSolanaChainId(quoteResponse.quote.srcChainId) &&
|
417
|
+
typeof quoteResponse.trade === 'string') {
|
418
|
+
txMeta = await __classPrivateFieldGet(this, _BridgeStatusController_handleSolanaTx, "f").call(this, quoteResponse);
|
419
|
+
}
|
420
|
+
// Submit EVM tx
|
421
|
+
let approvalTime, approvalTxId;
|
422
|
+
if (!isSolanaChainId(quoteResponse.quote.srcChainId) &&
|
423
|
+
typeof quoteResponse.trade !== 'string') {
|
424
|
+
// Set approval time and id if an approval tx is needed
|
425
|
+
const approvalTxMeta = await __classPrivateFieldGet(this, _BridgeStatusController_handleApprovalTx, "f").call(this, quoteResponse);
|
426
|
+
approvalTime = approvalTxMeta?.time;
|
427
|
+
approvalTxId = approvalTxMeta?.id;
|
428
|
+
// Handle smart transactions if enabled
|
429
|
+
if (isStxEnabledOnClient) {
|
430
|
+
txMeta = await __classPrivateFieldGet(this, _BridgeStatusController_handleEvmSmartTransaction, "f").call(this, quoteResponse.trade, quoteResponse, approvalTxId);
|
431
|
+
}
|
432
|
+
else {
|
433
|
+
txMeta = await __classPrivateFieldGet(this, _BridgeStatusController_handleEvmTransaction, "f").call(this, TransactionType.bridge, quoteResponse.trade, quoteResponse, approvalTxId);
|
434
|
+
}
|
435
|
+
}
|
436
|
+
if (!txMeta) {
|
437
|
+
throw new Error('Failed to submit bridge tx: txMeta is undefined');
|
438
|
+
}
|
439
|
+
try {
|
440
|
+
// Start polling for bridge tx status
|
441
|
+
this.startPollingForBridgeTxStatus({
|
442
|
+
bridgeTxMeta: txMeta,
|
443
|
+
statusRequest: {
|
444
|
+
...getStatusRequestParams(quoteResponse),
|
445
|
+
srcTxHash: txMeta.hash,
|
446
|
+
},
|
447
|
+
quoteResponse,
|
448
|
+
slippagePercentage: 0,
|
449
|
+
startTime: approvalTime ?? Date.now(),
|
450
|
+
approvalTxId,
|
451
|
+
});
|
452
|
+
// Add tokens to the token list
|
453
|
+
__classPrivateFieldGet(this, _BridgeStatusController_addTokens, "f").call(this, quoteResponse.quote.srcAsset);
|
454
|
+
__classPrivateFieldGet(this, _BridgeStatusController_addTokens, "f").call(this, quoteResponse.quote.destAsset);
|
455
|
+
}
|
456
|
+
catch {
|
457
|
+
// Ignore errors here, we don't want to crash the app if this fails and tx submission succeeds
|
458
|
+
}
|
459
|
+
return txMeta;
|
460
|
+
};
|
219
461
|
__classPrivateFieldSet(this, _BridgeStatusController_clientId, clientId, "f");
|
220
462
|
__classPrivateFieldSet(this, _BridgeStatusController_fetchFn, fetchFn, "f");
|
221
|
-
__classPrivateFieldSet(this,
|
463
|
+
__classPrivateFieldSet(this, _BridgeStatusController_addTransactionFn, addTransactionFn, "f");
|
464
|
+
__classPrivateFieldSet(this, _BridgeStatusController_addUserOperationFromTransactionFn, addUserOperationFromTransactionFn, "f");
|
465
|
+
__classPrivateFieldSet(this, _BridgeStatusController_estimateGasFeeFn, estimateGasFeeFn, "f");
|
466
|
+
__classPrivateFieldSet(this, _BridgeStatusController_config, {
|
467
|
+
customBridgeApiBaseUrl: config?.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,
|
468
|
+
}, "f");
|
222
469
|
// Register action handlers
|
223
470
|
this.messagingSystem.registerActionHandler(`${BRIDGE_STATUS_CONTROLLER_NAME}:startPollingForBridgeTxStatus`, this.startPollingForBridgeTxStatus.bind(this));
|
224
471
|
this.messagingSystem.registerActionHandler(`${BRIDGE_STATUS_CONTROLLER_NAME}:wipeBridgeStatus`, this.wipeBridgeStatus.bind(this));
|
225
472
|
this.messagingSystem.registerActionHandler(`${BRIDGE_STATUS_CONTROLLER_NAME}:resetState`, this.resetState.bind(this));
|
473
|
+
this.messagingSystem.registerActionHandler(`${BRIDGE_STATUS_CONTROLLER_NAME}:submitTx`, this.submitTx.bind(this));
|
226
474
|
// Set interval
|
227
475
|
this.setIntervalLength(REFRESH_INTERVAL_MS);
|
228
476
|
// If you close the extension, but keep the browser open, the polling continues
|
@@ -231,7 +479,9 @@ export class BridgeStatusController extends StaticIntervalPollingController() {
|
|
231
479
|
__classPrivateFieldGet(this, _BridgeStatusController_restartPollingForIncompleteHistoryItems, "f").call(this);
|
232
480
|
}
|
233
481
|
}
|
234
|
-
_BridgeStatusController_pollingTokensByTxMetaId = new WeakMap(), _BridgeStatusController_clientId = new WeakMap(), _BridgeStatusController_fetchFn = new WeakMap(), _BridgeStatusController_config = new WeakMap(), _BridgeStatusController_restartPollingForIncompleteHistoryItems = new WeakMap(), _BridgeStatusController_fetchBridgeTxStatus = new WeakMap(), _BridgeStatusController_getSrcTxHash = new WeakMap(), _BridgeStatusController_updateSrcTxHash = new WeakMap(), _BridgeStatusController_wipeBridgeStatusByChainId = new WeakMap(), _BridgeStatusController_instances = new WeakSet(),
|
235
|
-
return
|
482
|
+
_BridgeStatusController_pollingTokensByTxMetaId = new WeakMap(), _BridgeStatusController_clientId = new WeakMap(), _BridgeStatusController_fetchFn = new WeakMap(), _BridgeStatusController_config = new WeakMap(), _BridgeStatusController_addTransactionFn = new WeakMap(), _BridgeStatusController_estimateGasFeeFn = new WeakMap(), _BridgeStatusController_addUserOperationFromTransactionFn = new WeakMap(), _BridgeStatusController_restartPollingForIncompleteHistoryItems = new WeakMap(), _BridgeStatusController_fetchBridgeTxStatus = new WeakMap(), _BridgeStatusController_getSrcTxHash = new WeakMap(), _BridgeStatusController_updateSrcTxHash = new WeakMap(), _BridgeStatusController_wipeBridgeStatusByChainId = new WeakMap(), _BridgeStatusController_handleSolanaTx = new WeakMap(), _BridgeStatusController_waitForHashAndReturnFinalTxMeta = new WeakMap(), _BridgeStatusController_handleApprovalTx = new WeakMap(), _BridgeStatusController_handleEvmSmartTransaction = new WeakMap(), _BridgeStatusController_handleEvmTransaction = new WeakMap(), _BridgeStatusController_addTokens = new WeakMap(), _BridgeStatusController_handleUSDTAllowanceReset = new WeakMap(), _BridgeStatusController_calculateGasFees = new WeakMap(), _BridgeStatusController_instances = new WeakSet(), _BridgeStatusController_getMultichainSelectedAccount = function _BridgeStatusController_getMultichainSelectedAccount() {
|
483
|
+
return this.messagingSystem.call('AccountsController:getSelectedMultichainAccount');
|
484
|
+
}, _BridgeStatusController_getMultichainSelectedAccountAddress = function _BridgeStatusController_getMultichainSelectedAccountAddress() {
|
485
|
+
return __classPrivateFieldGet(this, _BridgeStatusController_instances, "m", _BridgeStatusController_getMultichainSelectedAccount).call(this)?.address ?? '';
|
236
486
|
};
|
237
487
|
//# sourceMappingURL=bridge-status-controller.mjs.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"bridge-status-controller.mjs","sourceRoot":"","sources":["../src/bridge-status-controller.ts"],"names":[],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C,+EAA+E;QAC/E,8CAA8C;QAC9C,mFAAmF;QACnF,uBAAA,IAAI,uEAAyC,MAA7C,IAAI,CAA2C,CAAC;IAClD,CAAC;CAgRF;;IAvJG,OAAO,CACL,IAAI,CAAC,eAAe,CAAC,IAAI,CACvB,iDAAiD,CAClD,EAAE,OAAO,IAAI,EAAE,CACjB,CAAC;AACJ,CAAC","sourcesContent":["import type { StateMetadata } from '@metamask/base-controller';\nimport type { BridgeClientId } from '@metamask/bridge-controller';\nimport { BRIDGE_PROD_API_BASE_URL } from '@metamask/bridge-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport { numberToHex, type Hex } from '@metamask/utils';\n\nimport {\n BRIDGE_STATUS_CONTROLLER_NAME,\n DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE,\n REFRESH_INTERVAL_MS,\n} from './constants';\nimport { StatusTypes, type BridgeStatusControllerMessenger } from './types';\nimport type {\n BridgeStatusControllerState,\n StartPollingForBridgeTxStatusArgsSerialized,\n FetchFunction,\n} from './types';\nimport {\n fetchBridgeTxStatus,\n getStatusRequestWithSrcTxHash,\n} from './utils/bridge-status';\n\nconst metadata: StateMetadata<BridgeStatusControllerState> = {\n // We want to persist the bridge status state so that we can show the proper data for the Activity list\n // basically match the behavior of TransactionController\n txHistory: {\n persist: true,\n anonymous: false,\n },\n};\n\n/** The input to start polling for the {@link BridgeStatusController} */\ntype BridgeStatusPollingInput = FetchBridgeTxStatusArgs;\n\ntype SrcTxMetaId = string;\nexport type FetchBridgeTxStatusArgs = {\n bridgeTxMetaId: string;\n};\nexport class BridgeStatusController extends StaticIntervalPollingController<BridgeStatusPollingInput>()<\n typeof BRIDGE_STATUS_CONTROLLER_NAME,\n BridgeStatusControllerState,\n BridgeStatusControllerMessenger\n> {\n #pollingTokensByTxMetaId: Record<SrcTxMetaId, string> = {};\n\n readonly #clientId: BridgeClientId;\n\n readonly #fetchFn: FetchFunction;\n\n readonly #config: {\n customBridgeApiBaseUrl?: string;\n };\n\n constructor({\n messenger,\n state,\n clientId,\n fetchFn,\n config,\n }: {\n messenger: BridgeStatusControllerMessenger;\n state?: Partial<BridgeStatusControllerState>;\n clientId: BridgeClientId;\n fetchFn: FetchFunction;\n config?: {\n customBridgeApiBaseUrl?: string;\n };\n }) {\n super({\n name: BRIDGE_STATUS_CONTROLLER_NAME,\n metadata,\n messenger,\n // Restore the persisted state\n state: {\n ...DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE,\n ...state,\n },\n });\n\n this.#clientId = clientId;\n this.#fetchFn = fetchFn;\n this.#config = config ?? {};\n\n // Register action handlers\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:startPollingForBridgeTxStatus`,\n this.startPollingForBridgeTxStatus.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:wipeBridgeStatus`,\n this.wipeBridgeStatus.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:resetState`,\n this.resetState.bind(this),\n );\n\n // Set interval\n this.setIntervalLength(REFRESH_INTERVAL_MS);\n\n // If you close the extension, but keep the browser open, the polling continues\n // If you close the browser, the polling stops\n // Check for historyItems that do not have a status of complete and restart polling\n this.#restartPollingForIncompleteHistoryItems();\n }\n\n resetState = () => {\n this.update((state) => {\n state.txHistory = DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE.txHistory;\n });\n };\n\n wipeBridgeStatus = ({\n address,\n ignoreNetwork,\n }: {\n address: string;\n ignoreNetwork: boolean;\n }) => {\n // Wipe all networks for this address\n if (ignoreNetwork) {\n this.update((state) => {\n state.txHistory = DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE.txHistory;\n });\n } else {\n const { selectedNetworkClientId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n const selectedNetworkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n const selectedChainId = selectedNetworkClient.configuration.chainId;\n\n this.#wipeBridgeStatusByChainId(address, selectedChainId);\n }\n };\n\n readonly #restartPollingForIncompleteHistoryItems = () => {\n // Check for historyItems that do not have a status of complete and restart polling\n const { txHistory } = this.state;\n const historyItems = Object.values(txHistory);\n const incompleteHistoryItems = historyItems\n .filter(\n (historyItem) =>\n historyItem.status.status === StatusTypes.PENDING ||\n historyItem.status.status === StatusTypes.UNKNOWN,\n )\n .filter((historyItem) => {\n // Check if we are already polling this tx, if so, skip restarting polling for that\n const srcTxMetaId = historyItem.txMetaId;\n const pollingToken = this.#pollingTokensByTxMetaId[srcTxMetaId];\n return !pollingToken;\n });\n\n incompleteHistoryItems.forEach((historyItem) => {\n const bridgeTxMetaId = historyItem.txMetaId;\n\n // We manually call startPolling() here rather than go through startPollingForBridgeTxStatus()\n // because we don't want to overwrite the existing historyItem in state\n this.#pollingTokensByTxMetaId[bridgeTxMetaId] = this.startPolling({\n bridgeTxMetaId,\n });\n });\n };\n\n startPollingForBridgeTxStatus = (\n startPollingForBridgeTxStatusArgs: StartPollingForBridgeTxStatusArgsSerialized,\n ) => {\n const {\n bridgeTxMeta,\n statusRequest,\n quoteResponse,\n startTime,\n slippagePercentage,\n initialDestAssetBalance,\n targetContractAddress,\n } = startPollingForBridgeTxStatusArgs;\n const accountAddress = this.#getMultichainSelectedAccountAddress();\n // Write all non-status fields to state so we can reference the quote in Activity list without the Bridge API\n // We know it's in progress but not the exact status yet\n const txHistoryItem = {\n txMetaId: bridgeTxMeta.id,\n quote: quoteResponse.quote,\n startTime,\n estimatedProcessingTimeInSeconds:\n quoteResponse.estimatedProcessingTimeInSeconds,\n slippagePercentage,\n pricingData: {\n amountSent: quoteResponse.sentAmount.amount,\n amountSentInUsd: quoteResponse.sentAmount.usd ?? undefined,\n quotedGasInUsd: quoteResponse.gasFee.usd ?? undefined,\n quotedReturnInUsd: quoteResponse.toTokenAmount.usd ?? undefined,\n },\n initialDestAssetBalance,\n targetContractAddress,\n account: accountAddress,\n status: {\n // We always have a PENDING status when we start polling for a tx, don't need the Bridge API for that\n // Also we know the bare minimum fields for status at this point in time\n status: StatusTypes.PENDING,\n srcChain: {\n chainId: statusRequest.srcChainId,\n txHash: statusRequest.srcTxHash,\n },\n },\n hasApprovalTx: Boolean(quoteResponse.approval),\n };\n this.update((state) => {\n // Use the txMeta.id as the key so we can reference the txMeta in TransactionController\n state.txHistory[bridgeTxMeta.id] = txHistoryItem;\n });\n\n this.#pollingTokensByTxMetaId[bridgeTxMeta.id] = this.startPolling({\n bridgeTxMetaId: bridgeTxMeta.id,\n });\n };\n\n // This will be called after you call this.startPolling()\n // The args passed in are the args you passed in to startPolling()\n _executePoll = async (pollingInput: BridgeStatusPollingInput) => {\n await this.#fetchBridgeTxStatus(pollingInput);\n };\n\n #getMultichainSelectedAccountAddress() {\n return (\n this.messagingSystem.call(\n 'AccountsController:getSelectedMultichainAccount',\n )?.address ?? ''\n );\n }\n\n readonly #fetchBridgeTxStatus = async ({\n bridgeTxMetaId,\n }: FetchBridgeTxStatusArgs) => {\n const { txHistory } = this.state;\n\n try {\n // We try here because we receive 500 errors from Bridge API if we try to fetch immediately after submitting the source tx\n // Oddly mostly happens on Optimism, never on Arbitrum. By the 2nd fetch, the Bridge API responds properly.\n // Also srcTxHash may not be available immediately for STX, so we don't want to fetch in those cases\n const historyItem = txHistory[bridgeTxMetaId];\n const srcTxHash = this.#getSrcTxHash(bridgeTxMetaId);\n if (!srcTxHash) {\n return;\n }\n\n this.#updateSrcTxHash(bridgeTxMetaId, srcTxHash);\n\n const statusRequest = getStatusRequestWithSrcTxHash(\n historyItem.quote,\n srcTxHash,\n );\n const status = await fetchBridgeTxStatus(\n statusRequest,\n this.#clientId,\n this.#fetchFn,\n this.#config.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n );\n const newBridgeHistoryItem = {\n ...historyItem,\n status,\n completionTime:\n status.status === StatusTypes.COMPLETE ||\n status.status === StatusTypes.FAILED\n ? Date.now()\n : undefined, // TODO make this more accurate by looking up dest txHash block time\n };\n\n // No need to purge these on network change or account change, TransactionController does not purge either.\n // TODO In theory we can skip checking status if it's not the current account/network\n // we need to keep track of the account that this is associated with as well so that we don't show it in Activity list for other accounts\n // First stab at this will not stop polling when you are on a different account\n this.update((state) => {\n state.txHistory[bridgeTxMetaId] = newBridgeHistoryItem;\n });\n\n const pollingToken = this.#pollingTokensByTxMetaId[bridgeTxMetaId];\n\n if (\n (status.status === StatusTypes.COMPLETE ||\n status.status === StatusTypes.FAILED) &&\n pollingToken\n ) {\n this.stopPollingByPollingToken(pollingToken);\n\n if (status.status === StatusTypes.COMPLETE) {\n this.messagingSystem.publish(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:bridgeTransactionComplete`,\n { bridgeHistoryItem: newBridgeHistoryItem },\n );\n }\n if (status.status === StatusTypes.FAILED) {\n this.messagingSystem.publish(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:bridgeTransactionFailed`,\n { bridgeHistoryItem: newBridgeHistoryItem },\n );\n }\n }\n } catch (e) {\n console.log('Failed to fetch bridge tx status', e);\n }\n };\n\n readonly #getSrcTxHash = (bridgeTxMetaId: string): string | undefined => {\n const { txHistory } = this.state;\n // Prefer the srcTxHash from bridgeStatusState so we don't have to l ook up in TransactionController\n // But it is possible to have bridgeHistoryItem in state without the srcTxHash yet when it is an STX\n const srcTxHash = txHistory[bridgeTxMetaId].status.srcChain.txHash;\n\n if (srcTxHash) {\n return srcTxHash;\n }\n\n // Look up in TransactionController if txMeta has been updated with the srcTxHash\n const txControllerState = this.messagingSystem.call(\n 'TransactionController:getState',\n );\n const txMeta = txControllerState.transactions.find(\n (tx) => tx.id === bridgeTxMetaId,\n );\n return txMeta?.hash;\n };\n\n readonly #updateSrcTxHash = (bridgeTxMetaId: string, srcTxHash: string) => {\n const { txHistory } = this.state;\n if (txHistory[bridgeTxMetaId].status.srcChain.txHash) {\n return;\n }\n\n this.update((state) => {\n state.txHistory[bridgeTxMetaId].status.srcChain.txHash = srcTxHash;\n });\n };\n\n // Wipes the bridge status for the given address and chainId\n // Will match only source chainId to the selectedChainId\n readonly #wipeBridgeStatusByChainId = (\n address: string,\n selectedChainId: Hex,\n ) => {\n const sourceTxMetaIdsToDelete = Object.keys(this.state.txHistory).filter(\n (txMetaId) => {\n const bridgeHistoryItem = this.state.txHistory[txMetaId];\n\n const hexSourceChainId = numberToHex(\n bridgeHistoryItem.quote.srcChainId,\n );\n\n return (\n bridgeHistoryItem.account === address &&\n hexSourceChainId === selectedChainId\n );\n },\n );\n\n sourceTxMetaIdsToDelete.forEach((sourceTxMetaId) => {\n const pollingToken = this.#pollingTokensByTxMetaId[sourceTxMetaId];\n\n if (pollingToken) {\n this.stopPollingByPollingToken(\n this.#pollingTokensByTxMetaId[sourceTxMetaId],\n );\n }\n });\n\n this.update((state) => {\n state.txHistory = sourceTxMetaIdsToDelete.reduce(\n (acc, sourceTxMetaId) => {\n delete acc[sourceTxMetaId];\n return acc;\n },\n state.txHistory,\n );\n });\n };\n}\n"]}
|
1
|
+
{"version":3,"file":"bridge-status-controller.mjs","sourceRoot":"","sources":["../src/bridge-status-controller.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,OAAO,EACL,kBAAkB,EAClB,mBAAmB,EACnB,SAAS,EACT,eAAe,EACf,eAAe,EAEhB,oCAAoC;AAMrC,OAAO,EAAE,KAAK,EAAE,mCAAmC;AACnD,OAAO,EAAE,cAAc,EAAE,8BAA8B;AACvD,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAK/E,OAAO,EACL,iBAAiB,EACjB,eAAe,EAEhB,yCAAyC;AAE1C,OAAO,EAAE,WAAW,EAAY,wBAAwB;AACxD,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAEzC,OAAO,EACL,wBAAwB,EACxB,6BAA6B,EAC7B,sCAAsC,EACtC,mBAAmB,EACpB,wBAAoB;AACrB,OAAO,EAAE,WAAW,EAAwC,oBAAgB;AAQ5E,OAAO,EACL,mBAAmB,EACnB,6BAA6B,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gC,EAChE,IAAI,CAAC,6BAA6B,CAAC,IAAI,CAAC,IAAI,CAAC,CAC9C,CAAC;QACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,GAAG,6BAA6B,mBAAmB,EACnD,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,CACjC,CAAC;QACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,GAAG,6BAA6B,aAAa,EAC7C,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAC3B,CAAC;QACF,IAAI,CAAC,eAAe,CAAC,qBAAqB,CACxC,GAAG,6BAA6B,WAAW,EAC3C,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CACzB,CAAC;QAEF,eAAe;QACf,IAAI,CAAC,iBAAiB,CAAC,mBAAmB,CAAC,CAAC;QAE5C,+EAA+E;QAC/E,8CAA8C;QAC9C,mFAAmF;QACnF,uBAAA,IAAI,uEAAyC,MAA7C,IAAI,CAA2C,CAAC;IAClD,CAAC;CAqoBF;;IArgBG,OAAO,IAAI,CAAC,eAAe,CAAC,IAAI,CAC9B,iDAAiD,CAClD,CAAC;AACJ,CAAC;IAGC,OAAO,uBAAA,IAAI,+FAA8B,MAAlC,IAAI,CAAgC,EAAE,OAAO,IAAI,EAAE,CAAC;AAC7D,CAAC","sourcesContent":["import type { StateMetadata } from '@metamask/base-controller';\nimport {\n formatChainIdToHex,\n getEthUsdtResetData,\n isEthUsdt,\n isNativeAddress,\n isSolanaChainId,\n type QuoteResponse,\n} from '@metamask/bridge-controller';\nimport type {\n BridgeAsset,\n QuoteMetadata,\n TxData,\n} from '@metamask/bridge-controller';\nimport { toHex } from '@metamask/controller-utils';\nimport { EthAccountType } from '@metamask/keyring-api';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type {\n TransactionController,\n TransactionParams,\n} from '@metamask/transaction-controller';\nimport {\n TransactionStatus,\n TransactionType,\n type TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { UserOperationController } from '@metamask/user-operation-controller';\nimport { numberToHex, type Hex } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n BRIDGE_PROD_API_BASE_URL,\n BRIDGE_STATUS_CONTROLLER_NAME,\n DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE,\n REFRESH_INTERVAL_MS,\n} from './constants';\nimport { StatusTypes, type BridgeStatusControllerMessenger } from './types';\nimport type {\n BridgeStatusControllerState,\n StartPollingForBridgeTxStatusArgsSerialized,\n FetchFunction,\n BridgeClientId,\n SolanaTransactionMeta,\n} from './types';\nimport {\n fetchBridgeTxStatus,\n getStatusRequestWithSrcTxHash,\n} from './utils/bridge-status';\nimport { getTxGasEstimates } from './utils/gas';\nimport {\n getKeyringRequest,\n getStatusRequestParams,\n getTxMetaFields,\n handleLineaDelay,\n handleSolanaTxResponse,\n} from './utils/transaction';\nimport { generateActionId } from './utils/transaction';\n\nconst metadata: StateMetadata<BridgeStatusControllerState> = {\n // We want to persist the bridge status state so that we can show the proper data for the Activity list\n // basically match the behavior of TransactionController\n txHistory: {\n persist: true,\n anonymous: false,\n },\n};\n\n/** The input to start polling for the {@link BridgeStatusController} */\ntype BridgeStatusPollingInput = FetchBridgeTxStatusArgs;\n\ntype SrcTxMetaId = string;\nexport type FetchBridgeTxStatusArgs = {\n bridgeTxMetaId: string;\n};\nexport class BridgeStatusController extends StaticIntervalPollingController<BridgeStatusPollingInput>()<\n typeof BRIDGE_STATUS_CONTROLLER_NAME,\n BridgeStatusControllerState,\n BridgeStatusControllerMessenger\n> {\n #pollingTokensByTxMetaId: Record<SrcTxMetaId, string> = {};\n\n readonly #clientId: BridgeClientId;\n\n readonly #fetchFn: FetchFunction;\n\n readonly #config: {\n customBridgeApiBaseUrl: string;\n };\n\n readonly #addTransactionFn: typeof TransactionController.prototype.addTransaction;\n\n readonly #estimateGasFeeFn: typeof TransactionController.prototype.estimateGasFee;\n\n readonly #addUserOperationFromTransactionFn?: typeof UserOperationController.prototype.addUserOperationFromTransaction;\n\n constructor({\n messenger,\n state,\n clientId,\n fetchFn,\n addTransactionFn,\n addUserOperationFromTransactionFn,\n estimateGasFeeFn,\n config,\n }: {\n messenger: BridgeStatusControllerMessenger;\n state?: Partial<BridgeStatusControllerState>;\n clientId: BridgeClientId;\n fetchFn: FetchFunction;\n addTransactionFn: typeof TransactionController.prototype.addTransaction;\n estimateGasFeeFn: typeof TransactionController.prototype.estimateGasFee;\n addUserOperationFromTransactionFn?: typeof UserOperationController.prototype.addUserOperationFromTransaction;\n config?: {\n customBridgeApiBaseUrl?: string;\n };\n }) {\n super({\n name: BRIDGE_STATUS_CONTROLLER_NAME,\n metadata,\n messenger,\n // Restore the persisted state\n state: {\n ...DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE,\n ...state,\n },\n });\n\n this.#clientId = clientId;\n this.#fetchFn = fetchFn;\n this.#addTransactionFn = addTransactionFn;\n this.#addUserOperationFromTransactionFn = addUserOperationFromTransactionFn;\n this.#estimateGasFeeFn = estimateGasFeeFn;\n this.#config = {\n customBridgeApiBaseUrl:\n config?.customBridgeApiBaseUrl ?? BRIDGE_PROD_API_BASE_URL,\n };\n\n // Register action handlers\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:startPollingForBridgeTxStatus`,\n this.startPollingForBridgeTxStatus.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:wipeBridgeStatus`,\n this.wipeBridgeStatus.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:resetState`,\n this.resetState.bind(this),\n );\n this.messagingSystem.registerActionHandler(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:submitTx`,\n this.submitTx.bind(this),\n );\n\n // Set interval\n this.setIntervalLength(REFRESH_INTERVAL_MS);\n\n // If you close the extension, but keep the browser open, the polling continues\n // If you close the browser, the polling stops\n // Check for historyItems that do not have a status of complete and restart polling\n this.#restartPollingForIncompleteHistoryItems();\n }\n\n resetState = () => {\n this.update((state) => {\n state.txHistory = DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE.txHistory;\n });\n };\n\n wipeBridgeStatus = ({\n address,\n ignoreNetwork,\n }: {\n address: string;\n ignoreNetwork: boolean;\n }) => {\n // Wipe all networks for this address\n if (ignoreNetwork) {\n this.update((state) => {\n state.txHistory = DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE.txHistory;\n });\n } else {\n const { selectedNetworkClientId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n const selectedNetworkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n const selectedChainId = selectedNetworkClient.configuration.chainId;\n\n this.#wipeBridgeStatusByChainId(address, selectedChainId);\n }\n };\n\n readonly #restartPollingForIncompleteHistoryItems = () => {\n // Check for historyItems that do not have a status of complete and restart polling\n const { txHistory } = this.state;\n const historyItems = Object.values(txHistory);\n const incompleteHistoryItems = historyItems\n .filter(\n (historyItem) =>\n historyItem.status.status === StatusTypes.PENDING ||\n historyItem.status.status === StatusTypes.UNKNOWN,\n )\n .filter((historyItem) => {\n // Check if we are already polling this tx, if so, skip restarting polling for that\n const srcTxMetaId = historyItem.txMetaId;\n const pollingToken = this.#pollingTokensByTxMetaId[srcTxMetaId];\n return !pollingToken;\n });\n\n incompleteHistoryItems.forEach((historyItem) => {\n const bridgeTxMetaId = historyItem.txMetaId;\n\n // We manually call startPolling() here rather than go through startPollingForBridgeTxStatus()\n // because we don't want to overwrite the existing historyItem in state\n this.#pollingTokensByTxMetaId[bridgeTxMetaId] = this.startPolling({\n bridgeTxMetaId,\n });\n });\n };\n\n /**\n * Starts polling for the bridge tx status\n *\n * @param startPollingForBridgeTxStatusArgs - The args to start polling for the bridge tx status\n */\n startPollingForBridgeTxStatus = (\n startPollingForBridgeTxStatusArgs: StartPollingForBridgeTxStatusArgsSerialized,\n ) => {\n const {\n bridgeTxMeta,\n statusRequest,\n quoteResponse,\n startTime,\n slippagePercentage,\n initialDestAssetBalance,\n targetContractAddress,\n approvalTxId,\n } = startPollingForBridgeTxStatusArgs;\n const accountAddress = this.#getMultichainSelectedAccountAddress();\n // Write all non-status fields to state so we can reference the quote in Activity list without the Bridge API\n // We know it's in progress but not the exact status yet\n const txHistoryItem = {\n txMetaId: bridgeTxMeta.id,\n quote: quoteResponse.quote,\n startTime,\n estimatedProcessingTimeInSeconds:\n quoteResponse.estimatedProcessingTimeInSeconds,\n slippagePercentage,\n pricingData: {\n amountSent: quoteResponse.sentAmount.amount,\n amountSentInUsd: quoteResponse.sentAmount.usd ?? undefined,\n quotedGasInUsd: quoteResponse.gasFee.usd ?? undefined,\n quotedReturnInUsd: quoteResponse.toTokenAmount.usd ?? undefined,\n },\n initialDestAssetBalance,\n targetContractAddress,\n account: accountAddress,\n status: {\n // We always have a PENDING status when we start polling for a tx, don't need the Bridge API for that\n // Also we know the bare minimum fields for status at this point in time\n status: StatusTypes.PENDING,\n srcChain: {\n chainId: statusRequest.srcChainId,\n txHash: statusRequest.srcTxHash,\n },\n },\n hasApprovalTx: Boolean(quoteResponse.approval),\n approvalTxId,\n };\n this.update((state) => {\n // Use the txMeta.id as the key so we can reference the txMeta in TransactionController\n state.txHistory[bridgeTxMeta.id] = txHistoryItem;\n });\n\n this.#pollingTokensByTxMetaId[bridgeTxMeta.id] = this.startPolling({\n bridgeTxMetaId: bridgeTxMeta.id,\n });\n };\n\n // This will be called after you call this.startPolling()\n // The args passed in are the args you passed in to startPolling()\n _executePoll = async (pollingInput: BridgeStatusPollingInput) => {\n await this.#fetchBridgeTxStatus(pollingInput);\n };\n\n #getMultichainSelectedAccount() {\n return this.messagingSystem.call(\n 'AccountsController:getSelectedMultichainAccount',\n );\n }\n\n #getMultichainSelectedAccountAddress() {\n return this.#getMultichainSelectedAccount()?.address ?? '';\n }\n\n readonly #fetchBridgeTxStatus = async ({\n bridgeTxMetaId,\n }: FetchBridgeTxStatusArgs) => {\n const { txHistory } = this.state;\n\n try {\n // We try here because we receive 500 errors from Bridge API if we try to fetch immediately after submitting the source tx\n // Oddly mostly happens on Optimism, never on Arbitrum. By the 2nd fetch, the Bridge API responds properly.\n // Also srcTxHash may not be available immediately for STX, so we don't want to fetch in those cases\n const historyItem = txHistory[bridgeTxMetaId];\n const srcTxHash = this.#getSrcTxHash(bridgeTxMetaId);\n if (!srcTxHash) {\n return;\n }\n\n this.#updateSrcTxHash(bridgeTxMetaId, srcTxHash);\n\n const statusRequest = getStatusRequestWithSrcTxHash(\n historyItem.quote,\n srcTxHash,\n );\n const status = await fetchBridgeTxStatus(\n statusRequest,\n this.#clientId,\n this.#fetchFn,\n this.#config.customBridgeApiBaseUrl,\n );\n const newBridgeHistoryItem = {\n ...historyItem,\n status,\n completionTime:\n status.status === StatusTypes.COMPLETE ||\n status.status === StatusTypes.FAILED\n ? Date.now()\n : undefined, // TODO make this more accurate by looking up dest txHash block time\n };\n\n // No need to purge these on network change or account change, TransactionController does not purge either.\n // TODO In theory we can skip checking status if it's not the current account/network\n // we need to keep track of the account that this is associated with as well so that we don't show it in Activity list for other accounts\n // First stab at this will not stop polling when you are on a different account\n this.update((state) => {\n state.txHistory[bridgeTxMetaId] = newBridgeHistoryItem;\n });\n\n const pollingToken = this.#pollingTokensByTxMetaId[bridgeTxMetaId];\n\n if (\n (status.status === StatusTypes.COMPLETE ||\n status.status === StatusTypes.FAILED) &&\n pollingToken\n ) {\n this.stopPollingByPollingToken(pollingToken);\n\n if (status.status === StatusTypes.COMPLETE) {\n this.messagingSystem.publish(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:bridgeTransactionComplete`,\n { bridgeHistoryItem: newBridgeHistoryItem },\n );\n }\n if (status.status === StatusTypes.FAILED) {\n this.messagingSystem.publish(\n `${BRIDGE_STATUS_CONTROLLER_NAME}:bridgeTransactionFailed`,\n { bridgeHistoryItem: newBridgeHistoryItem },\n );\n }\n }\n } catch (e) {\n console.log('Failed to fetch bridge tx status', e);\n }\n };\n\n readonly #getSrcTxHash = (bridgeTxMetaId: string): string | undefined => {\n const { txHistory } = this.state;\n // Prefer the srcTxHash from bridgeStatusState so we don't have to l ook up in TransactionController\n // But it is possible to have bridgeHistoryItem in state without the srcTxHash yet when it is an STX\n const srcTxHash = txHistory[bridgeTxMetaId].status.srcChain.txHash;\n\n if (srcTxHash) {\n return srcTxHash;\n }\n\n // Look up in TransactionController if txMeta has been updated with the srcTxHash\n const txControllerState = this.messagingSystem.call(\n 'TransactionController:getState',\n );\n const txMeta = txControllerState.transactions.find(\n (tx: TransactionMeta) => tx.id === bridgeTxMetaId,\n );\n return txMeta?.hash;\n };\n\n readonly #updateSrcTxHash = (bridgeTxMetaId: string, srcTxHash: string) => {\n const { txHistory } = this.state;\n if (txHistory[bridgeTxMetaId].status.srcChain.txHash) {\n return;\n }\n\n this.update((state) => {\n state.txHistory[bridgeTxMetaId].status.srcChain.txHash = srcTxHash;\n });\n };\n\n // Wipes the bridge status for the given address and chainId\n // Will match only source chainId to the selectedChainId\n readonly #wipeBridgeStatusByChainId = (\n address: string,\n selectedChainId: Hex,\n ) => {\n const sourceTxMetaIdsToDelete = Object.keys(this.state.txHistory).filter(\n (txMetaId) => {\n const bridgeHistoryItem = this.state.txHistory[txMetaId];\n\n const hexSourceChainId = numberToHex(\n bridgeHistoryItem.quote.srcChainId,\n );\n\n return (\n bridgeHistoryItem.account === address &&\n hexSourceChainId === selectedChainId\n );\n },\n );\n\n sourceTxMetaIdsToDelete.forEach((sourceTxMetaId) => {\n const pollingToken = this.#pollingTokensByTxMetaId[sourceTxMetaId];\n\n if (pollingToken) {\n this.stopPollingByPollingToken(\n this.#pollingTokensByTxMetaId[sourceTxMetaId],\n );\n }\n });\n\n this.update((state) => {\n state.txHistory = sourceTxMetaIdsToDelete.reduce(\n (acc, sourceTxMetaId) => {\n delete acc[sourceTxMetaId];\n return acc;\n },\n state.txHistory,\n );\n });\n };\n\n /**\n * ******************************************************\n * TX SUBMISSION HANDLING\n *******************************************************\n */\n\n /**\n * Submits the transaction to the snap using the keyring rpc method\n * This adds an approval tx to the ApprovalsController in the background\n * The client needs to handle the approval tx by redirecting to the confirmation page with the approvalTxId in the URL\n *\n * @param quoteResponse - The quote response\n * @param quoteResponse.quote - The quote\n * @returns The transaction meta\n */\n readonly #handleSolanaTx = async (\n quoteResponse: QuoteResponse<string> & QuoteMetadata,\n ) => {\n const selectedAccount = this.#getMultichainSelectedAccount();\n if (!selectedAccount) {\n throw new Error(\n 'Failed to submit cross-chain swap transaction: undefined multichain account',\n );\n }\n if (\n !selectedAccount.metadata?.snap?.id ||\n !selectedAccount.options?.scope\n ) {\n throw new Error(\n 'Failed to submit cross-chain swap transaction: undefined snap id or scope',\n );\n }\n const keyringRequest = getKeyringRequest(quoteResponse, selectedAccount);\n const keyringResponse = (await this.messagingSystem.call(\n 'SnapController:handleRequest',\n keyringRequest,\n )) as string | { result: Record<string, string> };\n\n // The extension client actually redirects before it can do anytyhing with this meta\n const txMeta = handleSolanaTxResponse(\n keyringResponse,\n quoteResponse,\n selectedAccount,\n );\n\n // TODO remove this eventually, just returning it now to match extension behavior\n // OR if the snap can propagate the snapRequestId or keyringReqId to the ApprovalsController, this can return the approvalTxId instead and clients won't need to subscribe to the ApprovalsController state to redirect\n return txMeta;\n };\n\n readonly #waitForHashAndReturnFinalTxMeta = async (\n hashPromise?:\n | Awaited<ReturnType<TransactionController['addTransaction']>>['result']\n | Awaited<\n ReturnType<UserOperationController['addUserOperationFromTransaction']>\n >['hash'],\n ): Promise<TransactionMeta | undefined> => {\n const transactionHash = await hashPromise;\n const finalTransactionMeta: TransactionMeta | undefined =\n this.messagingSystem\n .call('TransactionController:getState')\n .transactions.find(\n (tx: TransactionMeta) => tx.hash === transactionHash,\n );\n return finalTransactionMeta;\n };\n\n readonly #handleApprovalTx = async (\n quoteResponse: QuoteResponse<string | TxData> & QuoteMetadata,\n ): Promise<TransactionMeta | undefined> => {\n if (quoteResponse.approval) {\n await this.#handleUSDTAllowanceReset(quoteResponse);\n const approvalTxMeta = await this.#handleEvmTransaction(\n TransactionType.bridgeApproval,\n quoteResponse.approval,\n quoteResponse,\n );\n if (!approvalTxMeta) {\n throw new Error(\n 'Failed to submit bridge tx: approval txMeta is undefined',\n );\n }\n\n await handleLineaDelay(quoteResponse);\n return approvalTxMeta;\n }\n return undefined;\n };\n\n readonly #handleEvmSmartTransaction = async (\n trade: TxData,\n quoteResponse: Omit<QuoteResponse, 'approval' | 'trade'> & QuoteMetadata,\n approvalTxId?: string,\n ) => {\n return await this.#handleEvmTransaction(\n TransactionType.bridge,\n trade,\n quoteResponse,\n approvalTxId,\n false, // Set to false to indicate we don't want to wait for hash\n );\n };\n\n /**\n * Submits an EVM transaction to the TransactionController\n *\n * @param transactionType - The type of transaction to submit\n * @param trade - The trade data to confirm\n * @param quoteResponse - The quote response\n * @param quoteResponse.quote - The quote\n * @param approvalTxId - The tx id of the approval tx\n * @param shouldWaitForHash - Whether to wait for the hash of the transaction\n * @returns The transaction meta\n */\n readonly #handleEvmTransaction = async (\n transactionType: TransactionType,\n trade: TxData,\n quoteResponse: Omit<QuoteResponse, 'approval' | 'trade'> & QuoteMetadata,\n approvalTxId?: string,\n shouldWaitForHash = true,\n ): Promise<TransactionMeta | undefined> => {\n const actionId = generateActionId().toString();\n\n const selectedAccount = this.messagingSystem.call(\n 'AccountsController:getAccountByAddress',\n trade.from,\n );\n if (!selectedAccount) {\n throw new Error(\n 'Failed to submit cross-chain swap transaction: unknown account in trade data',\n );\n }\n const hexChainId = formatChainIdToHex(trade.chainId);\n const networkClientId = this.messagingSystem.call(\n 'NetworkController:findNetworkClientIdByChainId',\n hexChainId,\n );\n\n const requestOptions = {\n actionId,\n networkClientId,\n requireApproval: false,\n type: transactionType,\n origin: 'metamask',\n };\n const transactionParams: Parameters<\n TransactionController['addTransaction']\n >[0] = {\n ...trade,\n chainId: hexChainId,\n gasLimit: trade.gasLimit?.toString(),\n gas: trade.gasLimit?.toString(),\n };\n const transactionParamsWithMaxGas: TransactionParams = {\n ...transactionParams,\n ...(await this.#calculateGasFees(\n transactionParams,\n networkClientId,\n hexChainId,\n )),\n };\n\n let result:\n | Awaited<ReturnType<TransactionController['addTransaction']>>['result']\n | Awaited<\n ReturnType<UserOperationController['addUserOperationFromTransaction']>\n >['hash']\n | undefined;\n let transactionMeta: TransactionMeta | undefined;\n\n const isSmartContractAccount =\n selectedAccount.type === EthAccountType.Erc4337;\n if (isSmartContractAccount && this.#addUserOperationFromTransactionFn) {\n const smartAccountTxResult =\n await this.#addUserOperationFromTransactionFn(\n transactionParamsWithMaxGas,\n requestOptions,\n );\n result = smartAccountTxResult.transactionHash;\n transactionMeta = {\n ...requestOptions,\n chainId: hexChainId,\n txParams: transactionParamsWithMaxGas,\n time: Date.now(),\n id: smartAccountTxResult.id,\n status: TransactionStatus.confirmed,\n };\n } else {\n const addTransactionResult = await this.#addTransactionFn(\n transactionParamsWithMaxGas,\n requestOptions,\n );\n result = addTransactionResult.result;\n transactionMeta = addTransactionResult.transactionMeta;\n }\n\n if (shouldWaitForHash) {\n return await this.#waitForHashAndReturnFinalTxMeta(result);\n }\n\n // TODO why is this needed?\n // Note that updateTransaction doesn't actually error if you add fields that don't conform the to the txMeta type\n // they will be there at runtime, but you just don't get any type safety checks on them\n // const fieldsToAddToTxMeta = getTxMetaFields(quoteResponse, approvalTxId);\n // dispatch(updateTransaction(completeTxMeta);\n\n return {\n ...getTxMetaFields(quoteResponse, approvalTxId),\n ...transactionMeta,\n };\n };\n\n // Only adds tokens if the source or dest chain is an EVM chain bc non-evm tokens\n // are detected by the multichain asset controllers\n readonly #addTokens = (asset: BridgeAsset) => {\n if (isNativeAddress(asset.address) || isSolanaChainId(asset.chainId)) {\n return;\n }\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.messagingSystem.call(\n 'TokensController:addDetectedTokens',\n [\n {\n address: asset.address,\n decimals: asset.decimals,\n image: asset.iconUrl,\n name: asset.name,\n symbol: asset.symbol,\n },\n ],\n {\n chainId: formatChainIdToHex(asset.chainId),\n selectedAddress: this.#getMultichainSelectedAccountAddress(),\n },\n );\n };\n\n readonly #handleUSDTAllowanceReset = async (\n quoteResponse: QuoteResponse<TxData | string> & QuoteMetadata,\n ) => {\n const hexChainId = formatChainIdToHex(quoteResponse.quote.srcChainId);\n if (\n quoteResponse.approval &&\n isEthUsdt(hexChainId, quoteResponse.quote.srcAsset.address)\n ) {\n const allowance = new BigNumber(\n await this.messagingSystem.call(\n 'BridgeController:getBridgeERC20Allowance',\n quoteResponse.quote.srcAsset.address,\n hexChainId,\n ),\n );\n const shouldResetApproval =\n allowance.lt(quoteResponse.sentAmount.amount) && allowance.gt(0);\n if (shouldResetApproval) {\n await this.#handleEvmTransaction(\n TransactionType.bridgeApproval,\n { ...quoteResponse.approval, data: getEthUsdtResetData() },\n quoteResponse,\n );\n }\n }\n };\n\n readonly #calculateGasFees = async (\n transactionParams: TransactionParams,\n networkClientId: string,\n chainId: Hex,\n ) => {\n const { gasFeeEstimates } = this.messagingSystem.call(\n 'GasFeeController:getState',\n );\n const { estimates: txGasFeeEstimates } = await this.#estimateGasFeeFn({\n transactionParams,\n chainId,\n networkClientId,\n });\n const { maxFeePerGas, maxPriorityFeePerGas } = getTxGasEstimates({\n networkGasFeeEstimates: gasFeeEstimates,\n txGasFeeEstimates,\n });\n const maxGasLimit = toHex(transactionParams.gas ?? 0);\n\n return {\n maxFeePerGas,\n maxPriorityFeePerGas,\n gas: maxGasLimit,\n };\n };\n\n /**\n * Submits a cross-chain swap transaction\n *\n * @param quoteResponse - The quote response\n * @param isStxEnabledOnClient - Whether smart transactions are enabled on the client, for example the getSmartTransactionsEnabled selector value from the extension\n * @returns The transaction meta\n */\n submitTx = async (\n quoteResponse: QuoteResponse<TxData | string> & QuoteMetadata,\n isStxEnabledOnClient: boolean,\n ) => {\n let txMeta: (TransactionMeta & Partial<SolanaTransactionMeta>) | undefined;\n // Submit SOLANA tx\n if (\n isSolanaChainId(quoteResponse.quote.srcChainId) &&\n typeof quoteResponse.trade === 'string'\n ) {\n txMeta = await this.#handleSolanaTx(\n quoteResponse as QuoteResponse<string> & QuoteMetadata,\n );\n }\n // Submit EVM tx\n let approvalTime: number | undefined, approvalTxId: string | undefined;\n if (\n !isSolanaChainId(quoteResponse.quote.srcChainId) &&\n typeof quoteResponse.trade !== 'string'\n ) {\n // Set approval time and id if an approval tx is needed\n const approvalTxMeta = await this.#handleApprovalTx(quoteResponse);\n approvalTime = approvalTxMeta?.time;\n approvalTxId = approvalTxMeta?.id;\n // Handle smart transactions if enabled\n if (isStxEnabledOnClient) {\n txMeta = await this.#handleEvmSmartTransaction(\n quoteResponse.trade,\n quoteResponse,\n approvalTxId,\n );\n } else {\n txMeta = await this.#handleEvmTransaction(\n TransactionType.bridge,\n quoteResponse.trade,\n quoteResponse,\n approvalTxId,\n );\n }\n }\n\n if (!txMeta) {\n throw new Error('Failed to submit bridge tx: txMeta is undefined');\n }\n\n try {\n // Start polling for bridge tx status\n this.startPollingForBridgeTxStatus({\n bridgeTxMeta: txMeta, // Only the id field is used by the BridgeStatusController\n statusRequest: {\n ...getStatusRequestParams(quoteResponse),\n srcTxHash: txMeta.hash,\n },\n quoteResponse,\n slippagePercentage: 0, // TODO include slippage provided by quote if using dynamic slippage, or slippage from quote request\n startTime: approvalTime ?? Date.now(),\n approvalTxId,\n });\n // Add tokens to the token list\n this.#addTokens(quoteResponse.quote.srcAsset);\n this.#addTokens(quoteResponse.quote.destAsset);\n } catch {\n // Ignore errors here, we don't want to crash the app if this fails and tx submission succeeds\n }\n return txMeta;\n };\n}\n"]}
|
package/dist/constants.cjs
CHANGED
@@ -1,9 +1,11 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
-
exports.DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE = exports.BRIDGE_STATUS_CONTROLLER_NAME = exports.REFRESH_INTERVAL_MS = void 0;
|
3
|
+
exports.LINEA_DELAY_MS = exports.BRIDGE_PROD_API_BASE_URL = exports.DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE = exports.BRIDGE_STATUS_CONTROLLER_NAME = exports.REFRESH_INTERVAL_MS = void 0;
|
4
4
|
exports.REFRESH_INTERVAL_MS = 10 * 1000;
|
5
5
|
exports.BRIDGE_STATUS_CONTROLLER_NAME = 'BridgeStatusController';
|
6
6
|
exports.DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE = {
|
7
7
|
txHistory: {},
|
8
8
|
};
|
9
|
+
exports.BRIDGE_PROD_API_BASE_URL = 'https://bridge.api.cx.metamask.io';
|
10
|
+
exports.LINEA_DELAY_MS = 5000;
|
9
11
|
//# sourceMappingURL=constants.cjs.map
|
package/dist/constants.cjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"constants.cjs","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;AAEa,QAAA,mBAAmB,GAAG,EAAE,GAAG,IAAI,CAAC;AAEhC,QAAA,6BAA6B,GAAG,wBAAwB,CAAC;AAEzD,QAAA,sCAAsC,GACjD;IACE,SAAS,EAAE,EAAE;CACd,CAAC","sourcesContent":["import type { BridgeStatusControllerState } from './types';\n\nexport const REFRESH_INTERVAL_MS = 10 * 1000;\n\nexport const BRIDGE_STATUS_CONTROLLER_NAME = 'BridgeStatusController';\n\nexport const DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE: BridgeStatusControllerState =\n {\n txHistory: {},\n };\n"]}
|
1
|
+
{"version":3,"file":"constants.cjs","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;AAEa,QAAA,mBAAmB,GAAG,EAAE,GAAG,IAAI,CAAC;AAEhC,QAAA,6BAA6B,GAAG,wBAAwB,CAAC;AAEzD,QAAA,sCAAsC,GACjD;IACE,SAAS,EAAE,EAAE;CACd,CAAC;AAES,QAAA,wBAAwB,GAAG,mCAAmC,CAAC;AAE/D,QAAA,cAAc,GAAG,IAAI,CAAC","sourcesContent":["import type { BridgeStatusControllerState } from './types';\n\nexport const REFRESH_INTERVAL_MS = 10 * 1000;\n\nexport const BRIDGE_STATUS_CONTROLLER_NAME = 'BridgeStatusController';\n\nexport const DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE: BridgeStatusControllerState =\n {\n txHistory: {},\n };\n\nexport const BRIDGE_PROD_API_BASE_URL = 'https://bridge.api.cx.metamask.io';\n\nexport const LINEA_DELAY_MS = 5000;\n"]}
|
package/dist/constants.d.cts
CHANGED
@@ -2,4 +2,6 @@ import type { BridgeStatusControllerState } from "./types.cjs";
|
|
2
2
|
export declare const REFRESH_INTERVAL_MS: number;
|
3
3
|
export declare const BRIDGE_STATUS_CONTROLLER_NAME = "BridgeStatusController";
|
4
4
|
export declare const DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE: BridgeStatusControllerState;
|
5
|
+
export declare const BRIDGE_PROD_API_BASE_URL = "https://bridge.api.cx.metamask.io";
|
6
|
+
export declare const LINEA_DELAY_MS = 5000;
|
5
7
|
//# sourceMappingURL=constants.d.cts.map
|
package/dist/constants.d.cts.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,EAAE,oBAAgB;AAE3D,eAAO,MAAM,mBAAmB,QAAY,CAAC;AAE7C,eAAO,MAAM,6BAA6B,2BAA2B,CAAC;AAEtE,eAAO,MAAM,sCAAsC,EAAE,2BAGlD,CAAC"}
|
1
|
+
{"version":3,"file":"constants.d.cts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,EAAE,oBAAgB;AAE3D,eAAO,MAAM,mBAAmB,QAAY,CAAC;AAE7C,eAAO,MAAM,6BAA6B,2BAA2B,CAAC;AAEtE,eAAO,MAAM,sCAAsC,EAAE,2BAGlD,CAAC;AAEJ,eAAO,MAAM,wBAAwB,sCAAsC,CAAC;AAE5E,eAAO,MAAM,cAAc,OAAO,CAAC"}
|
package/dist/constants.d.mts
CHANGED
@@ -2,4 +2,6 @@ import type { BridgeStatusControllerState } from "./types.mjs";
|
|
2
2
|
export declare const REFRESH_INTERVAL_MS: number;
|
3
3
|
export declare const BRIDGE_STATUS_CONTROLLER_NAME = "BridgeStatusController";
|
4
4
|
export declare const DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE: BridgeStatusControllerState;
|
5
|
+
export declare const BRIDGE_PROD_API_BASE_URL = "https://bridge.api.cx.metamask.io";
|
6
|
+
export declare const LINEA_DELAY_MS = 5000;
|
5
7
|
//# sourceMappingURL=constants.d.mts.map
|
package/dist/constants.d.mts.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"constants.d.mts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,EAAE,oBAAgB;AAE3D,eAAO,MAAM,mBAAmB,QAAY,CAAC;AAE7C,eAAO,MAAM,6BAA6B,2BAA2B,CAAC;AAEtE,eAAO,MAAM,sCAAsC,EAAE,2BAGlD,CAAC"}
|
1
|
+
{"version":3,"file":"constants.d.mts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,EAAE,oBAAgB;AAE3D,eAAO,MAAM,mBAAmB,QAAY,CAAC;AAE7C,eAAO,MAAM,6BAA6B,2BAA2B,CAAC;AAEtE,eAAO,MAAM,sCAAsC,EAAE,2BAGlD,CAAC;AAEJ,eAAO,MAAM,wBAAwB,sCAAsC,CAAC;AAE5E,eAAO,MAAM,cAAc,OAAO,CAAC"}
|
package/dist/constants.mjs
CHANGED
@@ -3,4 +3,6 @@ export const BRIDGE_STATUS_CONTROLLER_NAME = 'BridgeStatusController';
|
|
3
3
|
export const DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE = {
|
4
4
|
txHistory: {},
|
5
5
|
};
|
6
|
+
export const BRIDGE_PROD_API_BASE_URL = 'https://bridge.api.cx.metamask.io';
|
7
|
+
export const LINEA_DELAY_MS = 5000;
|
6
8
|
//# sourceMappingURL=constants.mjs.map
|
package/dist/constants.mjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"constants.mjs","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7C,MAAM,CAAC,MAAM,6BAA6B,GAAG,wBAAwB,CAAC;AAEtE,MAAM,CAAC,MAAM,sCAAsC,GACjD;IACE,SAAS,EAAE,EAAE;CACd,CAAC","sourcesContent":["import type { BridgeStatusControllerState } from './types';\n\nexport const REFRESH_INTERVAL_MS = 10 * 1000;\n\nexport const BRIDGE_STATUS_CONTROLLER_NAME = 'BridgeStatusController';\n\nexport const DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE: BridgeStatusControllerState =\n {\n txHistory: {},\n };\n"]}
|
1
|
+
{"version":3,"file":"constants.mjs","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7C,MAAM,CAAC,MAAM,6BAA6B,GAAG,wBAAwB,CAAC;AAEtE,MAAM,CAAC,MAAM,sCAAsC,GACjD;IACE,SAAS,EAAE,EAAE;CACd,CAAC;AAEJ,MAAM,CAAC,MAAM,wBAAwB,GAAG,mCAAmC,CAAC;AAE5E,MAAM,CAAC,MAAM,cAAc,GAAG,IAAI,CAAC","sourcesContent":["import type { BridgeStatusControllerState } from './types';\n\nexport const REFRESH_INTERVAL_MS = 10 * 1000;\n\nexport const BRIDGE_STATUS_CONTROLLER_NAME = 'BridgeStatusController';\n\nexport const DEFAULT_BRIDGE_STATUS_CONTROLLER_STATE: BridgeStatusControllerState =\n {\n txHistory: {},\n };\n\nexport const BRIDGE_PROD_API_BASE_URL = 'https://bridge.api.cx.metamask.io';\n\nexport const LINEA_DELAY_MS = 5000;\n"]}
|