@metamask/bridge-status-controller 74.0.1 → 74.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -1
- package/dist/bridge-status-controller.cjs +57 -3
- package/dist/bridge-status-controller.cjs.map +1 -1
- package/dist/bridge-status-controller.d.cts.map +1 -1
- package/dist/bridge-status-controller.d.mts.map +1 -1
- package/dist/bridge-status-controller.mjs +59 -5
- package/dist/bridge-status-controller.mjs.map +1 -1
- package/dist/quote-status-manager/constants.cjs +17 -2
- package/dist/quote-status-manager/constants.cjs.map +1 -1
- package/dist/quote-status-manager/constants.d.cts +15 -0
- package/dist/quote-status-manager/constants.d.cts.map +1 -1
- package/dist/quote-status-manager/constants.d.mts +15 -0
- package/dist/quote-status-manager/constants.d.mts.map +1 -1
- package/dist/quote-status-manager/constants.mjs +16 -1
- package/dist/quote-status-manager/constants.mjs.map +1 -1
- package/dist/quote-status-manager/quotes-status-manager.cjs +7 -7
- package/dist/quote-status-manager/quotes-status-manager.cjs.map +1 -1
- package/dist/quote-status-manager/quotes-status-manager.d.cts +3 -1
- package/dist/quote-status-manager/quotes-status-manager.d.cts.map +1 -1
- package/dist/quote-status-manager/quotes-status-manager.d.mts +3 -1
- package/dist/quote-status-manager/quotes-status-manager.d.mts.map +1 -1
- package/dist/quote-status-manager/quotes-status-manager.mjs +7 -7
- package/dist/quote-status-manager/quotes-status-manager.mjs.map +1 -1
- package/dist/utils/bridge-status.cjs +14 -1
- package/dist/utils/bridge-status.cjs.map +1 -1
- package/dist/utils/bridge-status.d.cts +5 -0
- package/dist/utils/bridge-status.d.cts.map +1 -1
- package/dist/utils/bridge-status.d.mts +5 -0
- package/dist/utils/bridge-status.d.mts.map +1 -1
- package/dist/utils/bridge-status.mjs +12 -0
- package/dist/utils/bridge-status.mjs.map +1 -1
- package/dist/utils/snaps.cjs +14 -9
- package/dist/utils/snaps.cjs.map +1 -1
- package/dist/utils/snaps.d.cts.map +1 -1
- package/dist/utils/snaps.d.mts.map +1 -1
- package/dist/utils/snaps.mjs +15 -10
- package/dist/utils/snaps.mjs.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"quotes-status-manager.mjs","sourceRoot":"","sources":["../../src/quote-status-manager/quotes-status-manager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,iBAAiB,EAAE,yCAAyC;AAErE,OAAO,EAAE,cAAc,EAAmC,qBAAiB;AAC3E,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,cAAc,EACf,iCAA6B;AAC9B,OAAO,EACL,gBAAgB,EAChB,+BAA+B,EAC/B,iCAAiC,EACjC,wBAAwB,EACxB,oCAAoC,EACrC,wBAAoB;AACrB,OAAO,EAAE,sBAAsB,EAAE,qBAAiB;AAClD,OAAO,EAAE,qBAAqB,EAAE,uCAAmC;AACnE,OAAO,EAAE,qBAAqB,EAAE,uCAAmC;AACnE,OAAO,EAAE,mBAAmB,EAAE,qCAAiC;AAC/D,OAAO,EAAE,iCAAiC,EAAE,qDAAiD;AAG7F;;;;;;;;;GASG;AACH,MAAM,OAAO,kBAAkB;IAqB7B;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,YAAY,EACV,SAAS,EACT,QAAQ,EACR,aAAa,EACb,aAAa,EACb,UAAU,EACV,OAAO,EACP,SAAS,EACT,gBAAgB,EAChB,UAAU,EACV,gBAAgB,EAChB,WAAW,GAeZ;;QApEQ,gDAA4C;QAE5C,4DAA8C;QAE9C,4DAA8C;QAE9C,gDAAwC;QAExC,8CAAgE;QAEhE,uDAA0B;QAEnC;;;;;WAKG;QACH,8CAA0D,IAAI,EAAC;QAmD7D,uBAAA,IAAI,iCAAc,SAAS,MAAA,CAAC;QAC5B,uBAAA,IAAI,+BAAY,OAAO,MAAA,CAAC;QACxB,uBAAA,IAAI,wCAAqB,gBAAgB,MAAA,CAAC;QAC1C,uBAAA,IAAI,iCAAc,S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AAK,CAAC,MAAM,CAAC,KAAK,SAAS,SAAS,GAAG,EAC1G,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAC3B,CACF,CAAC;YACJ,CAAC;YACD,uBAAA,IAAI,wEAAe,MAAnB,IAAI,EAAgB,KAAK,CAAC,CAAC;YAC3B,OAAO;QACT,CAAC;IACH,CAAC;IAED,sEAAsE;IACtE,sEAAsE;IACtE,uBAAA,IAAI,sEAAa,MAAjB,IAAI,EAAc,KAAK,CAAC,CAAC;IACzB,uBAAA,IAAI,mCAAS,EAAE,KAAf,IAAI,EACF,IAAI,sBAAsB,CACxB,6CAA6C,EAC7C;QACE,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,SAAS,EAAE,QAAQ,EAAE,IAAI;KAC1B,CACF,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { TransactionStatus } from '@metamask/transaction-controller';\n\nimport { BridgeClientId, BridgeStatusControllerMessenger } from '../types';\nimport {\n getTransactionMetaById,\n hasNestedSwapTransactions,\n isCrossChainTx,\n} from '../utils/transaction';\nimport {\n QuoteStatusState,\n QuoteStatusStateToBackendStatus,\n QuoteStatusUpdateBackendErrorType,\n QuoteStatusBackendStatus,\n QuoteStatusFetchWithRetryOutcomeType,\n} from './constants';\nimport { QuoteStatusUpdateError } from './errors';\nimport { QuoteStatusApiService } from './quote-status-api-service';\nimport { QuoteStatusEntryStore } from './quote-status-entry-store';\nimport { QuoteStatusStateFsm } from './quote-status-state-fsm';\nimport { QuoteStatusUpdateWithRetryOutcome } from './quote-status-update-with-retry-outcome';\nimport { QuoteStatusPersistEntry, QuoteStatusRuntimeEntry } from './types';\n\n/**\n * Tracks bridge/swap quotes through their lifecycle and keeps the backend in\n * sync with the latest known status of each quote.\n *\n * Quotes are reported via {@link reportSubmitted} and {@link reportFinalised},\n * stored as runtime entries, and pushed to the backend. Updates that fail in a\n * retryable way are retried on a periodic timer until each entry reaches a\n * terminal state, at which point it is evicted and the timer stops once the\n * store is empty.\n */\nexport class QuoteStatusManager {\n readonly #messenger: BridgeStatusControllerMessenger;\n\n readonly #quoteStatusApiService: QuoteStatusApiService;\n\n readonly #quoteStatusEntryStore: QuoteStatusEntryStore;\n\n readonly #isEnabled: (() => boolean) | undefined;\n\n readonly #onError: ((error: QuoteStatusUpdateError) => void) | undefined;\n\n readonly #updateIntervalMs: number;\n\n /**\n * Handle for the periodic retry timer. While running, every\n * {@link QUOTE_STATUS_UPDATE_RETRY_INTERVAL_MS} all entries that have not yet\n * reached a terminal state (Completed/Expired) are re-processed. It is started\n * lazily when there is work to do and stopped once the store is empty.\n */\n #retryIntervalId: ReturnType<typeof setInterval> | null = null;\n\n /**\n * Creates a new manager and immediately processes any persisted entries.\n *\n * @param options - Constructor options.\n * @param options.messenger - Messenger used to communicate with the backend\n * API service.\n * @param options.clientId - Identifier of the client making the requests.\n * @param options.clientProduct - Name of the client product making the\n * requests.\n * @param options.clientVersion - Optional version of the client product.\n * @param options.apiBaseUrl - Base URL of the quote status backend API.\n * @param options.onPersistUpdates - Callback invoked to persist entry updates.\n * @param options.onError - Optional callback invoked when a non-recoverable\n * error occurs.\n * @param options.isEnabled - Optional predicate gating whether the manager\n * performs any work.\n * @param options.entryTtlMs - Time-to-live, in milliseconds, after which a\n * tracked entry is evicted.\n * @param options.updateIntervalMs - How often the manager re-processes entries that\n * have not yet reached a terminal state\n * @param options.initialData - Persisted entries to rehydrate on startup.\n */\n constructor({\n messenger,\n clientId,\n clientProduct,\n clientVersion,\n apiBaseUrl,\n onError,\n isEnabled,\n onPersistUpdates,\n entryTtlMs,\n updateIntervalMs,\n initialData,\n }: {\n messenger: BridgeStatusControllerMessenger;\n clientId: BridgeClientId;\n clientProduct: string;\n clientVersion?: string;\n apiBaseUrl: string;\n onPersistUpdates: (\n updates: Record<string, QuoteStatusPersistEntry>,\n ) => void;\n onError?: (error: QuoteStatusUpdateError) => void;\n isEnabled?: () => boolean;\n entryTtlMs: number;\n updateIntervalMs: number;\n initialData: Record<string, QuoteStatusPersistEntry>;\n }) {\n this.#isEnabled = isEnabled;\n this.#onError = onError;\n this.#updateIntervalMs = updateIntervalMs;\n this.#messenger = messenger;\n\n this.#quoteStatusApiService = new QuoteStatusApiService({\n messenger,\n clientId,\n clientProduct,\n clientVersion,\n apiBaseUrl,\n onError,\n });\n\n this.#quoteStatusEntryStore = new QuoteStatusEntryStore({\n onPersistUpdates,\n entryTtlMs,\n initial: initialData,\n });\n }\n\n /**\n * Whether quote-status tracking and backend sync are currently active.\n *\n * Reflects the latest value returned by the optional `isEnabled` predicate\n * supplied at construction time. When no predicate was provided, this is\n * always `false` and all public methods that gate on enablement no-op.\n *\n * @returns `true` when the `isEnabled` predicate returns a truthy value.\n */\n get enabled(): boolean {\n return Boolean(this.#isEnabled?.());\n }\n\n /**\n * Reports that a previously submitted quote has finalized on-chain.\n *\n * Looks up the tracked entry by its transaction metadata id, transitions it to\n * the appropriate terminal state, and processes the update. No-ops when the\n * manager is disabled, and surfaces an error when the entry is missing or\n * cannot transition to the finalized state.\n *\n * @param txMetaId - Transaction metadata id of the finalized quote.\n * @param success - Whether the transaction finalized successfully.\n */\n reportFinalised(txMetaId: string, success: boolean): void {\n if (!this.#isEnabled?.()) {\n return;\n }\n\n const entry = this.#quoteStatusEntryStore.getByTxMetaId(txMetaId);\n\n if (!entry) {\n this.#onError?.(\n new QuoteStatusUpdateError(\n 'reporting finalization status but entry was not found',\n { quoteId: '' },\n ),\n );\n return;\n }\n\n const nextState = success\n ? QuoteStatusState.FinalizedSuccess\n : QuoteStatusState.FinalizedFailed;\n\n if (!entry.status.canTransitionTo(nextState)) {\n // This is expected, there are race conditions where\n // reportFinalized can be called twice. If the second\n // call fails due to the first completed sucesfully\n // backend will report that we cannot transition outside\n // a final state, which is correct and we can safely abort\n // the flow.\n return;\n }\n\n entry.status.transitionTo(nextState);\n this.#ensureRetryTimerRunning();\n this.#processEntry(entry);\n }\n\n /**\n * Reports that a quote has been submitted on-chain and begins tracking it.\n *\n * Creates a new entry in the `Submitted` state, starts the retry timer, and\n * processes the initial status update. No-ops when the manager is disabled,\n * and surfaces an error if the entry cannot be retrieved after being stored.\n *\n * @param quoteId - Identifier of the submitted quote.\n * @param srcTxHash - Hash of the source-chain transaction for the quote.\n * @param txMetaId - Optional transaction metadata id used to correlate\n * finalization reports.\n */\n reportSubmitted(quoteId: string, srcTxHash: string, txMetaId?: string): void {\n if (!this.#isEnabled?.()) {\n return;\n }\n\n // Once a quote has advanced past `Submitted` (finalized or terminal), it is\n // done: reporting `SUBMITTED` again would be rejected by the backend as an\n // invalid transition. Retained terminal entries let us recognize and drop\n // these late/duplicate submissions instead of looping on a 400.\n const isQuoteAlreadyTracked = this.#quoteStatusEntryStore\n .getByQuoteId(quoteId)\n .some((entry) => entry.status.state !== QuoteStatusState.Submitted);\n if (isQuoteAlreadyTracked) {\n return;\n }\n\n const entryKey = QuoteStatusEntryStore.hash({\n quoteId,\n srcTxHash,\n });\n\n const entry = this.#quoteStatusEntryStore.put(entryKey, {\n quoteId,\n srcTxHash,\n txMetaId,\n status: new QuoteStatusStateFsm(QuoteStatusState.Submitted),\n });\n\n this.#ensureRetryTimerRunning();\n this.#processEntry(entry);\n }\n\n /**\n * Tears down the manager by stopping the retry timer and clearing all tracked\n * entries.\n */\n destroy(): void {\n this.#stopRetryTimer();\n this.#quoteStatusEntryStore.clear();\n }\n\n /**\n * Reconciles quote-status entries whose finalization was missed while the\n * client was closed. Called once during initialization.\n *\n * Swap/bridge source transactions report their final status through the\n * `TransactionController:transactionStatusUpdated` subscription\n * ({@link #onTransactionConfirmed}/{@link #onTransactionFailed}). When a source\n * transaction reaches a terminal state while the client is not running, that\n * event is never re-emitted on the next startup, so the persisted entry would\n * remain `Submitted` until it expires via TTL. This replays the missed terminal\n * event for both swaps and bridges: a confirmed source transaction is reported\n * as a finalized success and a failed/dropped one as a finalized failure.\n *\n * `rejected` is ignored because the transaction was never broadcast.\n */\n init(): void {\n this.#processInitial();\n\n for (const entry of this.#quoteStatusEntryStore.values()) {\n // Only entries still awaiting finalization need catching up. Entries\n // already in a finalized state are re-sent by `processInitial()`.\n if (\n entry.status.state !== QuoteStatusState.Submitted ||\n !entry.txMetaId\n ) {\n continue;\n }\n\n const txMeta = getTransactionMetaById(this.#messenger, entry.txMetaId);\n if (!txMeta) {\n continue;\n }\n\n // Reconcile swaps and bridges alike: a terminal source transaction\n // finalizes the quote status. `hasNestedSwapTransactions` also covers\n // batch/7702 swaps whose type may still read as `batch` rather than `swap`.\n const isCrossChainTrade =\n (txMeta.type !== undefined && isCrossChainTx(txMeta.type)) ||\n hasNestedSwapTransactions(txMeta);\n if (!isCrossChainTrade) {\n continue;\n }\n\n if (txMeta.status === TransactionStatus.confirmed) {\n this.reportFinalised(entry.txMetaId, true);\n } else if (\n txMeta.status === TransactionStatus.failed ||\n txMeta.status === TransactionStatus.dropped\n ) {\n this.reportFinalised(entry.txMetaId, false);\n }\n }\n }\n\n /**\n * Fetches the current quote status from the backend with automatic retries.\n *\n * Unlike {@link reportSubmitted} and {@link reportFinalised}, this is a\n * read-only query and does not mutate tracked entries. Returns `null` when\n * the manager is disabled ({@link enabled} is `false`).\n *\n * @param quoteId - Identifier of the quote whose status should be fetched.\n * @param options - Retry configuration.\n * @param options.maxRetries - Maximum number of retries after the initial attempt.\n * @param options.delayMsBetweenRetries - Delay in milliseconds between attempts.\n */\n getStatus(\n quoteId: string,\n options: {\n maxRetries?: number;\n delayMsBetweenRetries?: number;\n } = {\n maxRetries: 0,\n delayMsBetweenRetries: 1000,\n },\n ): void {\n if (!this.#isEnabled?.()) {\n return;\n }\n\n this.#quoteStatusApiService\n .getQuoteStatusWithRetry(\n {\n quoteId,\n },\n {\n maxRetries: options.maxRetries ?? 0,\n delayMsBetweenRetries: options.delayMsBetweenRetries ?? 1000,\n },\n // Errors already reported by #onError handlers of `getQuoteStatusWithRetry()`\n )\n .catch(() => undefined);\n }\n\n /**\n * Processes every entry rehydrated from persisted data on startup and starts\n * the retry timer if any entries still require further updates.\n */\n #processInitial(): void {\n for (const entry of this.#quoteStatusEntryStore.values()) {\n this.#processEntry(entry);\n }\n\n // Terminal entries (Completed/Expired) are retained, so the store is never\n // empty. Only start the retry timer when there is an entry whose status\n // still needs to be reported; otherwise it would tick forever doing nothing.\n if (this.#hasPendingUpdates()) {\n this.#ensureRetryTimerRunning();\n }\n }\n\n /**\n * Starts the periodic retry timer if it is not already running.\n *\n * The timer re-processes every non-terminal entry on each tick. It is\n * idempotent so callers can invoke it freely whenever new work is enqueued.\n */\n #ensureRetryTimerRunning(): void {\n if (this.#retryIntervalId !== null) {\n return;\n }\n\n this.#retryIntervalId = setInterval(\n () => this.#processRetries(),\n this.#updateIntervalMs,\n );\n }\n\n /**\n * Stops the periodic retry timer if it is running.\n */\n #stopRetryTimer(): void {\n if (this.#retryIntervalId !== null) {\n clearInterval(this.#retryIntervalId);\n this.#retryIntervalId = null;\n }\n }\n\n /**\n * Retry tick: re-processes every entry. Reading `values()` first transitions\n * TTL-expired entries to `Expired` (keeping them), and `#processEntry` no-ops\n * for terminal/acknowledged entries. When no entry has a status left to report\n * the timer stops until new work is enqueued.\n */\n #processRetries(): void {\n if (!this.#isEnabled?.()) {\n return;\n }\n\n // Snapshot first: `#processEntry` can mutate the store (e.g. transitioning an\n // accepted entry to a terminal state), so iterating a live iterator would be\n // unsafe.\n const entries = [...this.#quoteStatusEntryStore.values()];\n\n if (!this.#hasPendingUpdates()) {\n this.#stopRetryTimer();\n return;\n }\n\n for (const entry of entries) {\n this.#processEntry(entry);\n }\n }\n\n /**\n * Returns whether any tracked entry still has a status that needs to be\n * reported to the backend.\n *\n * Terminal entries (`Completed`/`Expired`) and entries whose current status\n * has already been acknowledged are excluded, so this is the signal used to\n * decide whether the retry timer has any work left to do.\n *\n * @returns `true` when at least one entry has an unreported status.\n */\n #hasPendingUpdates(): boolean {\n for (const entry of this.#quoteStatusEntryStore.values()) {\n const { state } = entry.status;\n const isTerminal =\n state === QuoteStatusState.Completed ||\n state === QuoteStatusState.Expired;\n if (!isTerminal && entry.acknowledgedState !== state) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Stops the retry timer when there are no entries left whose status needs\n * reporting. Since terminal entries are retained, the store is never empty, so\n * the timer's idle condition is \"no pending updates\" rather than \"no entries\".\n */\n #stopRetryTimerIfIdle(): void {\n if (!this.#hasPendingUpdates()) {\n this.#stopRetryTimer();\n }\n }\n\n /**\n * Pushes a single entry's current status to the backend and reconciles the\n * local state with the request outcome.\n *\n * Terminal entries are kept but no longer reported. Accepted finalized updates\n * advance the entry to `Completed` (kept so duplicate reports are rejected);\n * accepted non-final updates (e.g. `Submitted`) are kept tracked so a later\n * {@link reportFinalised} can find them, while being flagged so the retry loop\n * stops re-sending the acknowledged status. Updates whose status advanced\n * mid-flight are reprocessed, retryable failures are left for the next retry\n * tick, and non-retryable failures are delegated to\n * {@link #handleNonRetryableUpdateStatusError}.\n *\n * @param entry - The runtime entry to process.\n */\n #processEntry(entry: QuoteStatusRuntimeEntry): void {\n // The backend already accepted the entry's current status, so there is\n // nothing new to report. The entry is kept tracked (e.g. a `Submitted`\n // quote awaiting finalization) until its status advances past the\n // acknowledged one, at which point it is reprocessed.\n if (entry.acknowledgedState === entry.status.state) {\n return;\n }\n\n const sentStatus = entry.status.state;\n const sentStatusBackend = QuoteStatusStateToBackendStatus[sentStatus];\n\n // Terminal states (`Completed`/`Expired`) have no backend status to report.\n // The entry is retained so future interactions with the quote are rejected.\n if (sentStatusBackend === null) {\n this.#stopRetryTimerIfIdle();\n return;\n }\n\n // Re-checked before each retry attempt so an in-flight retry stops early when\n // the entry has since advanced, been acknowledged, become terminal, or\n // expired (a later `reportFinalised` re-triggers processing). This avoids\n // firing a request the backend would reject (e.g. `SUBMITTED` after\n // finalization).\n const retry = (): boolean => {\n const live = this.#quoteStatusEntryStore.get(\n QuoteStatusEntryStore.hash(entry),\n );\n return Boolean(\n live &&\n live.status.state === sentStatus &&\n live.acknowledgedState !== sentStatus,\n );\n };\n\n this.#quoteStatusApiService\n .updateQuoteStatusWithRetry(\n {\n quoteId: entry.quoteId,\n srcTxHash: entry.srcTxHash,\n newStatus: sentStatusBackend,\n },\n {\n maxRetries: 5,\n delayMsBetweenRetries: 3000,\n retry,\n },\n )\n .then((outcome) => {\n switch (outcome.type) {\n case QuoteStatusFetchWithRetryOutcomeType.Accepted: {\n const current = this.#quoteStatusEntryStore.get(\n QuoteStatusEntryStore.hash(entry),\n );\n // The entry can only be absent if the store was cleared (e.g. via\n // `destroy`) while the request was in flight; nothing left to do.\n if (!current) {\n return undefined;\n }\n if (current.status.state !== sentStatus) {\n // The status advanced mid-flight; report the newer status.\n this.#processEntry(current);\n return undefined;\n }\n if (\n sentStatus === QuoteStatusState.FinalizedSuccess ||\n sentStatus === QuoteStatusState.FinalizedFailed\n ) {\n // A finalized status was accepted; advance to the terminal\n // `Completed` state and keep the entry so any later duplicate\n // `reportSubmitted` for this quote is rejected instead of looping.\n this.#markCompleted(current);\n // Call getStatus to complete the flow on the backend.\n // We discard any value for now, this is used purely\n // to notify backend that the flow is complete.\n this.getStatus(entry.quoteId, { maxRetries: 1 });\n return undefined;\n }\n // A non-final status (e.g. `Submitted`) was accepted. The quote is\n // not done yet: it still needs to be finalized via a later\n // `reportFinalised`, which looks the entry up by `txMetaId`. Keep\n // the entry tracked and record the acknowledgement so the retry\n // loop stops re-sending the already-accepted status.\n current.acknowledgedState = sentStatus;\n this.#quoteStatusEntryStore.update(current);\n this.#stopRetryTimerIfIdle();\n return undefined;\n }\n case QuoteStatusFetchWithRetryOutcomeType.NonRetryable:\n this.#handleNonRetryableUpdateStatusError(entry, outcome);\n return undefined;\n case QuoteStatusFetchWithRetryOutcomeType.Interrupted:\n this.#processEntry(entry);\n return undefined;\n case QuoteStatusFetchWithRetryOutcomeType.RetryableExhausted:\n entry.lastAttemptAt = Date.now();\n this.#quoteStatusEntryStore.update(entry);\n return undefined;\n default:\n return undefined;\n }\n })\n .catch(() => {\n entry.lastAttemptAt = Date.now();\n this.#quoteStatusEntryStore.update(entry);\n });\n }\n\n /**\n * Advances an entry to the terminal `Completed` state and stops the retry\n * timer if no work remains. The entry is kept in the store so later duplicate\n * reports for the same quote are recognized and rejected.\n *\n * @param entry - The runtime entry to complete.\n * @param finalizedState - Optional finalized state the backend reports as\n * current. When provided and reachable, the entry is first advanced through it\n * so the FSM's forward-only path (`Submitted -> FinalizedX -> Completed`) is\n * respected before reaching `Completed`.\n */\n #markCompleted(\n entry: QuoteStatusRuntimeEntry,\n finalizedState?: QuoteStatusState,\n ): void {\n if (finalizedState && entry.status.canTransitionTo(finalizedState)) {\n entry.status.transitionTo(finalizedState);\n }\n\n if (entry.status.canTransitionTo(QuoteStatusState.Completed)) {\n entry.status.transitionTo(QuoteStatusState.Completed);\n }\n\n this.#stopRetryTimerIfIdle();\n }\n\n /**\n * Advances an entry to the terminal `Expired` state (abandoning it) and stops\n * the retry timer if no work remains. The entry is kept in the store so later\n * interactions with the same quote are rejected.\n *\n * @param entry - The runtime entry to abandon.\n */\n #markExpired(entry: QuoteStatusRuntimeEntry): void {\n if (entry.status.canTransitionTo(QuoteStatusState.Expired)) {\n entry.status.transitionTo(QuoteStatusState.Expired);\n }\n\n this.#stopRetryTimerIfIdle();\n }\n\n /**\n * Reconciles local state in response to a non-retryable backend error.\n *\n * When the backend reports a terminal status, the entry is either advanced to\n * match and reprocessed (if it is behind) or converged to `Completed` (if it\n * is already finalized), surfacing an error only for a genuine status\n * discrepancy. Other non-retryable errors that cannot be reconciled mark the\n * entry `Expired` (abandoned). Entries are always kept in the store so future\n * interactions with the quote are rejected rather than looping.\n *\n * @param entry - The runtime entry whose update failed.\n * @param outcome - The non-retryable outcome returned by the API service,\n * including the backend response used for reconciliation.\n */\n #handleNonRetryableUpdateStatusError(\n entry: QuoteStatusRuntimeEntry,\n outcome: QuoteStatusUpdateWithRetryOutcome,\n ): void {\n const { response } = outcome;\n\n const backendFinalizedToState: Partial<\n Record<QuoteStatusBackendStatus, QuoteStatusState>\n > = {\n [QuoteStatusBackendStatus.FinalizedSuccess]:\n QuoteStatusState.FinalizedSuccess,\n [QuoteStatusBackendStatus.FinalizedFailed]:\n QuoteStatusState.FinalizedFailed,\n };\n\n // The transition we requested is invalid because the backend is already in a\n // terminal state (e.g. we re-sent `SUBMITTED` after finalization). There is\n // nothing left to report, so advance the entry to `Completed` and keep it.\n if (\n response?.type ===\n QuoteStatusUpdateBackendErrorType.InvalidStatusTransaction &&\n (response.currentStatus === QuoteStatusBackendStatus.FinalizedSuccess ||\n response.currentStatus === QuoteStatusBackendStatus.FinalizedFailed)\n ) {\n this.#markCompleted(\n entry,\n backendFinalizedToState[response.currentStatus],\n );\n return;\n }\n\n // For mismatch errors the backend reports the status it currently has, which\n // lets us reconcile our local state. The discriminant check also narrows\n // `response` to the variant carrying `currentStatus`.\n if (\n response?.type ===\n QuoteStatusUpdateBackendErrorType.InvalidStatusTransaction ||\n response?.type ===\n QuoteStatusUpdateBackendErrorType.QuoteStatusOnChainMismatch\n ) {\n const nextState = backendFinalizedToState[response.currentStatus];\n\n if (nextState) {\n // We are behind the backend's terminal status; advance our local state\n // and reprocess so the correct finalization status is reported.\n if (entry.status.canTransitionTo(nextState)) {\n entry.status.transitionTo(nextState);\n this.#processEntry(entry);\n return;\n }\n\n // The backend reports a finalized status but we cannot transition there.\n // If we already hold that same finalized state, this can be a stale\n // `SUBMITTED` response racing with an in-flight finalized update. Do not\n // complete in this case: keep the entry pending so the finalized update\n // can continue retrying on transient backend errors such as\n // `CONCURRENT_UPDATE`.\n if (entry.status.state === nextState) {\n return;\n }\n\n // Any other non-transitionable finalized mismatch indicates we've reached\n // (or passed) a terminal state but disagree with the backend's final\n // status. Converge to `Completed` (kept) rather than expiring.\n if (\n entry.status.state !== QuoteStatusState.Completed &&\n entry.status.state !== QuoteStatusState.Expired\n ) {\n // Genuine discrepancy between our finalized status and the backend's\n // (e.g. we observed the opposite outcome); surface it for visibility,\n // but still complete the entry instead of looping or abandoning it.\n this.#onError?.(\n new QuoteStatusUpdateError(\n `reporting finalization status but entry cannot transition from \"${entry.status.state}\" to \"${nextState}\"`,\n { quoteId: entry.quoteId },\n ),\n );\n }\n this.#markCompleted(entry);\n return;\n }\n }\n\n // Any non-retryable error we could not reconcile means we cannot make\n // progress on this entry, so abandon it rather than leaving it stuck.\n this.#markExpired(entry);\n this.#onError?.(\n new QuoteStatusUpdateError(\n `abandoning entry due to non-retryable error`,\n {\n quoteId: entry.quoteId,\n errorType: response?.type,\n },\n ),\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"quotes-status-manager.mjs","sourceRoot":"","sources":["../../src/quote-status-manager/quotes-status-manager.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,iBAAiB,EAAE,yCAAyC;AAErE,OAAO,EAAE,cAAc,EAAmC,qBAAiB;AAC3E,OAAO,EACL,sBAAsB,EACtB,yBAAyB,EACzB,cAAc,EACf,iCAA6B;AAC9B,OAAO,EACL,gBAAgB,EAChB,+BAA+B,EAC/B,iCAAiC,EACjC,wBAAwB,EACxB,oCAAoC,EACrC,wBAAoB;AACrB,OAAO,EAAE,sBAAsB,EAAE,qBAAiB;AAClD,OAAO,EAAE,qBAAqB,EAAE,uCAAmC;AACnE,OAAO,EAAE,qBAAqB,EAAE,uCAAmC;AACnE,OAAO,EAAE,8BAA8B,EAAE,kDAA8C;AACvF,OAAO,EAAE,mBAAmB,EAAE,qCAAiC;AAC/D,OAAO,EAAE,iCAAiC,EAAE,qDAAiD;AAG7F;;;;;;;;;GASG;AACH,MAAM,OAAO,kBAAkB;IAqB7B;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,YAAY,EACV,SAAS,EACT,QAAQ,EACR,aAAa,EACb,aAAa,EACb,UAAU,EACV,OAAO,EACP,SAAS,EACT,gBAAgB,EAChB,UAAU,EACV,gBAAgB,EAChB,WAAW,GAeZ;;QApEQ,gDAA4C;QAE5C,4DAA8C;QAE9C,4DAA8C;QAE9C,gDAAwC;QAExC,8CAAgE;QAEhE,uDAA0B;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,CAAC,OAAO,EAC/C,CAAC;gBACD,qEAAqE;gBACrE,sEAAsE;gBACtE,oEAAoE;gBACpE,uBAAA,IAAI,mCAAS,EAAE,KAAf,IAAI,EACF,IAAI,sBAAsB,CACxB,mEAAmE,KAAK,CAAC,MAAM,CAAC,KAAK,SAAS,SAAS,GAAG,EAC1G,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAC3B,CACF,CAAC;YACJ,CAAC;YACD,uBAAA,IAAI,wEAAe,MAAnB,IAAI,EAAgB,KAAK,CAAC,CAAC;YAC3B,OAAO;QACT,CAAC;IACH,CAAC;IAED,sEAAsE;IACtE,sEAAsE;IACtE,uBAAA,IAAI,sEAAa,MAAjB,IAAI,EAAc,KAAK,CAAC,CAAC;IACzB,uBAAA,IAAI,mCAAS,EAAE,KAAf,IAAI,EACF,IAAI,sBAAsB,CACxB,6CAA6C,EAC7C;QACE,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,SAAS,EAAE,QAAQ,EAAE,IAAI;KAC1B,CACF,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { TransactionStatus } from '@metamask/transaction-controller';\n\nimport { BridgeClientId, BridgeStatusControllerMessenger } from '../types';\nimport {\n getTransactionMetaById,\n hasNestedSwapTransactions,\n isCrossChainTx,\n} from '../utils/transaction';\nimport {\n QuoteStatusState,\n QuoteStatusStateToBackendStatus,\n QuoteStatusUpdateBackendErrorType,\n QuoteStatusBackendStatus,\n QuoteStatusFetchWithRetryOutcomeType,\n} from './constants';\nimport { QuoteStatusUpdateError } from './errors';\nimport { QuoteStatusApiService } from './quote-status-api-service';\nimport { QuoteStatusEntryStore } from './quote-status-entry-store';\nimport { QuoteStatusGetWithRetryOutcome } from './quote-status-get-with-retry-outcome';\nimport { QuoteStatusStateFsm } from './quote-status-state-fsm';\nimport { QuoteStatusUpdateWithRetryOutcome } from './quote-status-update-with-retry-outcome';\nimport { QuoteStatusPersistEntry, QuoteStatusRuntimeEntry } from './types';\n\n/**\n * Tracks bridge/swap quotes through their lifecycle and keeps the backend in\n * sync with the latest known status of each quote.\n *\n * Quotes are reported via {@link reportSubmitted} and {@link reportFinalised},\n * stored as runtime entries, and pushed to the backend. Updates that fail in a\n * retryable way are retried on a periodic timer until each entry reaches a\n * terminal state, at which point it is evicted and the timer stops once the\n * store is empty.\n */\nexport class QuoteStatusManager {\n readonly #messenger: BridgeStatusControllerMessenger;\n\n readonly #quoteStatusApiService: QuoteStatusApiService;\n\n readonly #quoteStatusEntryStore: QuoteStatusEntryStore;\n\n readonly #isEnabled: (() => boolean) | undefined;\n\n readonly #onError: ((error: QuoteStatusUpdateError) => void) | undefined;\n\n readonly #updateIntervalMs: number;\n\n /**\n * Handle for the periodic retry timer. While running, every\n * {@link QUOTE_STATUS_UPDATE_RETRY_INTERVAL_MS} all entries that have not yet\n * reached a terminal state (Completed/Expired) are re-processed. It is started\n * lazily when there is work to do and stopped once the store is empty.\n */\n #retryIntervalId: ReturnType<typeof setInterval> | null = null;\n\n /**\n * Creates a new manager and immediately processes any persisted entries.\n *\n * @param options - Constructor options.\n * @param options.messenger - Messenger used to communicate with the backend\n * API service.\n * @param options.clientId - Identifier of the client making the requests.\n * @param options.clientProduct - Name of the client product making the\n * requests.\n * @param options.clientVersion - Optional version of the client product.\n * @param options.apiBaseUrl - Base URL of the quote status backend API.\n * @param options.onPersistUpdates - Callback invoked to persist entry updates.\n * @param options.onError - Optional callback invoked when a non-recoverable\n * error occurs.\n * @param options.isEnabled - Optional predicate gating whether the manager\n * performs any work.\n * @param options.entryTtlMs - Time-to-live, in milliseconds, after which a\n * tracked entry is evicted.\n * @param options.updateIntervalMs - How often the manager re-processes entries that\n * have not yet reached a terminal state\n * @param options.initialData - Persisted entries to rehydrate on startup.\n */\n constructor({\n messenger,\n clientId,\n clientProduct,\n clientVersion,\n apiBaseUrl,\n onError,\n isEnabled,\n onPersistUpdates,\n entryTtlMs,\n updateIntervalMs,\n initialData,\n }: {\n messenger: BridgeStatusControllerMessenger;\n clientId: BridgeClientId;\n clientProduct: string;\n clientVersion?: string;\n apiBaseUrl: string;\n onPersistUpdates: (\n updates: Record<string, QuoteStatusPersistEntry>,\n ) => void;\n onError?: (error: QuoteStatusUpdateError) => void;\n isEnabled?: () => boolean;\n entryTtlMs: number;\n updateIntervalMs: number;\n initialData: Record<string, QuoteStatusPersistEntry>;\n }) {\n this.#isEnabled = isEnabled;\n this.#onError = onError;\n this.#updateIntervalMs = updateIntervalMs;\n this.#messenger = messenger;\n\n this.#quoteStatusApiService = new QuoteStatusApiService({\n messenger,\n clientId,\n clientProduct,\n clientVersion,\n apiBaseUrl,\n onError,\n });\n\n this.#quoteStatusEntryStore = new QuoteStatusEntryStore({\n onPersistUpdates,\n entryTtlMs,\n initial: initialData,\n });\n }\n\n /**\n * Whether quote-status tracking and backend sync are currently active.\n *\n * Reflects the latest value returned by the optional `isEnabled` predicate\n * supplied at construction time. When no predicate was provided, this is\n * always `false` and all public methods that gate on enablement no-op.\n *\n * @returns `true` when the `isEnabled` predicate returns a truthy value.\n */\n get enabled(): boolean {\n return Boolean(this.#isEnabled?.());\n }\n\n /**\n * Reports that a previously submitted quote has finalized on-chain.\n *\n * Looks up the tracked entry by its transaction metadata id, transitions it to\n * the appropriate terminal state, and processes the update. No-ops when the\n * manager is disabled, and surfaces an error when the entry is missing or\n * cannot transition to the finalized state.\n *\n * @param txMetaId - Transaction metadata id of the finalized quote.\n * @param success - Whether the transaction finalized successfully.\n */\n reportFinalised(txMetaId: string, success: boolean): void {\n if (!this.#isEnabled?.()) {\n return;\n }\n\n const entry = this.#quoteStatusEntryStore.getByTxMetaId(txMetaId);\n\n if (!entry) {\n this.#onError?.(\n new QuoteStatusUpdateError(\n 'reporting finalization status but entry was not found',\n { quoteId: '' },\n ),\n );\n return;\n }\n\n const nextState = success\n ? QuoteStatusState.FinalizedSuccess\n : QuoteStatusState.FinalizedFailed;\n\n if (!entry.status.canTransitionTo(nextState)) {\n // This is expected, there are race conditions where\n // reportFinalized can be called twice. If the second\n // call fails due to the first completed sucesfully\n // backend will report that we cannot transition outside\n // a final state, which is correct and we can safely abort\n // the flow.\n return;\n }\n\n entry.status.transitionTo(nextState);\n this.#ensureRetryTimerRunning();\n this.#processEntry(entry);\n }\n\n /**\n * Reports that a quote has been submitted on-chain and begins tracking it.\n *\n * Creates a new entry in the `Submitted` state, starts the retry timer, and\n * processes the initial status update. No-ops when the manager is disabled,\n * and surfaces an error if the entry cannot be retrieved after being stored.\n *\n * @param quoteId - Identifier of the submitted quote.\n * @param srcTxHash - Hash of the source-chain transaction for the quote.\n * @param txMetaId - Optional transaction metadata id used to correlate\n * finalization reports.\n */\n reportSubmitted(quoteId: string, srcTxHash: string, txMetaId?: string): void {\n if (!this.#isEnabled?.()) {\n return;\n }\n\n // Once a quote has advanced past `Submitted` (finalized or terminal), it is\n // done: reporting `SUBMITTED` again would be rejected by the backend as an\n // invalid transition. Retained terminal entries let us recognize and drop\n // these late/duplicate submissions instead of looping on a 400.\n const isQuoteAlreadyTracked = this.#quoteStatusEntryStore\n .getByQuoteId(quoteId)\n .some((entry) => entry.status.state !== QuoteStatusState.Submitted);\n if (isQuoteAlreadyTracked) {\n return;\n }\n\n const entryKey = QuoteStatusEntryStore.hash({\n quoteId,\n srcTxHash,\n });\n\n const entry = this.#quoteStatusEntryStore.put(entryKey, {\n quoteId,\n srcTxHash,\n txMetaId,\n status: new QuoteStatusStateFsm(QuoteStatusState.Submitted),\n });\n\n this.#ensureRetryTimerRunning();\n this.#processEntry(entry);\n }\n\n /**\n * Tears down the manager by stopping the retry timer and clearing all tracked\n * entries.\n */\n destroy(): void {\n this.#stopRetryTimer();\n this.#quoteStatusEntryStore.clear();\n }\n\n /**\n * Reconciles quote-status entries whose finalization was missed while the\n * client was closed. Called once during initialization.\n *\n * Swap/bridge source transactions report their final status through the\n * `TransactionController:transactionStatusUpdated` subscription\n * ({@link #onTransactionConfirmed}/{@link #onTransactionFailed}). When a source\n * transaction reaches a terminal state while the client is not running, that\n * event is never re-emitted on the next startup, so the persisted entry would\n * remain `Submitted` until it expires via TTL. This replays the missed terminal\n * event for both swaps and bridges: a confirmed source transaction is reported\n * as a finalized success and a failed/dropped one as a finalized failure.\n *\n * `rejected` is ignored because the transaction was never broadcast.\n */\n init(): void {\n this.#processInitial();\n\n for (const entry of this.#quoteStatusEntryStore.values()) {\n // Only entries still awaiting finalization need catching up. Entries\n // already in a finalized state are re-sent by `processInitial()`.\n if (\n entry.status.state !== QuoteStatusState.Submitted ||\n !entry.txMetaId\n ) {\n continue;\n }\n\n const txMeta = getTransactionMetaById(this.#messenger, entry.txMetaId);\n if (!txMeta) {\n continue;\n }\n\n // Reconcile swaps and bridges alike: a terminal source transaction\n // finalizes the quote status. `hasNestedSwapTransactions` also covers\n // batch/7702 swaps whose type may still read as `batch` rather than `swap`.\n const isCrossChainTrade =\n (txMeta.type !== undefined && isCrossChainTx(txMeta.type)) ||\n hasNestedSwapTransactions(txMeta);\n if (!isCrossChainTrade) {\n continue;\n }\n\n if (txMeta.status === TransactionStatus.confirmed) {\n this.reportFinalised(entry.txMetaId, true);\n } else if (\n txMeta.status === TransactionStatus.failed ||\n txMeta.status === TransactionStatus.dropped\n ) {\n this.reportFinalised(entry.txMetaId, false);\n }\n }\n }\n\n /**\n * Fetches the current quote status from the backend with automatic retries.\n *\n * Unlike {@link reportSubmitted} and {@link reportFinalised}, this is a\n * read-only query and does not mutate tracked entries. Returns `null` when\n * the manager is disabled ({@link enabled} is `false`).\n *\n * @param quoteId - Identifier of the quote whose status should be fetched.\n * @param options - Retry configuration.\n * @param options.maxRetries - Maximum number of retries after the initial attempt.\n * @param options.delayMsBetweenRetries - Delay in milliseconds between attempts.\n * @returns The quote status outcome, or `undefined` when the manager is disabled.\n */\n async getStatus(\n quoteId: string,\n options: {\n maxRetries?: number;\n delayMsBetweenRetries?: number;\n } = {\n maxRetries: 0,\n delayMsBetweenRetries: 1000,\n },\n ): Promise<QuoteStatusGetWithRetryOutcome | undefined> {\n if (!this.#isEnabled?.()) {\n return undefined;\n }\n\n const response = this.#quoteStatusApiService\n .getQuoteStatusWithRetry(\n {\n quoteId,\n },\n {\n maxRetries: options.maxRetries ?? 0,\n delayMsBetweenRetries: options.delayMsBetweenRetries ?? 1000,\n },\n )\n // Errors already reported by #onError handlers of `getQuoteStatusWithRetry()`\n .catch(() => undefined);\n\n return response;\n }\n\n /**\n * Processes every entry rehydrated from persisted data on startup and starts\n * the retry timer if any entries still require further updates.\n */\n #processInitial(): void {\n for (const entry of this.#quoteStatusEntryStore.values()) {\n this.#processEntry(entry);\n }\n\n // Terminal entries (Completed/Expired) are retained, so the store is never\n // empty. Only start the retry timer when there is an entry whose status\n // still needs to be reported; otherwise it would tick forever doing nothing.\n if (this.#hasPendingUpdates()) {\n this.#ensureRetryTimerRunning();\n }\n }\n\n /**\n * Starts the periodic retry timer if it is not already running.\n *\n * The timer re-processes every non-terminal entry on each tick. It is\n * idempotent so callers can invoke it freely whenever new work is enqueued.\n */\n #ensureRetryTimerRunning(): void {\n if (this.#retryIntervalId !== null) {\n return;\n }\n\n this.#retryIntervalId = setInterval(\n () => this.#processRetries(),\n this.#updateIntervalMs,\n );\n }\n\n /**\n * Stops the periodic retry timer if it is running.\n */\n #stopRetryTimer(): void {\n if (this.#retryIntervalId !== null) {\n clearInterval(this.#retryIntervalId);\n this.#retryIntervalId = null;\n }\n }\n\n /**\n * Retry tick: re-processes every entry. Reading `values()` first transitions\n * TTL-expired entries to `Expired` (keeping them), and `#processEntry` no-ops\n * for terminal/acknowledged entries. When no entry has a status left to report\n * the timer stops until new work is enqueued.\n */\n #processRetries(): void {\n if (!this.#isEnabled?.()) {\n return;\n }\n\n // Snapshot first: `#processEntry` can mutate the store (e.g. transitioning an\n // accepted entry to a terminal state), so iterating a live iterator would be\n // unsafe.\n const entries = [...this.#quoteStatusEntryStore.values()];\n\n if (!this.#hasPendingUpdates()) {\n this.#stopRetryTimer();\n return;\n }\n\n for (const entry of entries) {\n this.#processEntry(entry);\n }\n }\n\n /**\n * Returns whether any tracked entry still has a status that needs to be\n * reported to the backend.\n *\n * Terminal entries (`Completed`/`Expired`) and entries whose current status\n * has already been acknowledged are excluded, so this is the signal used to\n * decide whether the retry timer has any work left to do.\n *\n * @returns `true` when at least one entry has an unreported status.\n */\n #hasPendingUpdates(): boolean {\n for (const entry of this.#quoteStatusEntryStore.values()) {\n const { state } = entry.status;\n const isTerminal =\n state === QuoteStatusState.Completed ||\n state === QuoteStatusState.Expired;\n if (!isTerminal && entry.acknowledgedState !== state) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Stops the retry timer when there are no entries left whose status needs\n * reporting. Since terminal entries are retained, the store is never empty, so\n * the timer's idle condition is \"no pending updates\" rather than \"no entries\".\n */\n #stopRetryTimerIfIdle(): void {\n if (!this.#hasPendingUpdates()) {\n this.#stopRetryTimer();\n }\n }\n\n /**\n * Pushes a single entry's current status to the backend and reconciles the\n * local state with the request outcome.\n *\n * Terminal entries are kept but no longer reported. Accepted finalized updates\n * advance the entry to `Completed` (kept so duplicate reports are rejected);\n * accepted non-final updates (e.g. `Submitted`) are kept tracked so a later\n * {@link reportFinalised} can find them, while being flagged so the retry loop\n * stops re-sending the acknowledged status. Updates whose status advanced\n * mid-flight are reprocessed, retryable failures are left for the next retry\n * tick, and non-retryable failures are delegated to\n * {@link #handleNonRetryableUpdateStatusError}.\n *\n * @param entry - The runtime entry to process.\n */\n #processEntry(entry: QuoteStatusRuntimeEntry): void {\n // The backend already accepted the entry's current status, so there is\n // nothing new to report. The entry is kept tracked (e.g. a `Submitted`\n // quote awaiting finalization) until its status advances past the\n // acknowledged one, at which point it is reprocessed.\n if (entry.acknowledgedState === entry.status.state) {\n return;\n }\n\n const sentStatus = entry.status.state;\n const sentStatusBackend = QuoteStatusStateToBackendStatus[sentStatus];\n\n // Terminal states (`Completed`/`Expired`) have no backend status to report.\n // The entry is retained so future interactions with the quote are rejected.\n if (sentStatusBackend === null) {\n this.#stopRetryTimerIfIdle();\n return;\n }\n\n // Re-checked before each retry attempt so an in-flight retry stops early when\n // the entry has since advanced, been acknowledged, become terminal, or\n // expired (a later `reportFinalised` re-triggers processing). This avoids\n // firing a request the backend would reject (e.g. `SUBMITTED` after\n // finalization).\n const retry = (): boolean => {\n const live = this.#quoteStatusEntryStore.get(\n QuoteStatusEntryStore.hash(entry),\n );\n return Boolean(\n live &&\n live.status.state === sentStatus &&\n live.acknowledgedState !== sentStatus,\n );\n };\n\n this.#quoteStatusApiService\n .updateQuoteStatusWithRetry(\n {\n quoteId: entry.quoteId,\n srcTxHash: entry.srcTxHash,\n newStatus: sentStatusBackend,\n },\n {\n maxRetries: 5,\n delayMsBetweenRetries: 3000,\n retry,\n },\n )\n .then((outcome) => {\n switch (outcome.type) {\n case QuoteStatusFetchWithRetryOutcomeType.Accepted: {\n const current = this.#quoteStatusEntryStore.get(\n QuoteStatusEntryStore.hash(entry),\n );\n // The entry can only be absent if the store was cleared (e.g. via\n // `destroy`) while the request was in flight; nothing left to do.\n if (!current) {\n return undefined;\n }\n if (current.status.state !== sentStatus) {\n // The status advanced mid-flight; report the newer status.\n this.#processEntry(current);\n return undefined;\n }\n if (\n sentStatus === QuoteStatusState.FinalizedSuccess ||\n sentStatus === QuoteStatusState.FinalizedFailed\n ) {\n // A finalized status was accepted; advance to the terminal\n // `Completed` state and keep the entry so any later duplicate\n // `reportSubmitted` for this quote is rejected instead of looping.\n this.#markCompleted(current);\n\n return undefined;\n }\n // A non-final status (e.g. `Submitted`) was accepted. The quote is\n // not done yet: it still needs to be finalized via a later\n // `reportFinalised`, which looks the entry up by `txMetaId`. Keep\n // the entry tracked and record the acknowledgement so the retry\n // loop stops re-sending the already-accepted status.\n current.acknowledgedState = sentStatus;\n this.#quoteStatusEntryStore.update(current);\n this.#stopRetryTimerIfIdle();\n return undefined;\n }\n case QuoteStatusFetchWithRetryOutcomeType.NonRetryable:\n this.#handleNonRetryableUpdateStatusError(entry, outcome);\n return undefined;\n case QuoteStatusFetchWithRetryOutcomeType.Interrupted:\n this.#processEntry(entry);\n return undefined;\n case QuoteStatusFetchWithRetryOutcomeType.RetryableExhausted:\n entry.lastAttemptAt = Date.now();\n this.#quoteStatusEntryStore.update(entry);\n return undefined;\n default:\n return undefined;\n }\n })\n .catch(() => {\n entry.lastAttemptAt = Date.now();\n this.#quoteStatusEntryStore.update(entry);\n });\n }\n\n /**\n * Advances an entry to the terminal `Completed` state and stops the retry\n * timer if no work remains. The entry is kept in the store so later duplicate\n * reports for the same quote are recognized and rejected.\n *\n * @param entry - The runtime entry to complete.\n * @param finalizedState - Optional finalized state the backend reports as\n * current. When provided and reachable, the entry is first advanced through it\n * so the FSM's forward-only path (`Submitted -> FinalizedX -> Completed`) is\n * respected before reaching `Completed`.\n */\n #markCompleted(\n entry: QuoteStatusRuntimeEntry,\n finalizedState?: QuoteStatusState,\n ): void {\n if (finalizedState && entry.status.canTransitionTo(finalizedState)) {\n entry.status.transitionTo(finalizedState);\n }\n\n if (entry.status.canTransitionTo(QuoteStatusState.Completed)) {\n entry.status.transitionTo(QuoteStatusState.Completed);\n }\n\n this.#stopRetryTimerIfIdle();\n }\n\n /**\n * Advances an entry to the terminal `Expired` state (abandoning it) and stops\n * the retry timer if no work remains. The entry is kept in the store so later\n * interactions with the same quote are rejected.\n *\n * @param entry - The runtime entry to abandon.\n */\n #markExpired(entry: QuoteStatusRuntimeEntry): void {\n if (entry.status.canTransitionTo(QuoteStatusState.Expired)) {\n entry.status.transitionTo(QuoteStatusState.Expired);\n }\n\n this.#stopRetryTimerIfIdle();\n }\n\n /**\n * Reconciles local state in response to a non-retryable backend error.\n *\n * When the backend reports a terminal status, the entry is either advanced to\n * match and reprocessed (if it is behind) or converged to `Completed` (if it\n * is already finalized), surfacing an error only for a genuine status\n * discrepancy. Other non-retryable errors that cannot be reconciled mark the\n * entry `Expired` (abandoned). Entries are always kept in the store so future\n * interactions with the quote are rejected rather than looping.\n *\n * @param entry - The runtime entry whose update failed.\n * @param outcome - The non-retryable outcome returned by the API service,\n * including the backend response used for reconciliation.\n */\n #handleNonRetryableUpdateStatusError(\n entry: QuoteStatusRuntimeEntry,\n outcome: QuoteStatusUpdateWithRetryOutcome,\n ): void {\n const { response } = outcome;\n\n const backendFinalizedToState: Partial<\n Record<QuoteStatusBackendStatus, QuoteStatusState>\n > = {\n [QuoteStatusBackendStatus.FinalizedSuccess]:\n QuoteStatusState.FinalizedSuccess,\n [QuoteStatusBackendStatus.FinalizedFailed]:\n QuoteStatusState.FinalizedFailed,\n };\n\n // The transition we requested is invalid because the backend is already in a\n // terminal state (e.g. we re-sent `SUBMITTED` after finalization). There is\n // nothing left to report, so advance the entry to `Completed` and keep it.\n if (\n response?.type ===\n QuoteStatusUpdateBackendErrorType.InvalidStatusTransaction &&\n (response.currentStatus === QuoteStatusBackendStatus.FinalizedSuccess ||\n response.currentStatus === QuoteStatusBackendStatus.FinalizedFailed)\n ) {\n this.#markCompleted(\n entry,\n backendFinalizedToState[response.currentStatus],\n );\n return;\n }\n\n // For mismatch errors the backend reports the status it currently has, which\n // lets us reconcile our local state. The discriminant check also narrows\n // `response` to the variant carrying `currentStatus`.\n if (\n response?.type ===\n QuoteStatusUpdateBackendErrorType.InvalidStatusTransaction ||\n response?.type ===\n QuoteStatusUpdateBackendErrorType.QuoteStatusOnChainMismatch\n ) {\n const nextState = backendFinalizedToState[response.currentStatus];\n\n if (nextState) {\n // We are behind the backend's terminal status; advance our local state\n // and reprocess so the correct finalization status is reported.\n if (entry.status.canTransitionTo(nextState)) {\n entry.status.transitionTo(nextState);\n this.#processEntry(entry);\n return;\n }\n\n // The backend reports a finalized status but we cannot transition there.\n // If we already hold that same finalized state, this can be a stale\n // `SUBMITTED` response racing with an in-flight finalized update. Do not\n // complete in this case: keep the entry pending so the finalized update\n // can continue retrying on transient backend errors such as\n // `CONCURRENT_UPDATE`.\n if (entry.status.state === nextState) {\n return;\n }\n\n // Any other non-transitionable finalized mismatch indicates we've reached\n // (or passed) a terminal state but disagree with the backend's final\n // status. Converge to `Completed` (kept) rather than expiring.\n if (\n entry.status.state !== QuoteStatusState.Completed &&\n entry.status.state !== QuoteStatusState.Expired\n ) {\n // Genuine discrepancy between our finalized status and the backend's\n // (e.g. we observed the opposite outcome); surface it for visibility,\n // but still complete the entry instead of looping or abandoning it.\n this.#onError?.(\n new QuoteStatusUpdateError(\n `reporting finalization status but entry cannot transition from \"${entry.status.state}\" to \"${nextState}\"`,\n { quoteId: entry.quoteId },\n ),\n );\n }\n this.#markCompleted(entry);\n return;\n }\n }\n\n // Any non-retryable error we could not reconcile means we cannot make\n // progress on this entry, so abandon it rather than leaving it stuck.\n this.#markExpired(entry);\n this.#onError?.(\n new QuoteStatusUpdateError(\n `abandoning entry due to non-retryable error`,\n {\n quoteId: entry.quoteId,\n errorType: response?.type,\n },\n ),\n );\n }\n}\n"]}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getStatusRequestParams = exports.shouldWaitForFinalBridgeStatus = exports.shouldSkipFetchDueToFetchFailures = exports.getStatusRequestWithSrcTxHash = exports.fetchBridgeTxStatus = exports.getStatusRequestDto = exports.getBridgeStatusUrl = void 0;
|
|
3
|
+
exports.getStatusRequestParams = exports.shouldWaitForFinalBridgeStatus = exports.shouldSkipFetchDueToFetchFailures = exports.getStatusRequestWithSrcTxHash = exports.fetchBridgeTxStatus = exports.fetchBridgeQuoteStatus = exports.getStatusRequestDto = exports.getBridgeStatusUrl = void 0;
|
|
4
4
|
const bridge_controller_1 = require("@metamask/bridge-controller");
|
|
5
5
|
const superstruct_1 = require("@metamask/superstruct");
|
|
6
6
|
const constants_1 = require("../constants.cjs");
|
|
7
|
+
const quotes_status_manager_1 = require("../quote-status-manager/quotes-status-manager.cjs");
|
|
7
8
|
const history_1 = require("./history.cjs");
|
|
8
9
|
const network_1 = require("./network.cjs");
|
|
9
10
|
const validators_1 = require("./validators.cjs");
|
|
@@ -22,6 +23,18 @@ const getStatusRequestDto = (statusRequest) => {
|
|
|
22
23
|
};
|
|
23
24
|
};
|
|
24
25
|
exports.getStatusRequestDto = getStatusRequestDto;
|
|
26
|
+
const fetchBridgeQuoteStatus = async (quoteStatusManager, quoteId) => {
|
|
27
|
+
const response = await quoteStatusManager.getStatus(quoteId);
|
|
28
|
+
const status = response?.response?.submittedTx;
|
|
29
|
+
if (!status) {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
return {
|
|
33
|
+
status,
|
|
34
|
+
validationFailures: response.error?.details?.validationFailures ?? [],
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
exports.fetchBridgeQuoteStatus = fetchBridgeQuoteStatus;
|
|
25
38
|
const fetchBridgeTxStatus = async (statusRequest, clientId, jwt, fetchFn, bridgeApiBaseUrl) => {
|
|
26
39
|
const statusRequestDto = (0, exports.getStatusRequestDto)(statusRequest);
|
|
27
40
|
const params = new URLSearchParams(statusRequestDto);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge-status.cjs","sourceRoot":"","sources":["../../src/utils/bridge-status.ts"],"names":[],"mappings":";;;AAAA,mEAIqC;AAGrC,uDAAoD;AAEpD,gDAAmD;AAUnD,2CAAgD;AAChD,2CAAsD;AACtD,iDAA4D;AAErD,MAAM,kBAAkB,GAAG,CAAC,gBAAwB,EAAU,EAAE,CACrE,GAAG,gBAAgB,cAAc,CAAC;AADvB,QAAA,kBAAkB,sBACK;AAE7B,MAAM,mBAAmB,GAAG,CACjC,aAAyC,EACvB,EAAE;IACpB,MAAM,EAAE,KAAK,EAAE,GAAG,oBAAoB,EAAE,GAAG,aAAa,CAAC;IAEzD,MAAM,6BAA6B,GAAG,MAAM,CAAC,WAAW,CACtD,MAAM,CAAC,OAAO,CAAC,oBAAoB,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC;QACzD,GAAG;QACH,KAAK,CAAC,QAAQ,EAAE;KACjB,CAAC,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,EAAE,aAAa,CAAC,KAAK,CAAC,QAAQ;QACtC,MAAM,EAAE,aAAa,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;QACtC,UAAU,EAAE,aAAa,CAAC,KAAK,CAAC,UAAU;QAC1C,WAAW,EAAE,aAAa,CAAC,KAAK,CAAC,WAAW;QAC5C,KAAK,EAAE,aAAa,CAAC,KAAK;QAC1B,MAAM,EAAE,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,MAAM,CAAC;KAC5C,CAAC;AACJ,CAAC,CAAC;AAXW,QAAA,sBAAsB,0BAWjC","sourcesContent":["import {\n getClientHeaders,\n isNonEvmChainId,\n StatusTypes,\n} from '@metamask/bridge-controller';\nimport type { Quote, QuoteResponse } from '@metamask/bridge-controller';\nimport type { Provider } from '@metamask/network-controller';\nimport { StructError } from '@metamask/superstruct';\n\nimport { REFRESH_INTERVAL_MS } from '../constants';\nimport type {\n StatusResponse,\n StatusRequestWithSrcTxHash,\n StatusRequestDto,\n FetchFunction,\n BridgeHistoryItem,\n StatusRequest,\n BridgeStatusControllerMessenger,\n} from '../types';\nimport { isHistoryItemTooOld } from './history';\nimport { getNetworkClientByChainId } from './network';\nimport { validateBridgeStatusResponse } from './validators';\n\nexport const getBridgeStatusUrl = (bridgeApiBaseUrl: string): string =>\n `${bridgeApiBaseUrl}/getTxStatus`;\n\nexport const getStatusRequestDto = (\n statusRequest: StatusRequestWithSrcTxHash,\n): StatusRequestDto => {\n const { quote, ...statusRequestNoQuote } = statusRequest;\n\n const statusRequestNoQuoteFormatted = Object.fromEntries(\n Object.entries(statusRequestNoQuote).map(([key, value]) => [\n key,\n value.toString(),\n ]),\n ) as unknown as Omit<StatusRequestDto, 'requestId'>;\n\n const requestId: { requestId: string } | Record<string, never> =\n quote?.requestId ? { requestId: quote.requestId } : {};\n\n return {\n ...statusRequestNoQuoteFormatted,\n ...requestId,\n };\n};\n\nexport const fetchBridgeTxStatus = async (\n statusRequest: StatusRequestWithSrcTxHash,\n clientId: string,\n jwt: string | undefined,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<{ status: StatusResponse; validationFailures: string[] }> => {\n const statusRequestDto = getStatusRequestDto(statusRequest);\n const params = new URLSearchParams(statusRequestDto);\n\n // Fetch\n const url = `${getBridgeStatusUrl(bridgeApiBaseUrl)}?${params.toString()}`;\n\n const rawTxStatus: unknown = await fetchFn(url, {\n headers: getClientHeaders({ clientId, jwt }),\n });\n\n const validationFailures: string[] = [];\n\n try {\n validateBridgeStatusResponse(rawTxStatus);\n } catch (error) {\n // Build validation failure event properties\n if (error instanceof StructError) {\n error.failures().forEach(({ path }) => {\n const aggregatorId =\n (rawTxStatus as StatusResponse)?.bridge ??\n (statusRequest.bridge || statusRequest.bridgeId) ??\n ('unknown' as string);\n const pathString = path?.join('.') || 'unknown';\n validationFailures.push([aggregatorId, pathString].join('|'));\n });\n }\n }\n return {\n status: rawTxStatus as StatusResponse,\n validationFailures,\n };\n};\n\nexport const getStatusRequestWithSrcTxHash = (\n quote: Quote,\n srcTxHash: string,\n): StatusRequestWithSrcTxHash => {\n const { bridgeId, bridges, srcChainId, destChainId, refuel } = quote;\n return {\n bridgeId,\n srcTxHash,\n bridge: bridges[0],\n srcChainId,\n destChainId,\n quote,\n refuel: Boolean(refuel),\n };\n};\n\nexport const shouldSkipFetchDueToFetchFailures = (\n attempts?: BridgeHistoryItem['attempts'],\n): boolean => {\n // If there's an attempt, it means we've failed at least once,\n // so we need to check if we need to wait longer due to exponential backoff\n if (attempts) {\n // Calculate exponential backoff delay: base interval * 2^(attempts-1)\n const backoffDelay =\n REFRESH_INTERVAL_MS * Math.pow(2, attempts.counter - 1);\n const timeSinceLastAttempt = Date.now() - attempts.lastAttemptTime;\n\n if (timeSinceLastAttempt < backoffDelay) {\n // Not enough time has passed, skip this fetch\n return true;\n }\n }\n return false;\n};\n\n/*\n * Checks if a pending history item is older than 2 days and does not have a valid tx hash\n *\n * @param messenger - The messenger to use to get the transaction meta by hash or id\n * @param historyItem - The history item to check\n *\n * @returns true if the src tx hash is valid or we should still wait for it, false otherwise\n */\nexport const shouldWaitForFinalBridgeStatus = async (\n messenger: BridgeStatusControllerMessenger,\n historyItem: BridgeHistoryItem,\n): Promise<boolean> => {\n // Keep waiting for status if the history is not pending or is not old enough yet\n if (\n !(\n isHistoryItemTooOld(messenger, historyItem) &&\n [StatusTypes.PENDING, StatusTypes.UNKNOWN].includes(\n historyItem.status.status,\n )\n )\n ) {\n return true;\n }\n\n if (isNonEvmChainId(historyItem.quote.srcChainId)) {\n return false;\n }\n\n let provider: Provider;\n try {\n provider = getNetworkClientByChainId(\n messenger,\n historyItem.quote.srcChainId,\n );\n } catch {\n // This happens when the network is disabled while the tx is pending\n return true;\n }\n\n if (!historyItem.status.srcChain.txHash) {\n return false;\n }\n\n // Otherwise check if the tx has been mined on chain\n return provider\n .request({\n method: 'eth_getTransactionReceipt',\n params: [historyItem.status.srcChain.txHash],\n })\n .then((txReceipt) => {\n if (txReceipt) {\n return true;\n }\n return false;\n })\n .catch(() => {\n return false;\n });\n};\n\n/**\n * @deprecated Use getStatusRequestWithSrcTxHash instead\n * @param quoteResponse - The quote response to get the status request parameters from\n * @returns The status request parameters\n */\nexport const getStatusRequestParams = (\n quoteResponse: QuoteResponse,\n): StatusRequest => {\n return {\n bridgeId: quoteResponse.quote.bridgeId,\n bridge: quoteResponse.quote.bridges[0],\n srcChainId: quoteResponse.quote.srcChainId,\n destChainId: quoteResponse.quote.destChainId,\n quote: quoteResponse.quote,\n refuel: Boolean(quoteResponse.quote.refuel),\n };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"bridge-status.cjs","sourceRoot":"","sources":["../../src/utils/bridge-status.ts"],"names":[],"mappings":";;;AAAA,mEAIqC;AAGrC,uDAAoD;AAEpD,gDAAmD;AACnD,6FAAmF;AAUnF,2CAAgD;AAChD,2CAAsD;AACtD,iDAA4D;AAErD,MAAM,kBAAkB,GAAG,CAAC,gBAAwB,EAAU,EAAE,CACrE,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onEvmChainId,\n StatusTypes,\n} from '@metamask/bridge-controller';\nimport type { Quote, QuoteResponse } from '@metamask/bridge-controller';\nimport type { Provider } from '@metamask/network-controller';\nimport { StructError } from '@metamask/superstruct';\n\nimport { REFRESH_INTERVAL_MS } from '../constants';\nimport { QuoteStatusManager } from '../quote-status-manager/quotes-status-manager';\nimport type {\n StatusResponse,\n StatusRequestWithSrcTxHash,\n StatusRequestDto,\n FetchFunction,\n BridgeHistoryItem,\n StatusRequest,\n BridgeStatusControllerMessenger,\n} from '../types';\nimport { isHistoryItemTooOld } from './history';\nimport { getNetworkClientByChainId } from './network';\nimport { validateBridgeStatusResponse } from './validators';\n\nexport const getBridgeStatusUrl = (bridgeApiBaseUrl: string): string =>\n `${bridgeApiBaseUrl}/getTxStatus`;\n\nexport const getStatusRequestDto = (\n statusRequest: StatusRequestWithSrcTxHash,\n): StatusRequestDto => {\n const { quote, ...statusRequestNoQuote } = statusRequest;\n\n const statusRequestNoQuoteFormatted = Object.fromEntries(\n Object.entries(statusRequestNoQuote).map(([key, value]) => [\n key,\n value.toString(),\n ]),\n ) as unknown as Omit<StatusRequestDto, 'requestId'>;\n\n const requestId: { requestId: string } | Record<string, never> =\n quote?.requestId ? { requestId: quote.requestId } : {};\n\n return {\n ...statusRequestNoQuoteFormatted,\n ...requestId,\n };\n};\n\nexport const fetchBridgeQuoteStatus = async (\n quoteStatusManager: QuoteStatusManager,\n quoteId: string,\n): Promise<{ status: StatusResponse; validationFailures: string[] } | null> => {\n const response = await quoteStatusManager.getStatus(quoteId);\n\n const status = response?.response?.submittedTx;\n\n if (!status) {\n return null;\n }\n\n return {\n status,\n validationFailures: response.error?.details?.validationFailures ?? [],\n };\n};\n\nexport const fetchBridgeTxStatus = async (\n statusRequest: StatusRequestWithSrcTxHash,\n clientId: string,\n jwt: string | undefined,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<{ status: StatusResponse; validationFailures: string[] }> => {\n const statusRequestDto = getStatusRequestDto(statusRequest);\n const params = new URLSearchParams(statusRequestDto);\n\n // Fetch\n const url = `${getBridgeStatusUrl(bridgeApiBaseUrl)}?${params.toString()}`;\n\n const rawTxStatus: unknown = await fetchFn(url, {\n headers: getClientHeaders({ clientId, jwt }),\n });\n\n const validationFailures: string[] = [];\n\n try {\n validateBridgeStatusResponse(rawTxStatus);\n } catch (error) {\n // Build validation failure event properties\n if (error instanceof StructError) {\n error.failures().forEach(({ path }) => {\n const aggregatorId =\n (rawTxStatus as StatusResponse)?.bridge ??\n (statusRequest.bridge || statusRequest.bridgeId) ??\n ('unknown' as string);\n const pathString = path?.join('.') || 'unknown';\n validationFailures.push([aggregatorId, pathString].join('|'));\n });\n }\n }\n return {\n status: rawTxStatus as StatusResponse,\n validationFailures,\n };\n};\n\nexport const getStatusRequestWithSrcTxHash = (\n quote: Quote,\n srcTxHash: string,\n): StatusRequestWithSrcTxHash => {\n const { bridgeId, bridges, srcChainId, destChainId, refuel } = quote;\n return {\n bridgeId,\n srcTxHash,\n bridge: bridges[0],\n srcChainId,\n destChainId,\n quote,\n refuel: Boolean(refuel),\n };\n};\n\nexport const shouldSkipFetchDueToFetchFailures = (\n attempts?: BridgeHistoryItem['attempts'],\n): boolean => {\n // If there's an attempt, it means we've failed at least once,\n // so we need to check if we need to wait longer due to exponential backoff\n if (attempts) {\n // Calculate exponential backoff delay: base interval * 2^(attempts-1)\n const backoffDelay =\n REFRESH_INTERVAL_MS * Math.pow(2, attempts.counter - 1);\n const timeSinceLastAttempt = Date.now() - attempts.lastAttemptTime;\n\n if (timeSinceLastAttempt < backoffDelay) {\n // Not enough time has passed, skip this fetch\n return true;\n }\n }\n return false;\n};\n\n/*\n * Checks if a pending history item is older than 2 days and does not have a valid tx hash\n *\n * @param messenger - The messenger to use to get the transaction meta by hash or id\n * @param historyItem - The history item to check\n *\n * @returns true if the src tx hash is valid or we should still wait for it, false otherwise\n */\nexport const shouldWaitForFinalBridgeStatus = async (\n messenger: BridgeStatusControllerMessenger,\n historyItem: BridgeHistoryItem,\n): Promise<boolean> => {\n // Keep waiting for status if the history is not pending or is not old enough yet\n if (\n !(\n isHistoryItemTooOld(messenger, historyItem) &&\n [StatusTypes.PENDING, StatusTypes.UNKNOWN].includes(\n historyItem.status.status,\n )\n )\n ) {\n return true;\n }\n\n if (isNonEvmChainId(historyItem.quote.srcChainId)) {\n return false;\n }\n\n let provider: Provider;\n try {\n provider = getNetworkClientByChainId(\n messenger,\n historyItem.quote.srcChainId,\n );\n } catch {\n // This happens when the network is disabled while the tx is pending\n return true;\n }\n\n if (!historyItem.status.srcChain.txHash) {\n return false;\n }\n\n // Otherwise check if the tx has been mined on chain\n return provider\n .request({\n method: 'eth_getTransactionReceipt',\n params: [historyItem.status.srcChain.txHash],\n })\n .then((txReceipt) => {\n if (txReceipt) {\n return true;\n }\n return false;\n })\n .catch(() => {\n return false;\n });\n};\n\n/**\n * @deprecated Use getStatusRequestWithSrcTxHash instead\n * @param quoteResponse - The quote response to get the status request parameters from\n * @returns The status request parameters\n */\nexport const getStatusRequestParams = (\n quoteResponse: QuoteResponse,\n): StatusRequest => {\n return {\n bridgeId: quoteResponse.quote.bridgeId,\n bridge: quoteResponse.quote.bridges[0],\n srcChainId: quoteResponse.quote.srcChainId,\n destChainId: quoteResponse.quote.destChainId,\n quote: quoteResponse.quote,\n refuel: Boolean(quoteResponse.quote.refuel),\n };\n};\n"]}
|
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import type { Quote, QuoteResponse } from "@metamask/bridge-controller";
|
|
2
|
+
import { QuoteStatusManager } from "../quote-status-manager/quotes-status-manager.cjs";
|
|
2
3
|
import type { StatusResponse, StatusRequestWithSrcTxHash, StatusRequestDto, FetchFunction, BridgeHistoryItem, StatusRequest, BridgeStatusControllerMessenger } from "../types.cjs";
|
|
3
4
|
export declare const getBridgeStatusUrl: (bridgeApiBaseUrl: string) => string;
|
|
4
5
|
export declare const getStatusRequestDto: (statusRequest: StatusRequestWithSrcTxHash) => StatusRequestDto;
|
|
6
|
+
export declare const fetchBridgeQuoteStatus: (quoteStatusManager: QuoteStatusManager, quoteId: string) => Promise<{
|
|
7
|
+
status: StatusResponse;
|
|
8
|
+
validationFailures: string[];
|
|
9
|
+
} | null>;
|
|
5
10
|
export declare const fetchBridgeTxStatus: (statusRequest: StatusRequestWithSrcTxHash, clientId: string, jwt: string | undefined, fetchFn: FetchFunction, bridgeApiBaseUrl: string) => Promise<{
|
|
6
11
|
status: StatusResponse;
|
|
7
12
|
validationFailures: string[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge-status.d.cts","sourceRoot":"","sources":["../../src/utils/bridge-status.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,KAAK,EAAE,aAAa,EAAE,oCAAoC;AAKxE,OAAO,KAAK,EACV,cAAc,EACd,0BAA0B,EAC1B,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,aAAa,EACb,+BAA+B,EAChC,qBAAiB;AAKlB,eAAO,MAAM,kBAAkB,qBAAsB,MAAM,KAAG,MAC3B,CAAC;AAEpC,eAAO,MAAM,mBAAmB,kBACf,0BAA0B,KACxC,gBAiBF,CAAC;AAEF,eAAO,MAAM,mBAAmB,kBACf,0BAA0B,YAC/B,MAAM,OACX,MAAM,GAAG,SAAS,WACd,aAAa,oBACJ,MAAM;YACL,cAAc;wBAAsB,MAAM,EAAE;EAgChE,CAAC;AAEF,eAAO,MAAM,6BAA6B,UACjC,KAAK,aACD,MAAM,KAChB,0BAWF,CAAC;AAEF,eAAO,MAAM,iCAAiC,cACjC,iBAAiB,CAAC,UAAU,CAAC,KACvC,OAeF,CAAC;AAUF,eAAO,MAAM,8BAA8B,4DAE5B,iBAAiB,KAC7B,QAAQ,OAAO,CA+CjB,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,kBAClB,aAAa,KAC3B,aASF,CAAC"}
|
|
1
|
+
{"version":3,"file":"bridge-status.d.cts","sourceRoot":"","sources":["../../src/utils/bridge-status.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,KAAK,EAAE,aAAa,EAAE,oCAAoC;AAKxE,OAAO,EAAE,kBAAkB,EAAE,0DAAsD;AACnF,OAAO,KAAK,EACV,cAAc,EACd,0BAA0B,EAC1B,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,aAAa,EACb,+BAA+B,EAChC,qBAAiB;AAKlB,eAAO,MAAM,kBAAkB,qBAAsB,MAAM,KAAG,MAC3B,CAAC;AAEpC,eAAO,MAAM,mBAAmB,kBACf,0BAA0B,KACxC,gBAiBF,CAAC;AAEF,eAAO,MAAM,sBAAsB,uBACb,kBAAkB,WAC7B,MAAM;YACI,cAAc;wBAAsB,MAAM,EAAE;SAahE,CAAC;AAEF,eAAO,MAAM,mBAAmB,kBACf,0BAA0B,YAC/B,MAAM,OACX,MAAM,GAAG,SAAS,WACd,aAAa,oBACJ,MAAM;YACL,cAAc;wBAAsB,MAAM,EAAE;EAgChE,CAAC;AAEF,eAAO,MAAM,6BAA6B,UACjC,KAAK,aACD,MAAM,KAChB,0BAWF,CAAC;AAEF,eAAO,MAAM,iCAAiC,cACjC,iBAAiB,CAAC,UAAU,CAAC,KACvC,OAeF,CAAC;AAUF,eAAO,MAAM,8BAA8B,4DAE5B,iBAAiB,KAC7B,QAAQ,OAAO,CA+CjB,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,kBAClB,aAAa,KAC3B,aASF,CAAC"}
|
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import type { Quote, QuoteResponse } from "@metamask/bridge-controller";
|
|
2
|
+
import { QuoteStatusManager } from "../quote-status-manager/quotes-status-manager.mjs";
|
|
2
3
|
import type { StatusResponse, StatusRequestWithSrcTxHash, StatusRequestDto, FetchFunction, BridgeHistoryItem, StatusRequest, BridgeStatusControllerMessenger } from "../types.mjs";
|
|
3
4
|
export declare const getBridgeStatusUrl: (bridgeApiBaseUrl: string) => string;
|
|
4
5
|
export declare const getStatusRequestDto: (statusRequest: StatusRequestWithSrcTxHash) => StatusRequestDto;
|
|
6
|
+
export declare const fetchBridgeQuoteStatus: (quoteStatusManager: QuoteStatusManager, quoteId: string) => Promise<{
|
|
7
|
+
status: StatusResponse;
|
|
8
|
+
validationFailures: string[];
|
|
9
|
+
} | null>;
|
|
5
10
|
export declare const fetchBridgeTxStatus: (statusRequest: StatusRequestWithSrcTxHash, clientId: string, jwt: string | undefined, fetchFn: FetchFunction, bridgeApiBaseUrl: string) => Promise<{
|
|
6
11
|
status: StatusResponse;
|
|
7
12
|
validationFailures: string[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge-status.d.mts","sourceRoot":"","sources":["../../src/utils/bridge-status.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,KAAK,EAAE,aAAa,EAAE,oCAAoC;AAKxE,OAAO,KAAK,EACV,cAAc,EACd,0BAA0B,EAC1B,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,aAAa,EACb,+BAA+B,EAChC,qBAAiB;AAKlB,eAAO,MAAM,kBAAkB,qBAAsB,MAAM,KAAG,MAC3B,CAAC;AAEpC,eAAO,MAAM,mBAAmB,kBACf,0BAA0B,KACxC,gBAiBF,CAAC;AAEF,eAAO,MAAM,mBAAmB,kBACf,0BAA0B,YAC/B,MAAM,OACX,MAAM,GAAG,SAAS,WACd,aAAa,oBACJ,MAAM;YACL,cAAc;wBAAsB,MAAM,EAAE;EAgChE,CAAC;AAEF,eAAO,MAAM,6BAA6B,UACjC,KAAK,aACD,MAAM,KAChB,0BAWF,CAAC;AAEF,eAAO,MAAM,iCAAiC,cACjC,iBAAiB,CAAC,UAAU,CAAC,KACvC,OAeF,CAAC;AAUF,eAAO,MAAM,8BAA8B,4DAE5B,iBAAiB,KAC7B,QAAQ,OAAO,CA+CjB,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,kBAClB,aAAa,KAC3B,aASF,CAAC"}
|
|
1
|
+
{"version":3,"file":"bridge-status.d.mts","sourceRoot":"","sources":["../../src/utils/bridge-status.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,KAAK,EAAE,aAAa,EAAE,oCAAoC;AAKxE,OAAO,EAAE,kBAAkB,EAAE,0DAAsD;AACnF,OAAO,KAAK,EACV,cAAc,EACd,0BAA0B,EAC1B,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,aAAa,EACb,+BAA+B,EAChC,qBAAiB;AAKlB,eAAO,MAAM,kBAAkB,qBAAsB,MAAM,KAAG,MAC3B,CAAC;AAEpC,eAAO,MAAM,mBAAmB,kBACf,0BAA0B,KACxC,gBAiBF,CAAC;AAEF,eAAO,MAAM,sBAAsB,uBACb,kBAAkB,WAC7B,MAAM;YACI,cAAc;wBAAsB,MAAM,EAAE;SAahE,CAAC;AAEF,eAAO,MAAM,mBAAmB,kBACf,0BAA0B,YAC/B,MAAM,OACX,MAAM,GAAG,SAAS,WACd,aAAa,oBACJ,MAAM;YACL,cAAc;wBAAsB,MAAM,EAAE;EAgChE,CAAC;AAEF,eAAO,MAAM,6BAA6B,UACjC,KAAK,aACD,MAAM,KAChB,0BAWF,CAAC;AAEF,eAAO,MAAM,iCAAiC,cACjC,iBAAiB,CAAC,UAAU,CAAC,KACvC,OAeF,CAAC;AAUF,eAAO,MAAM,8BAA8B,4DAE5B,iBAAiB,KAC7B,QAAQ,OAAO,CA+CjB,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,kBAClB,aAAa,KAC3B,aASF,CAAC"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { getClientHeaders, isNonEvmChainId, StatusTypes } from "@metamask/bridge-controller";
|
|
2
2
|
import { StructError } from "@metamask/superstruct";
|
|
3
3
|
import { REFRESH_INTERVAL_MS } from "../constants.mjs";
|
|
4
|
+
import { QuoteStatusManager } from "../quote-status-manager/quotes-status-manager.mjs";
|
|
4
5
|
import { isHistoryItemTooOld } from "./history.mjs";
|
|
5
6
|
import { getNetworkClientByChainId } from "./network.mjs";
|
|
6
7
|
import { validateBridgeStatusResponse } from "./validators.mjs";
|
|
@@ -17,6 +18,17 @@ export const getStatusRequestDto = (statusRequest) => {
|
|
|
17
18
|
...requestId,
|
|
18
19
|
};
|
|
19
20
|
};
|
|
21
|
+
export const fetchBridgeQuoteStatus = async (quoteStatusManager, quoteId) => {
|
|
22
|
+
const response = await quoteStatusManager.getStatus(quoteId);
|
|
23
|
+
const status = response?.response?.submittedTx;
|
|
24
|
+
if (!status) {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
status,
|
|
29
|
+
validationFailures: response.error?.details?.validationFailures ?? [],
|
|
30
|
+
};
|
|
31
|
+
};
|
|
20
32
|
export const fetchBridgeTxStatus = async (statusRequest, clientId, jwt, fetchFn, bridgeApiBaseUrl) => {
|
|
21
33
|
const statusRequestDto = getStatusRequestDto(statusRequest);
|
|
22
34
|
const params = new URLSearchParams(statusRequestDto);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bridge-status.mjs","sourceRoot":"","sources":["../../src/utils/bridge-status.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,WAAW,EACZ,oCAAoC;AAGrC,OAAO,EAAE,WAAW,EAAE,8BAA8B;AAEpD,OAAO,EAAE,mBAAmB,EAAE,yBAAqB;AAUnD,OAAO,EAAE,mBAAmB,EAAE,sBAAkB;AAChD,OAAO,EAAE,yBAAyB,EAAE,sBAAkB;AACtD,OAAO,EAAE,4BAA4B,EAAE,yBAAqB;AAE5D,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,gBAAwB,EAAU,EAAE,CACrE,GAAG,gBAAgB,cAAc,CAAC;AAEpC,MAAM,CAAC,MAAM,mBAAmB,GAAG,CACjC,aAAyC,EACvB,EAAE;IACpB,MAAM,EAAE,KAAK,EAAE,GAAG,oBAAoB,EAAE,GAAG,aAAa,CAAC;IAEzD,MA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AAM,sBAAsB,GAAG,CACpC,aAA4B,EACb,EAAE;IACjB,OAAO;QACL,QAAQ,EAAE,aAAa,CAAC,KAAK,CAAC,QAAQ;QACtC,MAAM,EAAE,aAAa,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;QACtC,UAAU,EAAE,aAAa,CAAC,KAAK,CAAC,UAAU;QAC1C,WAAW,EAAE,aAAa,CAAC,KAAK,CAAC,WAAW;QAC5C,KAAK,EAAE,aAAa,CAAC,KAAK;QAC1B,MAAM,EAAE,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,MAAM,CAAC;KAC5C,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import {\n getClientHeaders,\n isNonEvmChainId,\n StatusTypes,\n} from '@metamask/bridge-controller';\nimport type { Quote, QuoteResponse } from '@metamask/bridge-controller';\nimport type { Provider } from '@metamask/network-controller';\nimport { StructError } from '@metamask/superstruct';\n\nimport { REFRESH_INTERVAL_MS } from '../constants';\nimport type {\n StatusResponse,\n StatusRequestWithSrcTxHash,\n StatusRequestDto,\n FetchFunction,\n BridgeHistoryItem,\n StatusRequest,\n BridgeStatusControllerMessenger,\n} from '../types';\nimport { isHistoryItemTooOld } from './history';\nimport { getNetworkClientByChainId } from './network';\nimport { validateBridgeStatusResponse } from './validators';\n\nexport const getBridgeStatusUrl = (bridgeApiBaseUrl: string): string =>\n `${bridgeApiBaseUrl}/getTxStatus`;\n\nexport const getStatusRequestDto = (\n statusRequest: StatusRequestWithSrcTxHash,\n): StatusRequestDto => {\n const { quote, ...statusRequestNoQuote } = statusRequest;\n\n const statusRequestNoQuoteFormatted = Object.fromEntries(\n Object.entries(statusRequestNoQuote).map(([key, value]) => [\n key,\n value.toString(),\n ]),\n ) as unknown as Omit<StatusRequestDto, 'requestId'>;\n\n const requestId: { requestId: string } | Record<string, never> =\n quote?.requestId ? { requestId: quote.requestId } : {};\n\n return {\n ...statusRequestNoQuoteFormatted,\n ...requestId,\n };\n};\n\nexport const fetchBridgeTxStatus = async (\n statusRequest: StatusRequestWithSrcTxHash,\n clientId: string,\n jwt: string | undefined,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<{ status: StatusResponse; validationFailures: string[] }> => {\n const statusRequestDto = getStatusRequestDto(statusRequest);\n const params = new URLSearchParams(statusRequestDto);\n\n // Fetch\n const url = `${getBridgeStatusUrl(bridgeApiBaseUrl)}?${params.toString()}`;\n\n const rawTxStatus: unknown = await fetchFn(url, {\n headers: getClientHeaders({ clientId, jwt }),\n });\n\n const validationFailures: string[] = [];\n\n try {\n validateBridgeStatusResponse(rawTxStatus);\n } catch (error) {\n // Build validation failure event properties\n if (error instanceof StructError) {\n error.failures().forEach(({ path }) => {\n const aggregatorId =\n (rawTxStatus as StatusResponse)?.bridge ??\n (statusRequest.bridge || statusRequest.bridgeId) ??\n ('unknown' as string);\n const pathString = path?.join('.') || 'unknown';\n validationFailures.push([aggregatorId, pathString].join('|'));\n });\n }\n }\n return {\n status: rawTxStatus as StatusResponse,\n validationFailures,\n };\n};\n\nexport const getStatusRequestWithSrcTxHash = (\n quote: Quote,\n srcTxHash: string,\n): StatusRequestWithSrcTxHash => {\n const { bridgeId, bridges, srcChainId, destChainId, refuel } = quote;\n return {\n bridgeId,\n srcTxHash,\n bridge: bridges[0],\n srcChainId,\n destChainId,\n quote,\n refuel: Boolean(refuel),\n };\n};\n\nexport const shouldSkipFetchDueToFetchFailures = (\n attempts?: BridgeHistoryItem['attempts'],\n): boolean => {\n // If there's an attempt, it means we've failed at least once,\n // so we need to check if we need to wait longer due to exponential backoff\n if (attempts) {\n // Calculate exponential backoff delay: base interval * 2^(attempts-1)\n const backoffDelay =\n REFRESH_INTERVAL_MS * Math.pow(2, attempts.counter - 1);\n const timeSinceLastAttempt = Date.now() - attempts.lastAttemptTime;\n\n if (timeSinceLastAttempt < backoffDelay) {\n // Not enough time has passed, skip this fetch\n return true;\n }\n }\n return false;\n};\n\n/*\n * Checks if a pending history item is older than 2 days and does not have a valid tx hash\n *\n * @param messenger - The messenger to use to get the transaction meta by hash or id\n * @param historyItem - The history item to check\n *\n * @returns true if the src tx hash is valid or we should still wait for it, false otherwise\n */\nexport const shouldWaitForFinalBridgeStatus = async (\n messenger: BridgeStatusControllerMessenger,\n historyItem: BridgeHistoryItem,\n): Promise<boolean> => {\n // Keep waiting for status if the history is not pending or is not old enough yet\n if (\n !(\n isHistoryItemTooOld(messenger, historyItem) &&\n [StatusTypes.PENDING, StatusTypes.UNKNOWN].includes(\n historyItem.status.status,\n )\n )\n ) {\n return true;\n }\n\n if (isNonEvmChainId(historyItem.quote.srcChainId)) {\n return false;\n }\n\n let provider: Provider;\n try {\n provider = getNetworkClientByChainId(\n messenger,\n historyItem.quote.srcChainId,\n );\n } catch {\n // This happens when the network is disabled while the tx is pending\n return true;\n }\n\n if (!historyItem.status.srcChain.txHash) {\n return false;\n }\n\n // Otherwise check if the tx has been mined on chain\n return provider\n .request({\n method: 'eth_getTransactionReceipt',\n params: [historyItem.status.srcChain.txHash],\n })\n .then((txReceipt) => {\n if (txReceipt) {\n return true;\n }\n return false;\n })\n .catch(() => {\n return false;\n });\n};\n\n/**\n * @deprecated Use getStatusRequestWithSrcTxHash instead\n * @param quoteResponse - The quote response to get the status request parameters from\n * @returns The status request parameters\n */\nexport const getStatusRequestParams = (\n quoteResponse: QuoteResponse,\n): StatusRequest => {\n return {\n bridgeId: quoteResponse.quote.bridgeId,\n bridge: quoteResponse.quote.bridges[0],\n srcChainId: quoteResponse.quote.srcChainId,\n destChainId: quoteResponse.quote.destChainId,\n quote: quoteResponse.quote,\n refuel: Boolean(quoteResponse.quote.refuel),\n };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"bridge-status.mjs","sourceRoot":"","sources":["../../src/utils/bridge-status.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,gBAAgB,EAChB,eAAe,EACf,WAAW,EACZ,oCAAoC;AAGrC,OAAO,EAAE,WAAW,EAAE,8BAA8B;AAEpD,OAAO,EAAE,mBAAmB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C;AACJ,CAAC,CAAC","sourcesContent":["import {\n getClientHeaders,\n isNonEvmChainId,\n StatusTypes,\n} from '@metamask/bridge-controller';\nimport type { Quote, QuoteResponse } from '@metamask/bridge-controller';\nimport type { Provider } from '@metamask/network-controller';\nimport { StructError } from '@metamask/superstruct';\n\nimport { REFRESH_INTERVAL_MS } from '../constants';\nimport { QuoteStatusManager } from '../quote-status-manager/quotes-status-manager';\nimport type {\n StatusResponse,\n StatusRequestWithSrcTxHash,\n StatusRequestDto,\n FetchFunction,\n BridgeHistoryItem,\n StatusRequest,\n BridgeStatusControllerMessenger,\n} from '../types';\nimport { isHistoryItemTooOld } from './history';\nimport { getNetworkClientByChainId } from './network';\nimport { validateBridgeStatusResponse } from './validators';\n\nexport const getBridgeStatusUrl = (bridgeApiBaseUrl: string): string =>\n `${bridgeApiBaseUrl}/getTxStatus`;\n\nexport const getStatusRequestDto = (\n statusRequest: StatusRequestWithSrcTxHash,\n): StatusRequestDto => {\n const { quote, ...statusRequestNoQuote } = statusRequest;\n\n const statusRequestNoQuoteFormatted = Object.fromEntries(\n Object.entries(statusRequestNoQuote).map(([key, value]) => [\n key,\n value.toString(),\n ]),\n ) as unknown as Omit<StatusRequestDto, 'requestId'>;\n\n const requestId: { requestId: string } | Record<string, never> =\n quote?.requestId ? { requestId: quote.requestId } : {};\n\n return {\n ...statusRequestNoQuoteFormatted,\n ...requestId,\n };\n};\n\nexport const fetchBridgeQuoteStatus = async (\n quoteStatusManager: QuoteStatusManager,\n quoteId: string,\n): Promise<{ status: StatusResponse; validationFailures: string[] } | null> => {\n const response = await quoteStatusManager.getStatus(quoteId);\n\n const status = response?.response?.submittedTx;\n\n if (!status) {\n return null;\n }\n\n return {\n status,\n validationFailures: response.error?.details?.validationFailures ?? [],\n };\n};\n\nexport const fetchBridgeTxStatus = async (\n statusRequest: StatusRequestWithSrcTxHash,\n clientId: string,\n jwt: string | undefined,\n fetchFn: FetchFunction,\n bridgeApiBaseUrl: string,\n): Promise<{ status: StatusResponse; validationFailures: string[] }> => {\n const statusRequestDto = getStatusRequestDto(statusRequest);\n const params = new URLSearchParams(statusRequestDto);\n\n // Fetch\n const url = `${getBridgeStatusUrl(bridgeApiBaseUrl)}?${params.toString()}`;\n\n const rawTxStatus: unknown = await fetchFn(url, {\n headers: getClientHeaders({ clientId, jwt }),\n });\n\n const validationFailures: string[] = [];\n\n try {\n validateBridgeStatusResponse(rawTxStatus);\n } catch (error) {\n // Build validation failure event properties\n if (error instanceof StructError) {\n error.failures().forEach(({ path }) => {\n const aggregatorId =\n (rawTxStatus as StatusResponse)?.bridge ??\n (statusRequest.bridge || statusRequest.bridgeId) ??\n ('unknown' as string);\n const pathString = path?.join('.') || 'unknown';\n validationFailures.push([aggregatorId, pathString].join('|'));\n });\n }\n }\n return {\n status: rawTxStatus as StatusResponse,\n validationFailures,\n };\n};\n\nexport const getStatusRequestWithSrcTxHash = (\n quote: Quote,\n srcTxHash: string,\n): StatusRequestWithSrcTxHash => {\n const { bridgeId, bridges, srcChainId, destChainId, refuel } = quote;\n return {\n bridgeId,\n srcTxHash,\n bridge: bridges[0],\n srcChainId,\n destChainId,\n quote,\n refuel: Boolean(refuel),\n };\n};\n\nexport const shouldSkipFetchDueToFetchFailures = (\n attempts?: BridgeHistoryItem['attempts'],\n): boolean => {\n // If there's an attempt, it means we've failed at least once,\n // so we need to check if we need to wait longer due to exponential backoff\n if (attempts) {\n // Calculate exponential backoff delay: base interval * 2^(attempts-1)\n const backoffDelay =\n REFRESH_INTERVAL_MS * Math.pow(2, attempts.counter - 1);\n const timeSinceLastAttempt = Date.now() - attempts.lastAttemptTime;\n\n if (timeSinceLastAttempt < backoffDelay) {\n // Not enough time has passed, skip this fetch\n return true;\n }\n }\n return false;\n};\n\n/*\n * Checks if a pending history item is older than 2 days and does not have a valid tx hash\n *\n * @param messenger - The messenger to use to get the transaction meta by hash or id\n * @param historyItem - The history item to check\n *\n * @returns true if the src tx hash is valid or we should still wait for it, false otherwise\n */\nexport const shouldWaitForFinalBridgeStatus = async (\n messenger: BridgeStatusControllerMessenger,\n historyItem: BridgeHistoryItem,\n): Promise<boolean> => {\n // Keep waiting for status if the history is not pending or is not old enough yet\n if (\n !(\n isHistoryItemTooOld(messenger, historyItem) &&\n [StatusTypes.PENDING, StatusTypes.UNKNOWN].includes(\n historyItem.status.status,\n )\n )\n ) {\n return true;\n }\n\n if (isNonEvmChainId(historyItem.quote.srcChainId)) {\n return false;\n }\n\n let provider: Provider;\n try {\n provider = getNetworkClientByChainId(\n messenger,\n historyItem.quote.srcChainId,\n );\n } catch {\n // This happens when the network is disabled while the tx is pending\n return true;\n }\n\n if (!historyItem.status.srcChain.txHash) {\n return false;\n }\n\n // Otherwise check if the tx has been mined on chain\n return provider\n .request({\n method: 'eth_getTransactionReceipt',\n params: [historyItem.status.srcChain.txHash],\n })\n .then((txReceipt) => {\n if (txReceipt) {\n return true;\n }\n return false;\n })\n .catch(() => {\n return false;\n });\n};\n\n/**\n * @deprecated Use getStatusRequestWithSrcTxHash instead\n * @param quoteResponse - The quote response to get the status request parameters from\n * @returns The status request parameters\n */\nexport const getStatusRequestParams = (\n quoteResponse: QuoteResponse,\n): StatusRequest => {\n return {\n bridgeId: quoteResponse.quote.bridgeId,\n bridge: quoteResponse.quote.bridges[0],\n srcChainId: quoteResponse.quote.srcChainId,\n destChainId: quoteResponse.quote.destChainId,\n quote: quoteResponse.quote,\n refuel: Boolean(quoteResponse.quote.refuel),\n };\n};\n"]}
|
package/dist/utils/snaps.cjs
CHANGED
|
@@ -52,15 +52,20 @@ const getClientRequest = (trade, srcChainId, accountId, snapId, sourceAssetId, d
|
|
|
52
52
|
const scope = (0, bridge_controller_1.formatChainIdToCaip)(srcChainId);
|
|
53
53
|
const transaction = (0, bridge_controller_1.extractTradeData)(trade);
|
|
54
54
|
let options;
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
55
|
+
// Only Stellar trades expect asset IDs in the request options. Passing them
|
|
56
|
+
// for other non-EVM chains (e.g. Bitcoin) breaks strict snap request
|
|
57
|
+
// validation and prevents the transaction from being broadcast.
|
|
58
|
+
if ((0, bridge_controller_1.isStellarTrade)(trade)) {
|
|
59
|
+
if (sourceAssetId !== undefined || destAssetId !== undefined) {
|
|
60
|
+
options = {
|
|
61
|
+
...(sourceAssetId !== undefined && {
|
|
62
|
+
sourceAssetId,
|
|
63
|
+
}),
|
|
64
|
+
...(destAssetId !== undefined && {
|
|
65
|
+
destAssetId,
|
|
66
|
+
}),
|
|
67
|
+
};
|
|
68
|
+
}
|
|
64
69
|
}
|
|
65
70
|
if ((0, bridge_controller_1.isTronTrade)(trade)) {
|
|
66
71
|
// Tron trades need the visible flag and contract type to be included in the request options
|
package/dist/utils/snaps.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snaps.cjs","sourceRoot":"","sources":["../../src/utils/snaps.ts"],"names":[],"mappings":";;;AAOA,mEAMqC;AACrC,mEAA6D;AAC7D,6EAI0C;AAG1C,+BAAkC;AAOlC;;;;;;;;;;GAUG;AACI,MAAM,8BAA8B,GAAG,CAC5C,MAAc,EACd,WAAmB,EACnB,KAAkB,EAClB,SAAiB,EACjB,OAAiC,EACjC,EAAE;IACF,OAAO;QACL,kCAAkC;QAClC,MAAM,EAAE,MAAe;QACvB,MAAM,EAAE,UAAU;QAClB,OAAO,EAAE,iBAA0B;QACnC,OAAO,EAAE;YACP,EAAE,EAAE,IAAA,SAAI,GAAE;YACV,OAAO,EAAE,KAAK;YACd,MAAM,EAAE,wBAAwB;YAChC,MAAM,EAAE;gBACN,WAAW;gBACX,KAAK;gBACL,SAAS;gBACT,GAAG,CAAC,OAAO,IAAI,EAAE,OAAO,EAAE,CAAC;aAC5B;SACF;KACF,CAAC;AACJ,CAAC,CAAC;AAxBW,QAAA,8BAA8B,kCAwBzC;AAEF;;;;;;;;;;;GAWG;AACI,MA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AAE,0CAAiB,CAAC,SAAS;QACnC,IAAI,EAAE,wCAAwC;QAC9C,MAAM,EAAE,MAAM;QACd,6DAA6D;QAC7D,QAAQ,EAAE,IAAI,EAAE,+DAA+D;QAC/E,UAAU;KACX,CAAC;AACJ,CAAC,CAAC;AAvEW,QAAA,sBAAsB,0BAuEjC;AAEF;;;;;;;;;;;GAWG;AACI,MAAM,cAAc,GAAG,KAAK,EACjC,SAA0C,EAC1C,KAAY,EACZ,aAA0D,EAC1D,eAAgF,EACtD,EAAE;IAC5B,IAAI,CAAC,eAAe,CAAC,QAAQ,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC;QACxC,MAAM,IAAI,KAAK,CACb,kEAAkE,CACnE,CAAC;IACJ,CAAC;IAED,MAAM,OAAO,GAAG,IAAA,wBAAgB,EAC9B,KAAK,EACL,aAAa,CAAC,KAAK,CAAC,UAAU,EAC9B,eAAe,CAAC,EAAE,EAClB,eAAe,CAAC,QAAQ,EAAE,IAAI,EAAE,EAAE,EAClC,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,EACpC,aAAa,CAAC,KAAK,CAAC,SAAS,CAAC,OAAO,CACtC,CAAC;IACF,MAAM,eAAe,GAAG,CAAC,MAAM,SAAS,CAAC,IAAI,CAC3C,8BAA8B,EAC9B,OAAO,CACR,CAIwB,CAAC;IAE1B,MAAM,MAAM,GAAG,IAAA,8BAAsB,EACnC,eAAe,EACf,KAAK,EACL,aAAa,EACb,eAAe,CAChB,CAAC;IAEF,iFAAiF;IACjF,uNAAuN;IACvN,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC;AAvCW,QAAA,cAAc,kBAuCzB","sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\nimport type { AccountsControllerState } from '@metamask/accounts-controller';\nimport type {\n QuoteMetadata,\n QuoteResponse,\n Trade,\n} from '@metamask/bridge-controller';\nimport {\n extractTradeData,\n formatChainIdToCaip,\n formatChainIdToHex,\n isCrossChain,\n isTronTrade,\n} from '@metamask/bridge-controller';\nimport { SnapController } from '@metamask/snaps-controllers';\nimport {\n CHAIN_IDS,\n TransactionStatus,\n TransactionType,\n} from '@metamask/transaction-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';\nimport { v4 as uuid } from 'uuid';\n\nimport type {\n BridgeStatusControllerMessenger,\n SolanaTransactionMeta,\n} from '../types';\n\n/**\n * Creates a client request object for signing and sending a transaction\n * Works for Solana, BTC, Tron, and other non-EVM networks\n *\n * @param snapId - The snap ID to send the request to\n * @param transaction - The base64 encoded transaction string\n * @param scope - The CAIP-2 chain scope\n * @param accountId - The account ID\n * @param options - Optional network-specific options\n * @returns The snap request object\n */\nexport const createClientTransactionRequest = (\n snapId: string,\n transaction: string,\n scope: CaipChainId,\n accountId: string,\n options?: Record<string, unknown>,\n) => {\n return {\n // TODO: remove 'as never' typing.\n snapId: snapId as never,\n origin: 'metamask',\n handler: 'onClientRequest' as never,\n request: {\n id: uuid(),\n jsonrpc: '2.0',\n method: 'signAndSendTransaction',\n params: {\n transaction,\n scope,\n accountId,\n ...(options && { options }),\n },\n },\n };\n};\n\n/**\n * Creates a request to sign and send a transaction for non-EVM chains\n * Uses the new unified ClientRequest:signAndSendTransaction interface\n *\n * @param trade - The trade data\n * @param srcChainId - The source chain ID\n * @param accountId - The account ID\n * @param snapId - The snap ID\n * @param sourceAssetId - The source asset ID\n * @param destAssetId - The destination asset ID\n * @returns The snap request object for signing and sending transaction\n */\nexport const getClientRequest = (\n trade: Trade,\n srcChainId: number,\n accountId: AccountsControllerState['internalAccounts']['accounts'][string]['id'],\n snapId: string,\n sourceAssetId?: CaipAssetType,\n destAssetId?: CaipAssetType,\n): Parameters<SnapController['handleRequest']>[0] => {\n const scope = formatChainIdToCaip(srcChainId);\n\n const transaction = extractTradeData(trade);\n\n let options: Record<string, unknown> | undefined;\n\n if (sourceAssetId !== undefined || destAssetId !== undefined) {\n options = {\n ...(sourceAssetId !== undefined && {\n sourceAssetId,\n }),\n ...(destAssetId !== undefined && {\n destAssetId,\n }),\n };\n }\n\n if (isTronTrade(trade)) {\n // Tron trades need the visible flag and contract type to be included in the request options\n options = {\n visible: trade.visible,\n type: trade.raw_data?.contract?.[0]?.type,\n };\n }\n\n return createClientTransactionRequest(\n snapId,\n transaction,\n scope,\n accountId,\n options,\n );\n};\n\nexport const getTxMetaFields = (\n quoteResponse: Omit<QuoteResponse<Trade, Trade>, 'approval' | 'trade'> &\n QuoteMetadata,\n approvalTxId?: string,\n): Omit<\n TransactionMeta,\n 'networkClientId' | 'status' | 'time' | 'txParams' | 'id' | 'chainId'\n> => {\n // Handle destination chain ID - should always be convertible for EVM destinations\n let destinationChainId;\n try {\n destinationChainId = formatChainIdToHex(quoteResponse.quote.destChainId);\n } catch {\n // Fallback for non-EVM destination (shouldn't happen for BTC->EVM)\n destinationChainId = CHAIN_IDS.MAINNET; // Default to mainnet\n }\n\n return {\n destinationChainId,\n sourceTokenAmount: quoteResponse.quote.srcTokenAmount,\n sourceTokenSymbol: quoteResponse.quote.srcAsset.symbol,\n sourceTokenDecimals: quoteResponse.quote.srcAsset.decimals,\n sourceTokenAddress: quoteResponse.quote.srcAsset.address,\n\n destinationTokenAmount: quoteResponse.quote.destTokenAmount,\n destinationTokenSymbol: quoteResponse.quote.destAsset.symbol,\n destinationTokenDecimals: quoteResponse.quote.destAsset.decimals,\n destinationTokenAddress: quoteResponse.quote.destAsset.address,\n\n // chainId is now excluded from this function and handled by the caller\n approvalTxId,\n // this is the decimal (non atomic) amount (not USD value) of source token to swap\n swapTokenValue: quoteResponse.sentAmount.amount,\n };\n};\n\n/**\n * Handles the response from non-EVM transaction submission\n * Works with the new unified ClientRequest:signAndSendTransaction interface\n * Supports Solana, Bitcoin, and other non-EVM chains\n *\n * @param snapResponse - The response from the snap after transaction submission\n * @param trade - The non-evm trade or approval data\n * @param quoteResponse - The quote response containing trade details and metadata\n * @param selectedAccount - The selected account information\n * @returns The transaction metadata including non-EVM specific fields\n */\nexport const handleNonEvmTxResponse = (\n snapResponse:\n | string\n | { transactionId: string } // New unified interface response\n | { result: Record<string, string> }\n | { signature: string },\n trade: Trade,\n quoteResponse: Omit<QuoteResponse<Trade>, 'trade' | 'approval'> &\n QuoteMetadata,\n selectedAccount: AccountsControllerState['internalAccounts']['accounts'][string],\n): TransactionMeta & SolanaTransactionMeta => {\n const selectedAccountAddress = selectedAccount.address;\n const snapId = selectedAccount.metadata.snap?.id;\n let hash;\n // Handle different response formats\n if (typeof snapResponse === 'string') {\n hash = snapResponse;\n } else if (snapResponse && typeof snapResponse === 'object') {\n // Check for new unified interface response format first\n if ('transactionId' in snapResponse && snapResponse.transactionId) {\n hash = snapResponse.transactionId;\n } else if (\n 'result' in snapResponse &&\n snapResponse.result &&\n typeof snapResponse.result === 'object'\n ) {\n // Try to extract signature from common locations in response object\n hash =\n snapResponse.result.signature ||\n snapResponse.result.txid ||\n snapResponse.result.hash ||\n snapResponse.result.txHash;\n } else if (\n 'signature' in snapResponse &&\n snapResponse.signature &&\n typeof snapResponse.signature === 'string'\n ) {\n hash = snapResponse.signature;\n }\n }\n\n const isBridgeTx = isCrossChain(\n quoteResponse.quote.srcChainId,\n quoteResponse.quote.destChainId,\n );\n\n let hexChainId: Hex;\n try {\n hexChainId = formatChainIdToHex(quoteResponse.quote.srcChainId);\n } catch {\n hexChainId = '0x1';\n }\n // Extract the transaction data for storage\n const tradeData = extractTradeData(trade);\n\n // Create a transaction meta object with bridge-specific fields\n return {\n ...getTxMetaFields(quoteResponse),\n time: Date.now(),\n id: hash ?? uuid(),\n chainId: hexChainId,\n networkClientId: snapId ?? 'mainnet',\n txParams: { from: selectedAccountAddress, data: tradeData },\n type: isBridgeTx ? TransactionType.bridge : TransactionType.swap,\n status: TransactionStatus.submitted,\n hash, // Add the transaction signature as hash\n origin: snapId,\n // Add an explicit flag to mark this as a non-EVM transaction\n isSolana: true, // TODO deprecate this and use chainId to detect non-EVM chains\n isBridgeTx,\n };\n};\n\n/**\n * Submits the transaction to the snap using the new unified ClientRequest interface\n * Works for all non-EVM chains (Solana, BTC, Tron)\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 messenger - The BridgeStatusControllerMessenger instance\n * @param trade - The trade data (can be approval or main trade)\n * @param quoteResponse - The quote response containing metadata\n * @param selectedAccount - The account to submit the transaction for\n * @returns The transaction meta\n */\nexport const handleNonEvmTx = async (\n messenger: BridgeStatusControllerMessenger,\n trade: Trade,\n quoteResponse: QuoteResponse<Trade, Trade> & QuoteMetadata,\n selectedAccount: AccountsControllerState['internalAccounts']['accounts'][string],\n): Promise<TransactionMeta> => {\n if (!selectedAccount.metadata?.snap?.id) {\n throw new Error(\n 'Failed to submit cross-chain swap transaction: undefined snap id',\n );\n }\n\n const request = getClientRequest(\n trade,\n quoteResponse.quote.srcChainId,\n selectedAccount.id,\n selectedAccount.metadata?.snap?.id,\n quoteResponse.quote.srcAsset.assetId,\n quoteResponse.quote.destAsset.assetId,\n );\n const requestResponse = (await messenger.call(\n 'SnapController:handleRequest',\n request,\n )) as\n | string\n | { transactionId: string }\n | { result: Record<string, string> }\n | { signature: string };\n\n const txMeta = handleNonEvmTxResponse(\n requestResponse,\n trade,\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"]}
|
|
1
|
+
{"version":3,"file":"snaps.cjs","sourceRoot":"","sources":["../../src/utils/snaps.ts"],"names":[],"mappings":";;;AAOA,mEAOqC;AACrC,mEAA6D;AAC7D,6EAI0C;AAG1C,+BAAkC;AAOlC;;;;;;;;;;GAUG;AACI,MAAM,8BAA8B,GAAG,CAC5C,MAAc,EACd,WAAmB,EACnB,KAAkB,EAClB,SAAiB,EACjB,OAAiC,EACjC,E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SAAS,CAAC,OAAO,CACtC,CAAC;IACF,MAAM,eAAe,GAAG,CAAC,MAAM,SAAS,CAAC,IAAI,CAC3C,8BAA8B,EAC9B,OAAO,CACR,CAIwB,CAAC;IAE1B,MAAM,MAAM,GAAG,IAAA,8BAAsB,EACnC,eAAe,EACf,KAAK,EACL,aAAa,EACb,eAAe,CAChB,CAAC;IAEF,iFAAiF;IACjF,uNAAuN;IACvN,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC;AAvCW,QAAA,cAAc,kBAuCzB","sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\nimport type { AccountsControllerState } from '@metamask/accounts-controller';\nimport type {\n QuoteMetadata,\n QuoteResponse,\n Trade,\n} from '@metamask/bridge-controller';\nimport {\n extractTradeData,\n formatChainIdToCaip,\n formatChainIdToHex,\n isCrossChain,\n isStellarTrade,\n isTronTrade,\n} from '@metamask/bridge-controller';\nimport { SnapController } from '@metamask/snaps-controllers';\nimport {\n CHAIN_IDS,\n TransactionStatus,\n TransactionType,\n} from '@metamask/transaction-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { CaipAssetType, CaipChainId, Hex } from '@metamask/utils';\nimport { v4 as uuid } from 'uuid';\n\nimport type {\n BridgeStatusControllerMessenger,\n SolanaTransactionMeta,\n} from '../types';\n\n/**\n * Creates a client request object for signing and sending a transaction\n * Works for Solana, BTC, Tron, and other non-EVM networks\n *\n * @param snapId - The snap ID to send the request to\n * @param transaction - The base64 encoded transaction string\n * @param scope - The CAIP-2 chain scope\n * @param accountId - The account ID\n * @param options - Optional network-specific options\n * @returns The snap request object\n */\nexport const createClientTransactionRequest = (\n snapId: string,\n transaction: string,\n scope: CaipChainId,\n accountId: string,\n options?: Record<string, unknown>,\n) => {\n return {\n // TODO: remove 'as never' typing.\n snapId: snapId as never,\n origin: 'metamask',\n handler: 'onClientRequest' as never,\n request: {\n id: uuid(),\n jsonrpc: '2.0',\n method: 'signAndSendTransaction',\n params: {\n transaction,\n scope,\n accountId,\n ...(options && { options }),\n },\n },\n };\n};\n\n/**\n * Creates a request to sign and send a transaction for non-EVM chains\n * Uses the new unified ClientRequest:signAndSendTransaction interface\n *\n * @param trade - The trade data\n * @param srcChainId - The source chain ID\n * @param accountId - The account ID\n * @param snapId - The snap ID\n * @param sourceAssetId - The source asset ID\n * @param destAssetId - The destination asset ID\n * @returns The snap request object for signing and sending transaction\n */\nexport const getClientRequest = (\n trade: Trade,\n srcChainId: number,\n accountId: AccountsControllerState['internalAccounts']['accounts'][string]['id'],\n snapId: string,\n sourceAssetId?: CaipAssetType,\n destAssetId?: CaipAssetType,\n): Parameters<SnapController['handleRequest']>[0] => {\n const scope = formatChainIdToCaip(srcChainId);\n\n const transaction = extractTradeData(trade);\n\n let options: Record<string, unknown> | undefined;\n\n // Only Stellar trades expect asset IDs in the request options. Passing them\n // for other non-EVM chains (e.g. Bitcoin) breaks strict snap request\n // validation and prevents the transaction from being broadcast.\n if (isStellarTrade(trade)) {\n if (sourceAssetId !== undefined || destAssetId !== undefined) {\n options = {\n ...(sourceAssetId !== undefined && {\n sourceAssetId,\n }),\n ...(destAssetId !== undefined && {\n destAssetId,\n }),\n };\n }\n }\n\n if (isTronTrade(trade)) {\n // Tron trades need the visible flag and contract type to be included in the request options\n options = {\n visible: trade.visible,\n type: trade.raw_data?.contract?.[0]?.type,\n };\n }\n\n return createClientTransactionRequest(\n snapId,\n transaction,\n scope,\n accountId,\n options,\n );\n};\n\nexport const getTxMetaFields = (\n quoteResponse: Omit<QuoteResponse<Trade, Trade>, 'approval' | 'trade'> &\n QuoteMetadata,\n approvalTxId?: string,\n): Omit<\n TransactionMeta,\n 'networkClientId' | 'status' | 'time' | 'txParams' | 'id' | 'chainId'\n> => {\n // Handle destination chain ID - should always be convertible for EVM destinations\n let destinationChainId;\n try {\n destinationChainId = formatChainIdToHex(quoteResponse.quote.destChainId);\n } catch {\n // Fallback for non-EVM destination (shouldn't happen for BTC->EVM)\n destinationChainId = CHAIN_IDS.MAINNET; // Default to mainnet\n }\n\n return {\n destinationChainId,\n sourceTokenAmount: quoteResponse.quote.srcTokenAmount,\n sourceTokenSymbol: quoteResponse.quote.srcAsset.symbol,\n sourceTokenDecimals: quoteResponse.quote.srcAsset.decimals,\n sourceTokenAddress: quoteResponse.quote.srcAsset.address,\n\n destinationTokenAmount: quoteResponse.quote.destTokenAmount,\n destinationTokenSymbol: quoteResponse.quote.destAsset.symbol,\n destinationTokenDecimals: quoteResponse.quote.destAsset.decimals,\n destinationTokenAddress: quoteResponse.quote.destAsset.address,\n\n // chainId is now excluded from this function and handled by the caller\n approvalTxId,\n // this is the decimal (non atomic) amount (not USD value) of source token to swap\n swapTokenValue: quoteResponse.sentAmount.amount,\n };\n};\n\n/**\n * Handles the response from non-EVM transaction submission\n * Works with the new unified ClientRequest:signAndSendTransaction interface\n * Supports Solana, Bitcoin, and other non-EVM chains\n *\n * @param snapResponse - The response from the snap after transaction submission\n * @param trade - The non-evm trade or approval data\n * @param quoteResponse - The quote response containing trade details and metadata\n * @param selectedAccount - The selected account information\n * @returns The transaction metadata including non-EVM specific fields\n */\nexport const handleNonEvmTxResponse = (\n snapResponse:\n | string\n | { transactionId: string } // New unified interface response\n | { result: Record<string, string> }\n | { signature: string },\n trade: Trade,\n quoteResponse: Omit<QuoteResponse<Trade>, 'trade' | 'approval'> &\n QuoteMetadata,\n selectedAccount: AccountsControllerState['internalAccounts']['accounts'][string],\n): TransactionMeta & SolanaTransactionMeta => {\n const selectedAccountAddress = selectedAccount.address;\n const snapId = selectedAccount.metadata.snap?.id;\n let hash;\n // Handle different response formats\n if (typeof snapResponse === 'string') {\n hash = snapResponse;\n } else if (snapResponse && typeof snapResponse === 'object') {\n // Check for new unified interface response format first\n if ('transactionId' in snapResponse && snapResponse.transactionId) {\n hash = snapResponse.transactionId;\n } else if (\n 'result' in snapResponse &&\n snapResponse.result &&\n typeof snapResponse.result === 'object'\n ) {\n // Try to extract signature from common locations in response object\n hash =\n snapResponse.result.signature ||\n snapResponse.result.txid ||\n snapResponse.result.hash ||\n snapResponse.result.txHash;\n } else if (\n 'signature' in snapResponse &&\n snapResponse.signature &&\n typeof snapResponse.signature === 'string'\n ) {\n hash = snapResponse.signature;\n }\n }\n\n const isBridgeTx = isCrossChain(\n quoteResponse.quote.srcChainId,\n quoteResponse.quote.destChainId,\n );\n\n let hexChainId: Hex;\n try {\n hexChainId = formatChainIdToHex(quoteResponse.quote.srcChainId);\n } catch {\n hexChainId = '0x1';\n }\n // Extract the transaction data for storage\n const tradeData = extractTradeData(trade);\n\n // Create a transaction meta object with bridge-specific fields\n return {\n ...getTxMetaFields(quoteResponse),\n time: Date.now(),\n id: hash ?? uuid(),\n chainId: hexChainId,\n networkClientId: snapId ?? 'mainnet',\n txParams: { from: selectedAccountAddress, data: tradeData },\n type: isBridgeTx ? TransactionType.bridge : TransactionType.swap,\n status: TransactionStatus.submitted,\n hash, // Add the transaction signature as hash\n origin: snapId,\n // Add an explicit flag to mark this as a non-EVM transaction\n isSolana: true, // TODO deprecate this and use chainId to detect non-EVM chains\n isBridgeTx,\n };\n};\n\n/**\n * Submits the transaction to the snap using the new unified ClientRequest interface\n * Works for all non-EVM chains (Solana, BTC, Tron)\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 messenger - The BridgeStatusControllerMessenger instance\n * @param trade - The trade data (can be approval or main trade)\n * @param quoteResponse - The quote response containing metadata\n * @param selectedAccount - The account to submit the transaction for\n * @returns The transaction meta\n */\nexport const handleNonEvmTx = async (\n messenger: BridgeStatusControllerMessenger,\n trade: Trade,\n quoteResponse: QuoteResponse<Trade, Trade> & QuoteMetadata,\n selectedAccount: AccountsControllerState['internalAccounts']['accounts'][string],\n): Promise<TransactionMeta> => {\n if (!selectedAccount.metadata?.snap?.id) {\n throw new Error(\n 'Failed to submit cross-chain swap transaction: undefined snap id',\n );\n }\n\n const request = getClientRequest(\n trade,\n quoteResponse.quote.srcChainId,\n selectedAccount.id,\n selectedAccount.metadata?.snap?.id,\n quoteResponse.quote.srcAsset.assetId,\n quoteResponse.quote.destAsset.assetId,\n );\n const requestResponse = (await messenger.call(\n 'SnapController:handleRequest',\n request,\n )) as\n | string\n | { transactionId: string }\n | { result: Record<string, string> }\n | { signature: string };\n\n const txMeta = handleNonEvmTxResponse(\n requestResponse,\n trade,\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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snaps.d.cts","sourceRoot":"","sources":["../../src/utils/snaps.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,uBAAuB,EAAE,sCAAsC;AAC7E,OAAO,KAAK,EACV,aAAa,EACb,aAAa,EACb,KAAK,EACN,oCAAoC;
|
|
1
|
+
{"version":3,"file":"snaps.d.cts","sourceRoot":"","sources":["../../src/utils/snaps.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,uBAAuB,EAAE,sCAAsC;AAC7E,OAAO,KAAK,EACV,aAAa,EACb,aAAa,EACb,KAAK,EACN,oCAAoC;AASrC,OAAO,EAAE,cAAc,EAAE,oCAAoC;AAM7D,OAAO,KAAK,EAAE,eAAe,EAAE,yCAAyC;AACxE,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAO,wBAAwB;AAGvE,OAAO,KAAK,EACV,+BAA+B,EAC/B,qBAAqB,EACtB,qBAAiB;AAElB;;;;;;;;;;GAUG;AACH,eAAO,MAAM,8BAA8B,WACjC,MAAM,eACD,MAAM,SACZ,WAAW,aACP,MAAM,YACP,OAAO,MAAM,EAAE,OAAO,CAAC;;;;;;;;;;;;;;;CAmBlC,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,gBAAgB,UACpB,KAAK,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M,CAAC,CAAA;CAAE,GAClC;IAAE,SAAS,EAAE,MAAM,CAAA;CAAE,SAClB,KAAK,iBACG,KAAK,cAAc,KAAK,CAAC,EAAE,OAAO,GAAG,UAAU,CAAC,GAC7D,aAAa,mBACE,uBAAuB,CAAC,kBAAkB,CAAC,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,KAC/E,eAAe,GAAG,qBA6DpB,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,cAAc,sDAElB,KAAK,iBACG,cAAc,KAAK,EAAE,KAAK,CAAC,GAAG,aAAa,mBACzC,uBAAuB,CAAC,kBAAkB,CAAC,CAAC,UAAU,CAAC,CAAC,MAAM,CAAC,KAC/E,QAAQ,eAAe,CAkCzB,CAAC"}
|
package/dist/utils/snaps.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { extractTradeData, formatChainIdToCaip, formatChainIdToHex, isCrossChain, isTronTrade } from "@metamask/bridge-controller";
|
|
1
|
+
import { extractTradeData, formatChainIdToCaip, formatChainIdToHex, isCrossChain, isStellarTrade, isTronTrade } from "@metamask/bridge-controller";
|
|
2
2
|
import { SnapController } from "@metamask/snaps-controllers";
|
|
3
3
|
import { CHAIN_IDS, TransactionStatus, TransactionType } from "@metamask/transaction-controller";
|
|
4
4
|
import { v4 as uuid } from "uuid";
|
|
@@ -48,15 +48,20 @@ export const getClientRequest = (trade, srcChainId, accountId, snapId, sourceAss
|
|
|
48
48
|
const scope = formatChainIdToCaip(srcChainId);
|
|
49
49
|
const transaction = extractTradeData(trade);
|
|
50
50
|
let options;
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
51
|
+
// Only Stellar trades expect asset IDs in the request options. Passing them
|
|
52
|
+
// for other non-EVM chains (e.g. Bitcoin) breaks strict snap request
|
|
53
|
+
// validation and prevents the transaction from being broadcast.
|
|
54
|
+
if (isStellarTrade(trade)) {
|
|
55
|
+
if (sourceAssetId !== undefined || destAssetId !== undefined) {
|
|
56
|
+
options = {
|
|
57
|
+
...(sourceAssetId !== undefined && {
|
|
58
|
+
sourceAssetId,
|
|
59
|
+
}),
|
|
60
|
+
...(destAssetId !== undefined && {
|
|
61
|
+
destAssetId,
|
|
62
|
+
}),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
60
65
|
}
|
|
61
66
|
if (isTronTrade(trade)) {
|
|
62
67
|
// Tron trades need the visible flag and contract type to be included in the request options
|